3
W­E^Ý,  ã               @   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mZmZ ddl	m
Z
 ddlmZ yd dlZW n ek
r|   dZY nX G dd„ dƒZG dd	„ d	ƒZeZeZdS )
é    N)ÚFutureÚThreadPoolExecutoré   )ÚCurrentThreadExecutor)ÚLocalc               @   sD   e Zd ZdZi Zeƒ Z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.
    Fc             C   sJ   || _ |rd | _n4ytjƒ | _W n$ tk
rD   ttjdd ƒ| _Y nX d S )NÚmain_event_loop)Ú	awaitabler   ÚasyncioÚget_event_loopÚRuntimeErrorÚgetattrÚSyncToAsyncÚthreadlocal)Úselfr	   Zforce_new_loop© r   ú//tmp/pip-build-78s3knkw/asgiref/asgiref/sync.pyÚ__init__&   s    zAsyncToSync.__init__c             O   s(  yt jƒ }W n tk
r    Y nX |jƒ r2tdƒ‚tƒ }tjƒ }t| jdƒrV| jj	}nd }t
ƒ }|| j_	z’| jox| jjƒ sÆt jƒ }tdd�}	|	j| j|| j||||tjƒ ƒƒ}
|r¼|j|
ƒ |
jƒ  n2| jj| jj| j||||tjƒ ƒƒ |rø|j|ƒ W d t| jdƒ�r| j`	|�r|| j_	X |jƒ S )NznYou cannot use AsyncToSync in the same thread as an async event loop - just await the async function directly.Úcurrentr   )Úmax_workers)r
   r   r   Z
is_runningr   Ú	threadingÚcurrent_threadÚhasattrÚ	executorsr   r   r   Znew_event_loopr   ZsubmitÚ_run_event_loopÚ	main_wrapÚsysÚexc_infoZrun_until_futureÚresultZcall_soon_threadsafeZcreate_task)r   ÚargsÚkwargsZ
event_loopÚcall_resultÚsource_threadZold_current_executorZcurrent_executorÚloopZloop_executorZloop_futurer   r   r   Ú__call__5   sJ    




zAsyncToSync.__call__c             C   sT   t j|ƒ z|j|ƒ W dzt|dƒr4|j|jƒ ƒ W d|jƒ  t j| jƒ X X dS )zP
        Runs the given event loop (designed to be called in a thread).
        NÚshutdown_asyncgens)r
   Zset_event_loopZrun_until_completer   r%   Úcloser   )r   r#   Úcoror   r   r   r   v   s    

zAsyncToSync._run_event_loopc             C   s   t j| j|ƒ}t j|| jƒS )z*
        Include self for methods
        )Ú	functoolsÚpartialr$   Úupdate_wrapperr	   )r   ÚparentÚobjtypeÚfuncr   r   r   Ú__get__…   s    zAsyncToSync.__get__c       	      Ã   sª   t jƒ }|| j|< zˆyL|d rLy|d ‚W q^   | j||ŽI dH }Y q^X n| j||ŽI dH }W n, tk
rŒ } z|j|ƒ W Y dd}~X nX |j|ƒ W d| j|= X dS )zs
        Wraps the awaitable with something that puts the result into the
        result/exception future.
        r   N)r   Úget_current_taskÚ
launch_mapr	   Ú	ExceptionZset_exceptionZ
set_result)	r   r   r    r!   r"   r   Úcurrent_taskr   Úer   r   r   r   Œ   s    
zAsyncToSync.main_wrapN)F)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r0   r   r   r   r$   r   r.   r   r   r   r   r   r      s   
Ar   c               @   s€   e Zd ZdZdejkr8ejƒ Zej	e
eejd ƒd�ƒ i Zejƒ Ze
dd�Zddd„Zdd	„ Zd
d„ Zdd„ Zedd„ ƒZdS )r   aK  
    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.
    ZASGI_THREADS)r   r   Fc             C   s<   || _ || _tjj| _y|j| _W n tk
r6   Y nX d S )N)r-   Ú_thread_sensitiver
   Z
coroutinesZ_is_coroutineÚ__self__ÚAttributeError)r   r-   Zthread_sensitiver   r   r   r   Ç   s    
zSyncToAsync.__init__c       	      Ï   s¬   t jƒ }| jr,ttjdƒr$tjj}q0| j}nd }td k	rftj	ƒ }t
j| jf|ž|Ž}|j}|f}i }n| j}|j|t
j| j|| jƒ tjƒ |f|ž|Žƒ}t j|d d�I d H S )Nr   )Útimeout)r
   r   r8   r   r   r   r   Úsingle_thread_executorÚcontextvarsZcopy_contextr(   r)   r-   ÚrunZrun_in_executorÚthread_handlerr/   r   r   Úwait_for)	r   r   r    r#   ÚexecutorÚcontextÚchildr-   Úfuturer   r   r   r$   Ð   s0    
zSyncToAsync.__call__c             C   s   t j| j|ƒS )z*
        Include self for methods
        )r(   r)   r$   )r   r+   r,   r   r   r   r.   ö   s    zSyncToAsync.__get__c       	      O   s~   || j _tjƒ }tjj|ƒ|kr&d}n|| j|< d}z6|d r^y|d ‚W qh   |||ŽS n
|||ŽS W d|rx| j|= X dS )zE
        Wraps the sync application with exception handling.
        FTr   N)r   r   r   r   r   r0   Úget)	r   r#   Zsource_taskr   r-   r   r    r   Z
parent_setr   r   r   r?   ü   s    
zSyncToAsync.thread_handlerc               C   s:   y t tdƒrtjƒ S tjjƒ S W n tk
r4   dS X dS )zs
        Cross-version implementation of asyncio.current_task()

        Returns None if there is no task.
        r2   N)r   r
   r2   ZTaskr   r   r   r   r   r/     s    
zSyncToAsync.get_current_taskN)F)r4   r5   r6   r7   ÚosÚenvironr
   r   r#   Zset_default_executorr   Úintr0   r   Úlocalr   r<   r   r$   r.   r?   Ústaticmethodr/   r   r   r   r   r   ¥   s   


	& r   )r
   Zasyncio.coroutinesr(   rF   r   r   Úconcurrent.futuresr   r   Zcurrent_thread_executorr   rI   r   r=   ÚImportErrorr   r   Zsync_to_asyncZasync_to_syncr   r   r   r   Ú<module>   s$   
  