]L iIVddlmZddlZddlmZmZmZddlmZddl m Z m Z m Z ddl mZmZddlmZddlmZmZmZmZdd lmZdd lmZmZmZmZmZd d lm Z m!Z!m"Z"d d lm#Z$d dl%m&Z&d dl'm(Z(d dl)m*Z*m+Z+d dl,m-Z-d dl.m/Z/ej`dk\r ddlm1Z1m2Z2nddl3m1Z1m2Z2edZ4eddZ5e1dZ6d)dZ7dd d*dZ#dd d+dZ8Gddee5e Z9Gd d!e-Z:Gd"d#Z;eGd$d%Zy)/) annotationsN) AwaitableCallable Generator)Future)AbstractAsyncContextManagerAbstractContextManagercontextmanager) dataclassfield) isawaitable)LockThreadcurrent_thread get_ident) TracebackType)AnyGenericTypeVarcastoverload)get_async_backendget_cancelled_exc_class threadlocals)run)NoEventLoopError)Event) CancelScopecreate_task_group) TaskStatus)EventLoopToken) ) TypeVarTupleUnpackT_RetvalT_coT) covariantPosArgsTc^||S tjS#t$r tddwxYw)NzONot running inside an AnyIO worker thread, and no event loop token was provided)r current_tokenAttributeErrorrtokens W/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/anyio/from_thread.py_token_or_errorr1-sD  )))    s,r.c|du}t|}|jj|||r|jSdS)a Call a coroutine function from a worker thread. :param func: a coroutine function :param args: positional arguments for the callable :param token: an event loop token to use to get back to the event loop thread (required if calling this function from outside an AnyIO worker thread) :return: the return value of the coroutine function :raises MissingTokenError: if no token was provided and called from outside an AnyIO worker thread :raises RunFinishedError: if the event loop tied to ``token`` is no longer running .. versionchanged:: 4.11.0 Added the ``token`` parameter. Nr.)r1 backend_classrun_async_from_thread native_tokenfuncr/argsexplicit_tokens r0rr:sW*$&N E "E    4 4 d%,, 5 DH 5 c|du}t|}|jj|||r|jSdS)az Call a function in the event loop thread from a worker thread. :param func: a callable :param args: positional arguments for the callable :param token: an event loop token to use to get back to the event loop thread (required if calling this function from outside an AnyIO worker thread) :return: the return value of the callable :raises MissingTokenError: if no token was provided and called from outside an AnyIO worker thread :raises RunFinishedError: if the event loop tied to ``token`` is no longer running .. versionchanged:: 4.11.0 Added the ``token`` parameter. Nr.)r1r3run_sync_from_threadr5r6s r0run_syncr=VsW*$&N E "E    3 3 d%,, 4 DH 4 r:creZdZUded<ded<ded<dZded < dd Zdd Zdd Z dd Zy)_BlockingAsyncContextManagerz Future[T_co] _enter_futurezFuture[bool | None] _exit_futurer _exit_event)NNNzMtuple[type[BaseException] | None, BaseException | None, TracebackType | None]_exit_exc_infoc ||_||_yN) _async_cm_portal)selfasync_cmportals r0__init__z%_BlockingAsyncContextManager.__init__zs" r:c K t|_|jjd{}|jj | |jjd{|jj|jd{}|S7o#t $r!}|jj|d}~wwxYw7`77#|jj|jd{7}wxYwwrE) rrBrF __aenter__r@ set_result BaseException set_exceptionwait __aexit__rC)rHvalueexcresults r0 run_async_cmz)_BlockingAsyncContextManager.run_async_cms 1$wD ..3355E    ) )% 0 J ""'') ) ) 44>>33T5H5HIIF '6     , ,S 1   * J34>>33T5H5HIIIFsD,B"B B"DC.C/C3&DCD B"" C +CC  DCD'D:C=;DDct|_|jj|j|_|jj SrE)rr@rGstart_task_soonrVrArUrHs r0 __enter__z&_BlockingAsyncContextManager.__enter__s>#X LL889J9JK!!((**r:c|||f|_|jj|jj|j j SrE)rCrGcallrBsetrArU)rH&_BlockingAsyncContextManager__exc_type'_BlockingAsyncContextManager__exc_value'_BlockingAsyncContextManager__tracebacks r0__exit__z%_BlockingAsyncContextManager.__exit__sF )+{B $**../  ''))r:N)rI!AbstractAsyncContextManager[T_co]rJBlockingPortal)return bool | None)rdr()r^type[BaseException] | Noner_BaseException | Noner`TracebackType | Nonerdre) __name__ __module__ __qualname____annotations__rCrKrVrZrar:r0r?r?rsr%% 9CQ 0+ *.**** *  *r:r?ceZdZddZdddZy)_BlockingPortalTaskStatusc||_yrE)_future)rHfutures r0rKz"_BlockingPortalTaskStatus.__init__s  r:Nc:|jj|yrE)rqrN)rHrSs r0startedz!_BlockingPortalTaskStatus.starteds &r:)rrrrE)rSobjectrdNone)rirjrkrKrtrmr:r0roros 'r:roczeZdZdZddZddZddZ ddZddZddZ dddZ dd Z dd Z e dd Ze dd Z dd Ze dd ddZe dd d dZdd d!dZdd d"dZ d#dZy)$rczLAn object that lets external threads run code in an asynchronous event loop.c2tjSrE)rcreate_blocking_portal)clss r0__new__zBlockingPortal.__new__s "99;;r:c|t|_t|_t |_t |_yrE)r_event_loop_thread_idr _stop_eventr _task_groupr_cancelled_exc_classrYs r0rKzBlockingPortal.__init__s,1:" 7,.$;$=!r:cVK|jjd{|S7wrE)rrMrYs r0rMzBlockingPortal.__aenter__s())+++  ,s )')cK|jd{|jj|||d{S7)7wrE)stoprrR)rHexc_typeexc_valexc_tbs r0rRzBlockingPortal.__aexit__s> iik%%//'6JJJ JsAA$AAAAcv|j td|jtk(r tdy)NzThis portal is not runningz7This method cannot be called from the event loop thread)r} RuntimeErrorrrYs r0_check_runningzBlockingPortal._check_runnings?  % % -;< <  % % 4I  5r:cTK|jjd{y7w)z#Sleep until :meth:`stop` is called.N)r~rQrYs r0sleep_until_stoppedz"BlockingPortal.sleep_until_stoppeds##%%%s (&(cKd|_|jj|r&|jjj dyyw)a. Signal the portal to shut down. This marks the portal as no longer accepting new calls and exits from :meth:`sleep_until_stopped`. :param cancel_remaining: ``True`` to cancel all the remaining tasks, ``False`` to let them finish before returning Nz$the blocking portal is shutting down)r}r~r]r cancel_scopecancel)rHcancel_remainings r0rzBlockingPortal.stopsE&*"      ) ) 0 01W X sA A c^ Kd fd } ||i|}t|rQt5 |jr jdn|j ||d{}dddn|}|js|j  d y d y78#1swY4xYw#j $r%|j|jYd yt$r>}|js|j|t|tsYd}~d yd}~wwxYw#d wxYww)Nc|jr6jdtfvrjjdyyy)Nthe future was cancelled) cancelledr}rr\r)fscoperHs r0callbackz+BlockingPortal._call_func..callbacksC{{}!;!; D" %,,(BC "}r:r)rFuture[T_Retval]rdrv) r rrradd_done_callbackrNrset_running_or_notify_cancelrOrP isinstance Exception) rHr7r8kwargsrrrretval_or_awaitableretvalrTrs ` @r0 _call_funczBlockingPortal._call_funcs. D "&"7"7 ./ ]7e'') %?@00:#66F 77-##%!!&)E&E#7 77(( 2 MMO  / / 1E ##%$$S)c9-. E EsD-B*9B#B$B( B*3!D&D-D-BB'#B**/D#D&D-D#%2DD&D-D##D&&D**D-ct)a% Spawn a new task using the given callable. Implementers must ensure that the future is resolved when the task finishes. :param func: a callable :param args: positional arguments to be passed to the callable :param kwargs: keyword arguments to be passed to the callable :param name: name of the task (will be coerced to a string if not ``None``) :param future: a future that will resolve to the return value of the callable, or the exception raised during its execution )NotImplementedError)rHr7r8rnamerrs r0_spawn_task_from_threadz&BlockingPortal._spawn_task_from_threads *"!r:cyrErmrHr7r8s r0r\zBlockingPortal.call&s r:cyrErmrs r0r\zBlockingPortal.call-sr:c`tt|j|g|jS)a3 Call the given function in the event loop thread. If the callable returns a coroutine object, it is awaited on. :param func: any callable :raises RuntimeError: if the portal is not running or if this method is called from within the event loop thread )rr'rXrUrs r0r\zBlockingPortal.call2s-H2d224?$?FFHIIr:NrcyrErmrHr7rr8s r0rXzBlockingPortal.start_task_soonC r:cyrErmrs r0rXzBlockingPortal.start_task_soonKrr:cd|jt}|j||i|||S)a Start a task in the portal's task group. The task will be run inside a cancel scope which can be cancelled by cancelling the returned future. :param func: the target function :param args: positional arguments passed to ``func`` :param name: name of the task (will be coerced to a string if not ``None``) :return: a future that resolves with the return value of the callable if the task completes successfully, or with the exception raised in the task :raises RuntimeError: if the portal is not running or if this method is called from within the event loop thread :rtype: concurrent.futures.Future[T_Retval] .. versionadded:: 3.0 )rrr)rHr7rr8rs r0rXzBlockingPortal.start_task_soonSs20 $h $$T4T1=r:cdfd }|jtt}t}|j||j ||d|i|||j fS)a Start a task in the portal's task group and wait until it signals for readiness. This method works the same way as :meth:`.abc.TaskGroup.start`. :param func: the target function :param args: positional arguments passed to ``func`` :param name: name of the task (will be coerced to a string if not ``None``) :return: a tuple of (future, task_status_value) where the ``task_status_value`` is the value passed to ``task_status.started()`` from within the target function :rtype: tuple[concurrent.futures.Future[T_Retval], Any] .. versionadded:: 3.0 cjsn|jrjy|jr j |jyt d}j |yy)Nz1Task exited without calling task_status.started())donerr exceptionrPr)rrrTtask_status_futures r0 task_donez,BlockingPortal.start_task..task_donesl%**,##%&--/%%'&44V5E5E5GH&KC'44S9-r: task_status)rrrrdrv)rrrorrrU)rHr7rr8rrrrs @r0 start_taskzBlockingPortal.start_taskpso. : %+X/0BC H I& $$T4-1MtUVW$++---r:ct||S)a Wrap an async context manager as a synchronous context manager via this portal. Spawns a task that will call both ``__aenter__()`` and ``__aexit__()``, stopping in the middle until the synchronous context manager exits. :param cm: an asynchronous context manager :return: a synchronous context manager .. versionadded:: 2.1 )r?)rHcms r0wrap_async_context_managerz)BlockingPortal.wrap_async_context_managers,B55r:rdrcrdrv)rrfrrgrrhrdbool)F)rrrdrv) r7 K,K&K% K  K&Y (J(&( ( ! (  (T"J"&" "  " ! " ".?    :CS JJJ J  J"  ?      4     J    B ).0).). ). & ).V636 %6r:rcceZdZUdZdZded<dZded<ede Z d ed <edd Z ded<edZ ded<edd Z ded<ddZ ddZy)BlockingPortalProvidera= A manager for a blocking portal. Used as a context manager. The first thread to enter this context manager causes a blocking portal to be started with the specific parameters, and the last thread to exit causes the portal to be shut down. Thus, there will be exactly one blocking portal running in this context as long as at least one thread has entered this context manager. The parameters are the same as for :func:`~anyio.run`. :param backend: name of the backend :param backend_options: backend options .. versionadded:: 4.4 asynciostrbackendNdict[str, Any] | Nonebackend_optionsF)initdefault_factoryr_lockr)rdefaultint_leases)rrcrGz-AbstractContextManager[BlockingPortal] | None _portal_cmc(|j5|jDt|j|j|_|jj |_|xjdz c_|j cdddS#1swYyxYw)Nr)rrstart_blocking_portalrrrZrGrrYs r0rZz BlockingPortalProvider.__enter__sn ZZ &"7LL$"6"6# $88: LLA L<<   s A1BBc d}|j5|jsJ|jdkDsJ|xjdzc_|js|j}d|_|`ddd|r|j dddyy#1swY xYw)Nrr)rrrrGra)rHrrr portal_cms r0razBlockingPortalProvider.__exit__s DH ZZ !?? "?<.run_portals!# 0 0w|+2)8BwK?(K %   g &--/ / /  0 0 0 0  0 0 0 0sWB A1B AA7A3A7 B +A5,B 3A75B 7B =B >B B cjr tyy#t$r0}jsj |Yd}~yYd}~yd}~wwxYw)N)rr)r run_eventlooprOrrP)rTrrrrrs r0run_blocking_portalz2start_blocking_portal..run_blocking_portalsY  . . 0 . 1 ! .{{}((--% .s# A!AAT)targetdaemonrFNr) rrstartrUrOr\rrjoin) rrrrthreadcancel_remaining_tasksrJrrrs ``` @@r0rrs,0..&,XF .t$ GF LLN!& L   FKK)?@   %) "        FKK)?@    s}:C-CBB7C- BB' B$!C#B$$C'C)CC CCCCCC**C-c tj}|jj y#t$r tddwxYw)aa Check if the cancel scope of the host task's running the current worker thread has been cancelled. If the host task's current cancel scope has indeed been cancelled, the backend-specific cancellation exception will be raised. :raises RuntimeError: if the current thread was not spawned by :func:`.to_thread.run_sync` z>This function can only be called inside an AnyIO worker threadN)rr,r-rr3check_cancelledr.s r0rr"sJ , : :  '')  L  s -A)r/EventLoopToken | Nonerdr")r7rr8rr/rrdr')r7rr8rr/rrdr')rN)rrrrrz str | Nonerdz$Generator[BlockingPortal, Any, None]r)? __future__rsyscollections.abcrrrconcurrent.futuresr contextlibrr r dataclassesr r inspectr threadingrrrrtypesrtypingrrrrr_core._eventlooprrrrr_core._exceptionsr_core._synchronizationr _core._tasksrr abc._tasksr!lowlevelr" version_infor%r&typing_extensionsr'r(r*r1r=r?rorcrrrrmr:r0rs" ::% )== 3/)8"$w++6 : v&  #  $( ;  ! >$( 0  ! 83*74=2H3*l' 'z6z6z 5151 51p-18 8 8*8  8 * 88v*r: