Format: application/x-python-code
⬇ Download File (13.4 KB)
   1  o
   2  
   3  -h�S�@s�UddlZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
   4  mZmZddl
   5  mZmZmZmZmZmZmZmZmZmZmZmZddlmZddlmZejdkreddl
   6  mZnddl mZersdd	l!m"Z"ed
   7  edefd�Z#ed
   8  �Z$ed�Z%dej&ddfdd�Z'e(ed�r�ej)Z)ej*Z*ee#ge#fe+d<nej)Z)de#de#fdd�Z*Gdd�d�Z,Gdd�dee$e%f�Z-Gdd�dee$e%f�Z.edd�de/deeee$eeee%ffee$ee%ffgee$e%fffdd ��Z0edd�d!eee$eeee%ffee$ee%ffde/dee$e%ffd"d ��Z0	d-dd�d!eeee$eeee%ffee$ee%ffde/deeeee$eeee%ffee$ee%ffgee$e%ffee$e%fffd#d �Z0ed$dd%�d&e/d'ed(deee$e%fgee$eeee%ffffd)d*��Z1ed$dd%�dee$e%fd&e/d'ed(dee$eeee%fffd+d*��Z1	d-d$dd%�deee$e%fd&e/d'ed(deeee$e%fgee$eeee%fffee$eeee%ffffd,d*�Z1dS).�N)�Future�ThreadPoolExecutor)�
   9  TYPE_CHECKING�Any�	Awaitable�Callable�	Coroutine�Dict�Generic�List�Optional�TypeVar�Union�overload�)�CurrentThreadExecutor)�Local)��
  10  )�	ParamSpec)�
  11  OptExcInfo�_F.)�bound�_P�_R�context�returnc	CsN|D]"}|�|�}z
  12  |��|kr|�|�Wqty$|�|�YqwdS�N)�get�set�LookupError)rZcvarZcvalue�r!�BC:\Users\shubh\Videos\agent\nova\Lib\site-packages\asgiref/sync.py�_restore_context,s
  13  
  14  ���r#�markcoroutinefunction�funccCstjj|_|Sr)�asyncio�
  15  coroutines�
  16  _is_coroutine)r%r!r!r"r$Cs
  17  c@s(eZdZdZdd�Zdd�Zdd�ZdS)	�ThreadSensitiveContextaYAsync context manager to manage context for thread sensitive mode
  18  
  19      This context manager controls which thread pool executor is used when in
  20      thread sensitive mode. By default, a single thread pool executor is shared
  21      within a process.
  22  
  23      The ThreadSensitiveContext() context manager may be used to specify a
  24      thread pool per context.
  25  
  26      This context manager is re-entrant, so only the outer-most call to
  27      ThreadSensitiveContext will set the context.
  28  
  29      Usage:
  30  
  31      >>> import time
  32      >>> async with ThreadSensitiveContext():
  33      ...     await sync_to_async(time.sleep, 1)()
  34      cCs
  35  d|_dSr)�token��selfr!r!r"�__init__\s
  36  zThreadSensitiveContext.__init__c�s6�ztj��W|Stytj�|�|_Y|Swr)�SyncToAsync�thread_sensitive_contextrr rr*r+r!r!r"�
  37  __aenter___s���z!ThreadSensitiveContext.__aenter__c�s8�|jsdStj�|d�}|r|��tj�|j�dSr)r*r.�context_to_thread_executor�pop�shutdownr/�reset)r,�exc�value�tb�executorr!r!r"�	__aexit__gs�z ThreadSensitiveContext.__aexit__N)�__name__�
  38  __module__�__qualname__�__doc__r-r0r9r!r!r!r"r)Hs
  39  r)c@s�eZdZUdZe�Zded<iZded<	d dee	e
  40  eeee
  41  ffe	e
  42  ee
  43  ffdefd	d
  44  �Zde
  45  jde
  46  jd
  47  e
  48  fdd�Zdd�Zdeded
  49  e	e
  50  e
  51  ffdd�Zdddddddeejde
  52  jde
  53  jd
  54  dfdd�ZdS)!�AsyncToSynca�
  55      Utility class which turns an awaitable that only works on the thread with
  56      the event loop into a synchronous callable that works in a subthread.
  57  
  58      If the call stack contains an async loop, the code runs there.
  59      Otherwise, the code runs in a new loop in a new thread.
  60  
  61      Either way, this thread then pauses and waits to run any thread_sensitive
  62      code called from further down the call stack using SyncToAsync, before
  63      finally exiting once the async task returns.
  64      r�	executorsz6Dict[asyncio.AbstractEventLoop, CurrentThreadExecutor]�loop_thread_executorsF�	awaitable�force_new_loopcCs�t|�rt|�stt|d|��stjddd�||_z|jj|_Wn	ty*Ynw||_d|_	zt
  65  ��|_	WdStyCYdSw)N�__call__z4async_to_sync was passed a non-async-marked callable�)�
  66  stacklevel)
  67  �callable�iscoroutinefunction�getattr�warnings�warnrA�__self__�AttributeErrorrB�main_event_loopr&�get_running_loop�RuntimeError)r,rArBr!r!r"r-�s*�����zAsyncToSync.__init__�args�kwargsrc	Os�d}|js|jsttjdd�}|r|t��krttjdd�|_zt��}Wn	t	y.Yn	w|�
  68  �r7t	d��t�}t|jdd�}t
  69  �}||j_t��g}	ttjdd�}
  70  d}zb|j|t��|
  71  |	g|�Ri|��}|jrp|j�
  72  �s�t��}||j|<tdd�}
  73  |
  74  �|j||�}|r�|�|�|��n|j�|jj|�|r�|�|�W|dur�|j|=t|	d	�||j_|��S|dur�|j|=t|	d	�||j_w)
  75  NT�main_event_loop_pidrMznYou cannot use AsyncToSync in the same thread as an async event loop - just await the async function directly.�current�task_contextr��max_workersr)rBrMrHr.�threadlocal�os�getpidr&rNrO�
  76  is_runningrr?rrS�contextvars�copy_context�	main_wrap�sys�exc_info�new_event_loopr@r�submit�_run_event_loopZrun_until_future�result�call_soon_threadsafe�create_taskr#)r,rPrQ�__traceback_hide__rRZ
  77  event_loop�call_resultZold_executorZcurrent_executorrrT�looprAZ
  78  loop_executorZloop_futurer!r!r"rC�sz����
  79  ���	
  80  
  81  �
  82  
  83  �
  84  ��
  85  zAsyncToSync.__call__cs�t�|�zm|�|�Wz[t�|���D]}|��q�fdd�}|�|���D]}|��r0q)|��durA|�d|��|d��q)t|d�r[|�|�	��W|�
  86  �t�|j�dSW|�
  87  �t�|j�dS|�
  88  �t�|j�wzYt�|���D]}|��q{�fdd�}|�|���D]}|��r�q�|��dur�|�d|��|d��q�t|d�r�|�|�	��W|�
  89  �t�|j�wW|�
  90  �t�|j�w|�
  91  �t�|j�w)zP
  92          Runs the given event loop (designed to be called in a thread).
  93          c�s�tj�ddi�IdHdS)N�return_exceptionsT)r&�gatherr!��tasksr!r"rjs�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�	cancelledrn�call_exception_handler�hasattrrp�closerM)r,rh�corororjr!rkr"rbsn
  94  
  95  
  96  ���
  97  ���
  98  
  99  ���
 100  ��zAsyncToSync._run_event_loop�parent�objtypecC�t�|j|�}t�||j�S�z*
 101          Include self for methods
 102          )�	functools�partialrC�update_wrapperrA�r,rzr{r%r!r!r"�__get__$szAsyncToSync.__get__rgz
 103  Future[_R]r_rrTz!Optional[List[asyncio.Task[Any]]]rNc
 104  �s �d}|dur
 105  t|d�t��}|dur|dur|�|�z]z*|dr=z|d�ty<|j|i|��IdH}	Ynw|j|i|��IdH}	Wnty`}
 106  z|�|
 107  �WYd}
 108  ~
 109  n
 110  d}
 111  ~
 112  ww|�|	�W|durt|durt|�|�t	�
 113  �|d<dS|dur�|dur�|�|�t	�
 114  �|d<w)zs
 115          Wraps the awaitable with something that puts the result into the
 116          result/exception future.
 117          TNrr)r#r&�current_task�append�
 118  BaseExceptionrA�
 119  set_exception�
 120  set_result�remover[r\)r,rgr_rTrrPrQrfr�rc�er!r!r"r]+s8�
 121  ����
 122  �
 123  �
 124  zAsyncToSync.main_wrap)F)r:r;r<r=rr?�__annotations__r@rrrrrrr�boolr-rPrQrCrbr�rr[�Contextr]r!r!r!r"r>qs@
 125  ����
 126  �\$�������r>c@s�eZdZUdZe��Zedd�Ze	�
 127  d�Zded<e	�
 128  d�Z
 129  ded<e��Zded	<	
 130  	ddeeefd
 131  ededddfdd�Zdejdejdefdd�Zdededeeeeeefffdd�Zdd�ZdS)r.a
 132      Utility class which turns a synchronous callable into an awaitable that
 133      runs in a threadpool. It also sets a threadlocal inside the thread so
 134      calls to AsyncToSync can escape it.
 135  
 136      If thread_sensitive is passed, the code will run in the same thread as any
 137      outer code. This is needed for underlying Python code that is not
 138      threadsafe (for example, code which handles SQLite database connections).
 139  
 140      If the outermost program is async (i.e. SyncToAsync is outermost), then
 141      this will be a dedicated single sub-thread that all sync code runs in,
 142      one after the other. If the outermost program is sync (i.e. AsyncToSync is
 143      outermost), this will just be the main thread. This is achieved by idling
 144      with a CurrentThreadExecutor while AsyncToSync is blocking its sync parent,
 145      rather than just blocking.
 146  
 147      If executor is passed in, that will be used instead of the loop's default executor.
 148      In order to pass in an executor, thread_sensitive must be set to False, otherwise
 149      a TypeError will be raised.
 150      rrUr/z.contextvars.ContextVar[ThreadSensitiveContext]�deadlock_contextzcontextvars.ContextVar[bool]zEweakref.WeakKeyDictionary[ThreadSensitiveContext, ThreadPoolExecutor]r1TNr%�thread_sensitiver8rrcCs�t|�rt|�stt|d|��rtd��||_t�||�||_t|�|r.|dur.td��||_	z|j
 151  |_
 152  WdStyBYdSw)NrCz4sync_to_async can only be applied to sync functions.z6executor must not be set when thread_sensitive is True)rFrGrH�	TypeErrorr%r~r��_thread_sensitiver$�	_executorrKrL)r,r%r�r8r!r!r"r-�s&����zSyncToAsync.__init__rPrQc�s��d}t��}|jrVttjdd�}|r|}nC|j�d�r7|j��}||jvr,|j|}n-t	dd�}||j|<n"|tj
 153  vrBtj
 154  |}n|j�d�rLtd��|j
 155  }|j�d�n|j}t��}tj|jg|�Ri|��}	|j}
 156  g}|�|t�|j|t��||
 157  |	��}ziz
 158  t�|�IdH}
 159  WnDtjy�d}z|d}|��z	|IdHd}Wn
 160  tjy�YnwWn	ty�Ynw|��r‚|r�|��|IdH}
 161  YnwWt|�|j�d�|
 162  SWt|�|j�d�|
 163  St|�|j�d�w)NTrSrrUFz9Single thread executor already being used, would deadlockr) r&rNr�rHr>r?r/rr1rr@r�rO�single_thread_executorrr�r[r\r~rr%�run�run_in_executor�thread_handlerr^r_�shield�CancelledErrorrt�
 164  IndexError�doner#)r,rPrQrfrh�current_thread_executorr8r/r�childr%rTZ	exec_coro�retZ
 165  cancel_parentror!r!r"rC�s��
 166  
 167  
 168  
 169  ���
 170  �������zSyncToAsync.__call__rzr{cCr|r})r~rrCr�r%r�r!r!r"r��szSyncToAsync.__get__cOs`d}||j_t��|j_||j_|dr)z|d�ty(||i|��YSw||i|��S)zE
 171          Wraps the sync application with exception handling.
 172          Tr)rWrMrXrYrRrTr�)r,rhr_rTr%rPrQrfr!r!r"r��s�zSyncToAsync.thread_handler)TN)r:r;r<r=�	threading�localrWrr�r[�
 173  ContextVarr/r�r��weakref�WeakKeyDictionaryr1rrrr�rr-rPrQrCrrr�r�r!r!r!r"r.Vs>
 174  
 175  
 176  ��
 177  ��
 178  ���
 179  �P��
 180  �	r.F�rBrBcC�dSrr!r�r!r!r"�
 181  async_to_sync
 182  sr�rAcCr�rr!�rArBr!r!r"r�s	cs |dur
 183  �fdd�St|�d�S)Ncst|�d�S)Nr��r>��fr�r!r"�<lambda>5s�zasync_to_sync.<locals>.<lambda>r�r�r�r!r�r"r�$s�T�r�r8r�r8rcCr�rr!r�r!r!r"�
 184  sync_to_async?sr�cCr�rr!�r%r�r8r!r!r"r�Hscs$|dur��fdd�St|��d�S)Ncst|��d�S)Nr��r.r��r8r�r!r"r�\s
 185  �zsync_to_async.<locals>.<lambda>r�r�r�r!r�r"r�Rs	�r)2r&Zasyncio.coroutinesr[r~�inspectrXr^r�rIr��concurrent.futuresrr�typingrrrrrr	r
 186  rrr
 187  rrr�rr�r�version_inforZtyping_extensionsZ	_typeshedrrrrr�r#rwrGr$r�r)r>r.r�r�r�r!r!r!r"�<module>s�
 188  8
 189  
 190  )f8��*
 191  ���
 192  �����
 193  ��������	*
 194  ��
 195  ��
 196  ����&��
 197  ����
 198  �����&���