o
    ".hP                     @   s  d dl Z d dlZ d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
mZmZ d dlmZmZmZmZmZ ddlmZ ddlmZ dd Zd	ed
efddZd	ed
efddZd	ed
efddZG dd dZG dd dZG dd dZeZe			d d	ddeded d
eedef gef fddZ e		d!d	edef deded d
efddZ 			d ddZ dS )"    N)FutureThreadPoolExecutor)AnyCallableDictOptionaloverload   )CurrentThreadExecutor)Localc              	   C   sV   | D ]&}z|  |  |kr||  | W q ty(   ||  | Y qw d S N)getsetLookupError)contextcvar r   K/var/www/supernova/superenvnew/lib/python3.10/site-packages/asgiref/sync.py_restore_context   s   r   funcreturnc                 C   s"   t tdr
t| S tjj| _| S Nmarkcoroutinefunction)hasattrinspectr   asyncio
coroutines_is_coroutiner   r   r   r   r   $   s   


r   c                 C   s   t tdr
t| S t| S r   )r   r   iscoroutinefunctionr   r   r   r   r   r   ,   s   


r   c                 C   sR   t jdkr	t| S t| r| j} t| st| tjr%| j	} t| tjst| S )N)      )
sysversion_infor   r   ismethod__func__
isinstance	functoolspartialr   r   r   r   r   _iscoroutinefunction_or_partial3   s   


r)   c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	ThreadSensitiveContextai  Async context manager to manage context for thread sensitive mode

    This context manager controls which thread pool executor is used when in
    thread sensitive mode. By default, a single thread pool executor is shared
    within a process.

    In Python 3.7+, the ThreadSensitiveContext() context manager may be used to
    specify a thread pool per context.

    This context manager is re-entrant, so only the outer-most call to
    ThreadSensitiveContext will set the context.

    Usage:

    >>> import time
    >>> async with ThreadSensitiveContext():
    ...     await sync_to_async(time.sleep, 1)()
    c                 C   s
   d | _ d S r   )tokenselfr   r   r   __init__V   s   
zThreadSensitiveContext.__init__c                    s6   zt j  W | S  ty   t j| | _Y | S w r   )SyncToAsyncthread_sensitive_contextr   r   r   r+   r,   r   r   r   
__aenter__Y   s   z!ThreadSensitiveContext.__aenter__c                    s8   | j sd S tj| d }|r|  tj| j  d S r   )r+   r/   context_to_thread_executorpopshutdownr0   reset)r-   excvaluetbexecutorr   r   r   	__aexit__a   s   z ThreadSensitiveContext.__aexit__N)__name__
__module____qualname____doc__r.   r1   r:   r   r   r   r   r*   B   s
    r*   c                   @   sZ   e Zd ZU dZi Zded< e Zi Zded< dddZ	d	d
 Z
dd Zdd Zdd ZdS )AsyncToSynca  
    Utility class which turns an awaitable that only works on the thread with
    the event loop into a synchronous callable that works in a subthread.

    If the call stack contains an async loop, the code runs there.
    Otherwise, the code runs in a new loop in a new thread.

    Either way, this thread then pauses and waits to run any thread_sensitive
    code called from further down the call stack using SyncToAsync, before
    finally exiting once the async task returns.
    z,Dict[asyncio.Task[object], threading.Thread]
launch_mapz6Dict[asyncio.AbstractEventLoop, CurrentThreadExecutor]loop_thread_executorsFc                 C   s   t |rt|stt|d|stjddd || _z| jj| _W n	 ty*   Y nw |r2d | _d S zt	
 | _W d S  tya   ttjdd }|r[|t kr[ttjdd | _Y d S d | _Y d S w )N__call__z4async_to_sync was passed a non-async-marked callable   )
stacklevelmain_event_loop_pidmain_event_loop)callabler)   getattrwarningswarn	awaitable__self__AttributeErrorrF   r   get_running_loopRuntimeErrorr/   threadlocalosgetpid)r-   rK   force_new_looprE   r   r   r   r.      s<   

zAsyncToSync.__init__c              	   O   s  zt  }W n	 ty   Y n	w | rtdt g}t }t }t	| j
dr/| j
j}nd }t }|| j
_d }	zh| ||||t |}
| jrO| j sqt  }	|| j|	< tdd}|| j|	|
}|rl|| |  n| j| jj|
 |r|| W |	d ur| j|	= t	| j
dr| j
`|r|| j
_t|d  | S |	d ur| j|	= t	| j
dr| j
`|r|| j
_t|d  w )NznYou cannot use AsyncToSync in the same thread as an async event loop - just await the async function directly.currentr	   max_workersr   )r   rN   rO   
is_runningcontextvarscopy_contextr   	threadingcurrent_threadr   	executorsrT   r
   	main_wrapr"   exc_inforF   new_event_looprA   r   submit_run_event_looprun_until_futureresultcall_soon_threadsafecreate_taskr   )r-   argskwargs
event_loopr   call_resultsource_threadold_current_executorcurrent_executorlooprK   loop_executorloop_futurer   r   r   rB      sj   






zAsyncToSync.__call__c                    s  t | zm|| W z[t |  D ]}|  q fdd}||   D ]}| r0q)| durA|d| |d q)t|dr[||	  W |
  t | j dS W |
  t | j dS |
  t | j w zYt |  D ]}|  q{ fdd}||   D ]}| rq| dur|d| |d qt|dr||	  W |
  t | j w W |
  t | j w |
  t | j w )zP
        Runs the given event loop (designed to be called in a thread).
        c                      s   t j ddiI d H  d S )Nreturn_exceptionsT)r   gatherr   tasksr   r   rq     s   z+AsyncToSync._run_event_loop.<locals>.gatherNz(unhandled exception during loop shutdown)message	exceptiontaskshutdown_asyncgens)r   set_event_looprun_until_complete	all_taskscancel	cancelledru   call_exception_handlerr   rw   closerF   )r-   rm   cororv   rq   r   rr   r   ra      sn   






zAsyncToSync._run_event_loopc                 C      t | j|}t || jS z*
        Include self for methods
        )r'   r(   rB   update_wrapperrK   r-   parentobjtyper   r   r   r   __get__     zAsyncToSync.__get__c           
   
      s  |durt |d  t }|| j|< zaz*|d r3z|d  ty2   | j|i |I dH }Y nw | j|i |I dH }W n tyV }	 z||	 W Y d}	~	nd}	~	ww || W | j|= t	 |d< dS W | j|= t	 |d< dS | j|= t	 |d< w )zs
        Wraps the awaitable with something that puts the result into the
        result/exception future.
        Nr   r	   )
r   r/   get_current_taskr@   BaseExceptionrK   set_exception
set_resultrX   rY   )
r-   rf   rg   ri   rj   r^   r   current_taskrc   er   r   r   r]     s4   
zAsyncToSync.main_wrapN)F)r;   r<   r=   r>   r@   __annotations__r   r\   rA   r.   rB   ra   r   r]   r   r   r   r   r?   k   s   
 
