U
    ڲgS                     @   s  U 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mZmZmZmZmZmZmZ ddlmZ ddlmZ ejdkrd dlmZ nd dl mZ erd d	l!m"Z" ed
edef dZ#edZ$edZ%ej&ddddZ'e(edrHej)Z)ej*Z*ee#ge#f e+d< ne j)Z)e#e#dddZ*G dd dZ,G dd dee$e%f Z-G dd dee$e%f Z.edde/eeee$eeee%f f ee$ee% f f gee$e%f f dddZ0eddeee$eeee%f f ee$ee% f f e/ee$e%f d d!dZ0d,ddeeee$eeee%f f ee$ee% f f  e/eeeee$eeee%f f ee$ee% f f gee$e%f f ee$e%f f d d"dZ0ed#dd$e/ed% eee$e%f gee$eeee%f f f d&d'd(Z1ed#dd$ee$e%f e/ed% ee$eeee%f f d)d*d(Z1d-d#dd$eee$e%f  e/ed% eeee$e%f gee$eeee%f f f ee$eeee%f f f d)d+d(Z1dS ).    N)FutureThreadPoolExecutor)TYPE_CHECKINGAny	AwaitableCallable	CoroutineDictGenericListOptionalTypeVarUnionoverload   )CurrentThreadExecutor)Local)   
   )	ParamSpec)
OptExcInfo_F.)bound_P_R)contextreturnc              	   C   sR   | D ]H}|  |}z|  |kr*|| W q tk
rJ   || Y qX qd S N)getsetLookupError)r   ZcvarZcvalue r!   0/tmp/pip-unpacked-wheel-hay1n6u8/asgiref/sync.py_restore_context,   s    
r#   markcoroutinefunction)funcr   c                 C   s   t jj| _| S r   )asyncioZ
coroutinesZ_is_coroutine)r%   r!   r!   r"   r$   C   s    
c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	ThreadSensitiveContextaY  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.

    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__\   s    zThreadSensitiveContext.__init__c                    s6   zt j  W n" tk
r0   t j| | _Y nX | S r   )SyncToAsyncthread_sensitive_contextr   r    r   r(   r)   r!   r!   r"   
__aenter___   s
    z!ThreadSensitiveContext.__aenter__c                    s6   | j s
d S tj| d }|r$|  tj| j  d S r   )r(   r,   context_to_thread_executorpopshutdownr-   reset)r*   excvaluetbexecutorr!   r!   r"   	__aexit__g   s    z ThreadSensitiveContext.__aexit__N)__name__
__module____qualname____doc__r+   r.   r7   r!   r!   r!   r"   r'   H   s   r'   c                   @   s   e Zd ZU dZe Zded< i Zded< dee	e
eeeef f e	e
ee f f eddd	Ze
je
jed
ddZdd Zeee	e
ef dddZdddeej e
je
jdd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.
    r   	executorsz6Dict[asyncio.AbstractEventLoop, CurrentThreadExecutor]loop_thread_executorsF	awaitableforce_new_loopc                 C   s   t |r t|s.tt|d|s.tjddd || _z| jj| _W n tk
rV   Y nX || _d | _	zt
 | _	W n tk
r   Y nX d S )N__call__z4async_to_sync was passed a non-async-marked callable   )
stacklevel)callableiscoroutinefunctiongetattrwarningswarnr@   __self__AttributeErrorrA   main_event_loopr&   get_running_loopRuntimeError)r*   r@   rA   r!   r!   r"   r+      s(     zAsyncToSync.__init__argskwargsr   c              	   O   sz  d}| j s>| js>ttjdd }|r>|t kr>ttjdd | _zt }W n t	k
r^   Y nX |
 rpt	dt }t| jdd }t }|| j_t g}	ttjdd }
d }z| j|t |
|	f||}| jr| j
 s$t }|| j|< tdd	}|| j||}|r|| |  n"| j| jj| |rF|| W 5 |d k	r\| j|= t|	d  || j_X | S )
NTmain_event_loop_pidrL   znYou cannot use AsyncToSync in the same thread as an async event loop - just await the async function directly.currenttask_contextr   r   max_workers)rA   rL   rG   r,   threadlocalosgetpidr&   rM   rN   Z
is_runningr   r=   r   rS   contextvarscopy_contextr>   r#   	main_wrapsysexc_infoZnew_event_loopr   Zsubmit_run_event_loopZrun_until_futureresultZcall_soon_threadsafeZcreate_task)r*   rP   rQ   __traceback_hide__rR   Z
event_loopcall_resultZold_executorZcurrent_executorr   rT   loopr@   Zloop_executorZloop_futurer!   r!   r"   rB      s|        
	

  

 

zAsyncToSync.__call__c                    s   t | z|| W 5 zt |  D ]}|  q* fdd}||   D ]0}| rbqT| dk	rT|	d| |d qTt
|dr||  W 5 |  t | j X X dS )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 )NZreturn_exceptionsT)r&   gatherr!   Ztasksr!   r"   rd     s    z+AsyncToSync._run_event_loop.<locals>.gatherNz(unhandled exception during loop shutdown)message	exceptiontaskshutdown_asyncgens)r&   Zset_event_loopcloserL   Z	all_taskscancelZrun_until_completeZ	cancelledrg   Zcall_exception_handlerhasattrri   )r*   rc   cororh   rd   r!   re   r"   r_      s.    



