Format: application/x-python-code
⬇ Download File (16.8 KB)
   1  o
   2  
   3  ;'hFD�@s�ddlmZddlZddlmZmZmZddlmZddl	m
   4  Z
   5  mZmZddl
   6  mZmZddlmZddlmZmZmZdd	lmZdd
   7  lmZmZmZmZmZddlmZdd
   8  l m!Z!m"Z"m#Z#ddl$m%Z%ddl&m'Z'm(Z(ddl)m*Z*ddl+m,Z,ej-dkr�ddlm.Z.m/Z/nddl0m.Z.m/Z/ed�Z1eddd�Z2e.d�Z3d6dd�Z4d7d!d"�Z5Gd#d$�d$ee2e�Z6Gd%d&�d&e,�Z7Gd'd(�d(�Z8eGd)d*�d*��Z9e	d8d9d1d2��Z:d:d4d5�Z;dS);�)�annotationsN)�	Awaitable�Callable�	Generator)�Future)�AbstractAsyncContextManager�AbstractContextManager�contextmanager)�	dataclass�field)�isawaitable)�Lock�Thread�	get_ident)�
   9  TracebackType)�Any�Generic�TypeVar�cast�overload�)�
  10  _eventloop)�get_async_backend�get_cancelled_exc_class�threadlocals)�Event)�CancelScope�create_task_group)�AsyncBackend)�
  11  TaskStatus)��)�TypeVarTuple�Unpack�T_Retval�T_coT)�	covariant�PosArgsT�func�1Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]]�args�Unpack[PosArgsT]�returncG�:ztj}tj}Wntytd�d�w|j|||d�S)z�
  12      Call a coroutine function from a worker thread.
  13  
  14      :param func: a coroutine function
  15      :param args: positional arguments for the callable
  16      :return: the return value of the coroutine function
  17  
  18      �9This function can only be run from an AnyIO worker threadN��token)r�current_async_backend�
  19  current_token�AttributeError�RuntimeErrorZrun_async_from_thread�r(r*�
  20  async_backendr0�r7�GC:\Users\shubh\Videos\agent\nova\Lib\site-packages\anyio/from_thread.py�run(�
  21  ���r9�&Callable[[Unpack[PosArgsT]], T_Retval]cGr-)z�
  22      Call a function in the event loop thread from a worker thread.
  23  
  24      :param func: a callable
  25      :param args: positional arguments for the callable
  26      :return: the return value of the callable
  27  
  28      r.Nr/)rr1r2r3r4Zrun_sync_from_threadr5r7r7r8�run_sync>r:r<c@sZeZdZUded<ded<ded<dZded	<d dd�Zd!dd�Zd"dd�Zd#dd�ZdS)$�_BlockingAsyncContextManagerzFuture[T_co]�
  29  _enter_futurezFuture[bool | None]�_exit_futurer�_exit_event)NNNzMtuple[type[BaseException] | None, BaseException | None, TracebackType | None]�_exit_exc_info�async_cm�!AbstractAsyncContextManager[T_co]�portal�BlockingPortalcCs||_||_dS�N)�	_async_cm�_portal)�selfrBrDr7r7r8�__init__\s
  30  z%_BlockingAsyncContextManager.__init__r,�bool | Nonec
  31  �s��zt�|_|j��IdH}Wnty"}z|j�|��d}~ww|j�|�z|j��IdHW|jj	|j
  32  �IdH}|S|jj	|j
  33  �IdH}|YSrF)rr@rG�
  34  __aenter__�
  35  BaseExceptionr>�
  36  set_exception�
  37  set_result�wait�	__aexit__rA)rI�value�exc�resultr7r7r8�run_async_cmbs ����z)_BlockingAsyncContextManager.run_async_cmr%cCs"t�|_|j�|j�|_|j��SrF)rr>rH�start_task_soonrUr?rT�rIr7r7r8�	__enter__ys
  38  z&_BlockingAsyncContextManager.__enter__�&_BlockingAsyncContextManager__exc_type�type[BaseException] | None�'_BlockingAsyncContextManager__exc_value�BaseException | None�'_BlockingAsyncContextManager__traceback�TracebackType | NonecCs&|||f|_|j�|jj�|j��SrF)rArH�callr@�setr?rT)rIrYr[r]r7r7r8�__exit__~s
  39  z%_BlockingAsyncContextManager.__exit__N)rBrCrDrE)r,rK)r,r%)rYrZr[r\r]r^r,rK)	�__name__�
  40  __module__�__qualname__�__annotations__rArJrUrXrar7r7r7r8r=Ts
  41  
  42  �
  43  
  44  
  45  r=c@s"eZdZddd�Zd
  46  dd
  47  d�ZdS)�_BlockingPortalTaskStatus�futurercCs
  48  ||_dSrF)�_future)rIrgr7r7r8rJ��
  49  z"_BlockingPortalTaskStatus.__init__NrR�objectr,�NonecCs|j�|�dSrF)rhrO)rIrRr7r7r8�started�sz!_BlockingPortalTaskStatus.started)rgrrF)rRrjr,rk)rbrcrdrJrlr7r7r7r8rf�s
  50  rfc@s�eZdZdZdAdd�ZdBdd�ZdAdd	�ZdCdd�ZdBdd�ZdBdd�Z	dDdEdd�Z
  51  dFd$d%�ZdGd(d)�Ze
  52  dHd-d.��Ze
  53  dId0d.��ZdJd1d.�Ze
  54  d2d3�dKd4d5��Ze
  55  d2d3�dLd6d5��Zd2d3�dMd7d5�Zd2d3�dNd:d;�ZdOd?d@�Zd2S)PrEzLAn object that lets external threads run code in an asynchronous event loop.r,cCs
  56  t���SrF)rZcreate_blocking_portal)�clsr7r7r8�__new__�rizBlockingPortal.__new__rkcCs$t�|_t�|_t�|_t�|_dSrF)r�_event_loop_thread_idr�_stop_eventr�_task_groupr�_cancelled_exc_classrWr7r7r8rJ�szBlockingPortal.__init__c�s�|j��IdH|SrF)rqrLrWr7r7r8rL�s�zBlockingPortal.__aenter__�exc_typerZ�exc_valr\�exc_tbr^rKc�s&�|��IdH|j�|||�IdHSrF)�stoprqrQ)rIrsrtrur7r7r8rQ�s�zBlockingPortal.__aexit__cCs*|jdur	td��|jt�krtd��dS)NzThis portal is not runningz7This method cannot be called from the event loop thread)ror4rrWr7r7r8�_check_running�s
  57  ��zBlockingPortal._check_runningc�s�|j��IdHdS)z#Sleep until :meth:`stop` is called.N)rprPrWr7r7r8�sleep_until_stopped�s�z"BlockingPortal.sleep_until_stoppedF�cancel_remaining�boolc�s*�d|_|j��|r|jj��dSdS)a.
  58          Signal the portal to shut down.
  59  
  60          This marks the portal as no longer accepting new calls and exits from
  61          :meth:`sleep_until_stopped`.
  62  
  63          :param cancel_remaining: ``True`` to cancel all the remaining tasks, ``False``
  64              to let them finish before returning
  65  
  66          N)rorpr`rqZcancel_scope�cancel)rIryr7r7r8rv�s�
  67  �zBlockingPortal.stopr(�<Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval]r*�tuple[Unpack[PosArgsT]]�kwargs�dict[str, Any]rg�Future[T_Retval]c	
  68  �s&�d��fdd�}z�z6||i|��}t|�r=t���|��r#���n|�|�|IdH}Wd�n1s7wYn|}Wn2�jyR|��|��Yn4tyr}z|��sb|�|�t	|t
  69  �sh�WYd}~nd}~ww|��s�|�|�Wd�dSWd�dSWd�dSWd�dSd�w)N�fr�r,rkcs0|��r�jdt�fvr���j�dSdSdSrF)�	cancelledrorr_r{)r���scoperIr7r8�callback�s��z+BlockingPortal._call_func.<locals>.callback)r�r�r,rk)rrr�r{�add_done_callbackrr�set_running_or_notify_cancelrMrN�
  70  isinstance�	ExceptionrO)	rIr(r*r~rgr�Zretval_or_awaitable�retvalrSr7r�r8�
  71  _call_func�sD�
  72  
  73  ���
  74  
  75  ������zBlockingPortal._call_func�namerjcCst�)a%
  76          Spawn a new task using the given callable.
  77  
  78          Implementers must ensure that the future is resolved when the task finishes.
  79  
  80          :param func: a callable
  81          :param args: positional arguments to be passed to the callable
  82          :param kwargs: keyword arguments to be passed to the callable
  83          :param name: name of the task (will be coerced to a string if not ``None``)
  84          :param future: a future that will resolve to the return value of the callable,
  85              or the exception raised during its execution
  86  
  87          )�NotImplementedError)rIr(r*r~r�rgr7r7r8�_spawn_task_from_thread�sz&BlockingPortal._spawn_task_from_threadr)r+r$cG�dSrFr7�rIr(r*r7r7r8r_szBlockingPortal.callr;cGr�rFr7r�r7r7r8r_scGstt|j|g|�R����S)a3
  88          Call the given function in the event loop thread.
  89  
  90          If the callable returns a coroutine object, it is awaited on.
  91  
  92          :param func: any callable
  93          :raises RuntimeError: if the portal is not running or if this method is called
  94              from within the event loop thread
  95  
  96          )rr$rVrTr�r7r7r8r_sN)r�cGr�rFr7�rIr(r�r*r7r7r8rV$�zBlockingPortal.start_task_sooncGr�rFr7r�r7r7r8rV,r�cGs$|��t�}|�||i||�|S)a�
  97          Start a task in the portal's task group.
  98  
  99          The task will be run inside a cancel scope which can be cancelled by cancelling
 100          the returned future.
 101  
 102          :param func: the target function
 103          :param args: positional arguments passed to ``func``
 104          :param name: name of the task (will be coerced to a string if not ``None``)
 105          :return: a future that resolves with the return value of the callable if the
 106              task completes successfully, or with the exception raised in the task
 107          :raises RuntimeError: if the portal is not running or if this method is called
 108              from within the event loop thread
 109          :rtype: concurrent.futures.Future[T_Retval]
 110  
 111          .. versionadded:: 3.0
 112  
 113          )rwrr�)rIr(r�r*r�r7r7r8rV4s�"Callable[..., Awaitable[T_Retval]]�tuple[Future[T_Retval], Any]csVd	�fdd�}|��t��t��}t�}|�|�|�||d|i||�|���fS)
 114  a�
 115          Start a task in the portal's task group and wait until it signals for readiness.
 116  
 117          This method works the same way as :meth:`.abc.TaskGroup.start`.
 118  
 119          :param func: the target function
 120          :param args: positional arguments passed to ``func``
 121          :param name: name of the task (will be coerced to a string if not ``None``)
 122          :return: a tuple of (future, task_status_value) where the ``task_status_value``
 123              is the value passed to ``task_status.started()`` from within the target
 124              function
 125          :rtype: tuple[concurrent.futures.Future[T_Retval], Any]
 126  
 127          .. versionadded:: 3.0
 128  
 129          rgr�r,rkcsP���s&|��r���dS|��r��|���dStd�}��|�dSdS)Nz1Task exited without calling task_status.started())�doner�r{�	exceptionrNr4)rgrS�Ztask_status_futurer7r8�	task_donehs��z,BlockingPortal.start_task.<locals>.task_done�task_statusN)rgr�r,rk)rwrrfr�r�rT)rIr(r�r*r�r�r�r7r�r8�
 130  start_taskQs
 131  zBlockingPortal.start_task�cmrC�AbstractContextManager[T_co]cCs
 132  t||�S)a�
 133          Wrap an async context manager as a synchronous context manager via this portal.
 134  
 135          Spawns a task that will call both ``__aenter__()`` and ``__aexit__()``, stopping
 136          in the middle until the synchronous context manager exits.
 137  
 138          :param cm: an asynchronous context manager
 139          :return: a synchronous context manager
 140  
 141          .. versionadded:: 2.1
 142  
 143          )r=)rIr�r7r7r8�wrap_async_context_manager|s
 144  z)BlockingPortal.wrap_async_context_manager�r,rE�r,rk)rsrZrtr\rur^r,rK)F)ryrzr,rk)
 145  r(r|r*r}r~rrgr�r,rk)r(r|r*r}r~rr�rjrgr�r,rk�r(r)r*r+r,r$�r(r;r*r+r,r$)r(r|r*r+r,r$)r(r)r*r+r�rjr,r�)r(r;r*r+r�rjr,r�)r(r|r*r+r�rjr,r�)r(r�r*rjr�rjr,r�)r�rCr,r�)rbrcrd�__doc__rnrJrLrQrwrxrvr�r�rr_rVr�r�r7r7r7r8rE�s6
 146  
 147  
 148  
 149  
 150  	
 151  
 152  
 153  *
 154  ���!�+rEc@s�eZdZUdZdZded<dZded<eded	�Z	d
 155  ed<eddd
 156  �Z
 157  ded<edd�Zded<eddd
 158  �Zded<d!dd�Z
 159  d"dd �ZdS)#�BlockingPortalProvidera=
 160      A manager for a blocking portal. Used as a context manager. The first thread to
 161      enter this context manager causes a blocking portal to be started with the specific
 162      parameters, and the last thread to exit causes the portal to be shut down. Thus,
 163      there will be exactly one blocking portal running in this context as long as at
 164      least one thread has entered this context manager.
 165  
 166      The parameters are the same as for :func:`~anyio.run`.
 167  
 168      :param backend: name of the backend
 169      :param backend_options: backend options
 170  
 171      .. versionadded:: 4.4
 172      �asyncio�str�backendN�dict[str, Any] | None�backend_optionsF)�init�default_factoryr
 173  �_lockr)r��default�int�_leases)r�rErHz-AbstractContextManager[BlockingPortal] | None�
 174  _portal_cmr,cCsd|j�%|jdurt|j|j�|_|j��|_|jd7_|jWd�S1s+wYdS)Nr)r�r��start_blocking_portalr�r�rXrHr�rWr7r7r8rX�s
 175  �$�z BlockingPortalProvider.__enter__rsrZrtr\rur^rkcCs�d}|j�&|jsJ�|jdksJ�|jd8_|js$|j}d|_|`Wd�n1s.wY|r>|�ddd�dSdS)Nrr)r�r�r�rHra)rIrsrtruZ	portal_cmr7r7r8ra�s
 176  ��	�zBlockingPortalProvider.__exit__r�)rsrZrtr\rur^r,rk)rbrcrdr�r�rer�rr
 177  r�r�rHr�rXrar7r7r7r8r��s
 178  �
 179  r�r�r�r�r�r��$Generator[BlockingPortal, Any, None]c#s��d�fdd��d����fdd�}t��t|dd�}|��zLd	}���}z$z|VWn
 180  ty6d}�wWz	|�|j|�WntyJYnwz	|�|j|�Wwty]YwwW|��d
 181  SW|��d
 182  S|��w)a|
 183      Start a new event loop in a new thread and run a blocking portal in its main task.
 184  
 185      The parameters are the same as for :func:`~anyio.run`.
 186  
 187      :param backend: name of the backend
 188      :param backend_options: backend options
 189      :return: a context manager that yields a blocking portal
 190  
 191      .. versionchanged:: 3.0
 192          Usage as a context manager is now required.
 193  
 194      r,rkc	�sZ�t�4IdH�}��|�|��IdHWd�IdHdS1IdHs&wYdSrF)rErOrx)Zportal_)rgr7r8�
 195  run_portal�s
 196  �
 197  .�z)start_blocking_portal.<locals>.run_portalc
 198  sj���r3ztj���d�WdSty2}z���s'��|�WYd}~dSWYd}~dSd}~wwdS)N)r�r�)r�rr9rMr�rN)rS�r�r�rgr�r7r8�run_blocking_portal�s�����z2start_blocking_portal.<locals>.run_blocking_portalT)�target�daemonFNr�)	rr�startrTrMr_rvr4�join)r�r�r��threadZcancel_remaining_tasksrDr7r�r8r��s<�
 199  
 200  �������r�rkcCs0ztj}Wntytd�d�w|��dS)aa
 201      Check if the cancel scope of the host task's running the current worker thread has
 202      been cancelled.
 203  
 204      If the host task's current cancel scope has indeed been cancelled, the
 205      backend-specific cancellation exception will be raised.
 206  
 207      :raises RuntimeError: if the current thread was not spawned by
 208          :func:`.to_thread.run_sync`
 209  
 210      r.N)rr1r3r4�check_cancelled)r6r7r7r8r��s
 211  ���r�r�r�)r�N)r�r�r�r�r,r�r�)<�
 212  __future__r�sys�collections.abcrrr�concurrent.futuresr�
 213  contextlibrrr	�dataclassesr
 214  r�inspectr�	threadingr
 215  rr�typesr�typingrrrrrZ_corerZ_core._eventlooprrrZ_core._synchronizationrZ_core._tasksrr�abcrZ
 216  abc._tasksr�version_infor"r#Ztyping_extensionsr$r%r'r9r<r=rfrEr�r�r�r7r7r7r8�<module>sD
 217  
 218  
 219  5~8�4