&I$r?   c                	   @   s   e Zd ZU dZi Zded< e Ze	ddZ
edZded< edZd	ed< e Zd
ed< 		ddedef deded ddfddZdd Zdd Zdd Zedd ZdS )r/   a  
    Utility class which turns a synchronous callable into an awaitable that
    runs in a threadpool. It also sets a threadlocal inside the thread so
    calls to AsyncToSync can escape it.

    If thread_sensitive is passed, the code will run in the same thread as any
    outer code. This is needed for underlying Python code that is not
    threadsafe (for example, code which handles SQLite database connections).

    If the outermost program is async (i.e. SyncToAsync is outermost), then
    this will be a dedicated single sub-thread that all sync code runs in,
    one after the other. If the outermost program is sync (i.e. AsyncToSync is
    outermost), this will just be the main thread. This is achieved by idling
    with a CurrentThreadExecutor while AsyncToSync is blocking its sync parent,
    rather than just blocking.

    If executor is passed in, that will be used instead of the loop's default executor.
    In order to pass in an executor, thread_sensitive must be set to False, otherwise
    a TypeError will be raised.
    z,Dict[threading.Thread, asyncio.Task[object]]r@   r	   rU   r0   zcontextvars.ContextVar[str]deadlock_contextzcontextvars.ContextVar[bool]z5weakref.WeakKeyDictionary[object, ThreadPoolExecutor]r2   TNr   .thread_sensitiver9   r   r   c                 C   s   t |rt|stt|d|rtd|| _t| | || _t|  |r.|d ur.td|| _	z|j
| _
W d S  tyB   Y d S w )NrB   z4sync_to_async can only be applied to sync functions.z6executor must not be set when thread_sensitive is True)rG   r)   rH   	TypeErrorr   r'   r   _thread_sensitiver   	_executorrL   rM   )r-   r   r   r9   r   r   r   r.   n  s&   zSyncToAsync.__init__c              	      sv  t  }| jr\ttjdrtjj}nL| jr7| jd r7| j }|| j	v r,| j	| }n3t
dd}|| j	|< n(|tjv rBtj| }n| jrO| jdrOtd| j}| jr[| jd n| j}t }tj| jg|R i |}|j}|f}i }z3||tj| j||  t |g|R i |}	t j|	d dI d H }
W t| | jr| jd |
S t| | jr| jd w w )NrT   r	   rU   Fz9Single thread executor already being used, would deadlockT)timeout)r   rN   r   r   r?   r\   rT   r0   r   r2   r   rA   r   rO   single_thread_executorr   r   rX   rY   r'   r(   r   runrun_in_executorthread_handlerr   r"   r^   wait_forr   )r-   rf   rg   rm   r9   r0   r   childr   futureretr   r   r   rB     sj   




zSyncToAsync.__call__c                 C   r   r   )r'   r(   rB   r   r   r   r   r   r   r     r   zSyncToAsync.__get__c           	      O   s   || j _t | j _t }tj	||krd}n|| j|< d}z0|d rBz|d  t
yA   ||i | Y W |r@| j|= S S w ||i |W |rP| j|= S S |rW| j|= w )zE
        Wraps the sync application with exception handling.
        FTr	   )rP   rF   rQ   rR   rE   rZ   r[   r?   r@   r   r   )	r-   rm   source_taskr^   r   rf   rg   r[   
parent_setr   r   r   r     s,   



zSyncToAsync.thread_handlerc                   C   s    zt  W S  ty   Y dS w )zi
        Implementation of asyncio.current_task()
        that returns None if there is no task.
        N)r   r   rO   r   r   r   r   r     s
   
zSyncToAsync.get_current_taskTN)r;   r<   r=   r>   r@   r   rZ   localrP   r   r   rX   
ContextVarr0   r   weakrefWeakKeyDictionaryr2   r   r   boolr   r.   rB   r   r   staticmethodr   r   r   r   r   r/   =  s:   
 



C!r/   Tr   r9   r   .c                 C      d S r   r   r   r   r9   r   r   r   sync_to_async     r   c                 C   r   r   r   r   r   r   r   r   
  r   c                    s$   | d u r fddS t |  dS )Nc                    s   t |  dS )Nr   r9   r/   )fr9   r   r   r   <lambda>  s
    zsync_to_async.<locals>.<lambda>r   r   r   r   r   r   r     s   )NTNr   )!r   asyncio.coroutinesrX   r'   r   rQ   r"   rZ   rI   r   concurrent.futuresr   r   typingr   r   r   r   r   current_thread_executorr
   r   r   r   r   r   r   r)   r*   r?   r/   async_to_syncr   r   r   r   r   <module>   sj    ) S B
	