zAsyncToSync._run_event_loopparentobjtyper   c                 C   s   t | j|}t || jS z*
        Include self for methods
        )	functoolspartialrB   update_wrapperr@   r*   ro   rp   r%   r!   r!   r"   __get__$  s    zAsyncToSync.__get__z
Future[_R]r   z!Optional[List[asyncio.Task[Any]]]N)rb   r^   rT   r   rP   rQ   r   c              
      s   d}|dk	rt |d  t }|dk	r:|dk	r:|| zzT|d r|z|d W q tk
rx   | j||I dH }	Y qX n| j||I dH }	W n, tk
r }
 z|	|
 W 5 d}
~
X Y nX |
|	 W 5 |dk	r|dk	r|| t |d< X dS )zs
        Wraps the awaitable with something that puts the result into the
        result/exception future.
        TNr   r   )r#   r&   current_taskappendremoverZ   r[   BaseExceptionr@   Zset_exceptionZ
set_result)r*   rb   r^   rT   r   rP   rQ   ra   rw   r`   er!   r!   r"   r\   +  s&    

zAsyncToSync.main_wrap)F)r8   r9   r:   r;   r   r=   __annotations__r>   r   r   r   r   r   r   r   boolr+   rP   rQ   rB   r_   rv   r   rZ   Contextr\   r!   r!   r!   r"   r<   q   s.   
 \$	r<   c                   @   s   e Zd ZU dZe ZeddZe	
dZded< e	
dZded< e Zded	< deeef eed ddddZejejedddZeeeeeeeef f dddZ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.
    r   rU   r-   z.contextvars.ContextVar[ThreadSensitiveContext]deadlock_contextzcontextvars.ContextVar[bool]zEweakref.WeakKeyDictionary[ThreadSensitiveContext, ThreadPoolExecutor]r/   TNr   r%   thread_sensitiver6   r   c                 C   s   t |r t|s tt|d|r(td|| _t| | || _t|  |r\|d k	r\td|| _	z|j
| _
W n tk
r   Y nX d S )NrB   z4sync_to_async can only be applied to sync functions.z6executor must not be set when thread_sensitive is True)rE   rF   rG   	TypeErrorr%   rr   rt   _thread_sensitiver$   	_executorrJ   rK   )r*   r%   r   r6   r!   r!   r"   r+     s$    zSyncToAsync.__init__rO   c                    s  d}t  }| jrttjdd }|r*|}q| jd rl| j }|| jkrV| j| }qt	dd}|| j|< q|tj
krtj
| }q| jdrtdq| j}| jd n| j}t }tj| jf||}	|j}
g }||t| j|t ||
|	}zzt |I d H }W n t jk
r   d}z@|d }|  z|I d H  d}W n t jk
rd   Y nX W n tk
r~   Y nX | r |r|  |I d H }Y nX W 5 t| | jd X |S )NTrS   r   rU   Fz9Single thread executor already being used, would deadlockr   ) r&   rM   r   rG   r<   r=   r-   r   r/   r   r>   r   rN   single_thread_executorr   r   rZ   r[   rr   rs   r%   runZrun_in_executorthread_handlerr]   r^   r#   ZshieldZCancelledErrorrk   
IndexErrordone)r*   rP   rQ   ra   rc   current_thread_executorr6   r-   r   childr%   rT   Z	exec_cororetZcancel_parentrh   r!   r!   r"   rB     st    






zSyncToAsync.__call__rn   c                 C   s   t | j|}t || jS rq   )rr   rs   rB   rt   r%   ru   r!   r!   r"   rv     s    zSyncToAsync.__get__c                 O   sd   d}|| j _t | j _|| j _|d rVz|d W q` tk
rR   ||| Y S X n
|||S dS )zE
        Wraps the sync application with exception handling.
        Tr   N)rW   rL   rX   rY   rR   rT   rz   )r*   rc   r^   rT   r%   rP   rQ   ra   r!   r!   r"   r     s    zSyncToAsync.thread_handler)TN)r8   r9   r:   r;   	threadinglocalrW   r   r   rZ   Z
ContextVarr-   r|   r   weakrefWeakKeyDictionaryr/   r   r   r   r}   r   r+   rP   rQ   rB   r   r   rv   r   r!   r!   r!   r"   r,   V  s0   



  
Q 	r,   FrA   )rA   r   c                 C   s   d S r   r!   r   r!   r!   r"   async_to_sync  s    r   )r@   rA   r   c                C   s   d S r   r!   r?   r!   r!   r"   r     s    	c                   s    | d kr fddS t |  dS )Nc                    s   t |  dS )Nr   r<   fr   r!   r"   <lambda>5  s   zasync_to_sync.<locals>.<lambda>r   r   r?   r!   r   r"   r   $  s    Tr   r6   r   )r   r6   r   c                 C   s   d S r   r!   r   r!   r!   r"   sync_to_async?  s    r   r   c                C   s   d S r   r!   r%   r   r6   r!   r!   r"   r   H  s    c                   s$   | d kr fddS t |  dS )Nc                    s   t |  dS )Nr   r,   r   r6   r   r!   r"   r   \  s   zsync_to_async.<locals>.<lambda>r   r   r   r!   r   r"   r   R  s    	)N)N)2r&   Zasyncio.coroutinesrZ   rr   inspectrX   r]   r   rH   r   concurrent.futuresr   r   typingr   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   version_infor   Ztyping_extensionsZ	_typeshedr   r   r   r   r~   r#   rl   rF   r$   r|   r'   r<   r,   r}   r   r   r!   r!   r!   r"   <module>   s    8
) f 8*


 *

&

 &