
    +h@                       d dl mZ d dlZd dlmZ d dlmZmZmZm	Z	 d dl
mZmZ d dl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 d dlmZ d	d
lmZ d	dlm Z m!Z!m"Z" d	dl#m$Z$ d	dl%m&Z&m'Z' d	dl(m)Z)  ed      Z* ed      Z+ddZ,	 	 	 	 	 	 ddZ-ddZ.ddZ/ G d dee+   e      Z0 G d de)      Z1 G d d      Z2ddZ3e	 d 	 	 	 	 	 d!d       Z4y)"    )annotationsN)iscoroutine)FIRST_COMPLETEDFutureThreadPoolExecutorwait)AbstractContextManagercontextmanager)TracebackType)AnyAsyncContextManager	AwaitableCallableContextManager	GeneratorGenericIterableTypeVarcastoverload)warn   )
_eventloop)get_asynclibget_cancelled_exc_classthreadlocals)Event)CancelScopecreate_task_group)
TaskStatusT_RetvalT_coc                z    	 t         j                  } |j                  | g| S # t        $ r t        d      w xY w)z
    Call a coroutine function from a worker thread.

    :param func: a coroutine function
    :param args: positional arguments for the callable
    :return: the return value of the coroutine function

    9This function can only be run from an AnyIO worker thread)r   current_async_moduleAttributeErrorRuntimeErrorrun_async_from_threadfuncargsasynclibs      D/var/www/html/venv/lib/python3.12/site-packages/anyio/from_thread.pyrunr.   !   sL    X44 *8))$666  XVWWX   % :c                :    t        dt               t        | g| S )NzPrun_async_from_thread() has been deprecated, use anyio.from_thread.run() instead)r   DeprecationWarningr.   r*   r+   s     r-   r(   r(   2   s$     	Z td    c                z    	 t         j                  } |j                  | g| S # t        $ r t        d      w xY w)z
    Call a function in the event loop thread from a worker thread.

    :param func: a callable
    :param args: positional arguments for the callable
    :return: the return value of the callable

    r$   )r   r%   r&   r'   run_sync_from_threadr)   s      r-   run_syncr6   <   sL    X44 )8((555  XVWWXr/   c                :    t        dt               t        | g| S )NzTrun_sync_from_thread() has been deprecated, use anyio.from_thread.run_sync() instead)r   r1   r6   r2   s     r-   r5   r5   M   s"    ^ D 4  r3   c                  j    e Zd ZU ded<   ded<   ded<   dZded<   dd	Zdd
ZddZ	 	 	 	 	 	 	 	 ddZy)_BlockingAsyncContextManagerr   _enter_future_exit_futurer   _exit_event)NNNzMtuple[type[BaseException] | None, BaseException | None, TracebackType | None]_exit_exc_infoc                     || _         || _        y N)	_async_cm_portal)selfasync_cmportals      r-   __init__z%_BlockingAsyncContextManager.__init__]   s    !r3   c                  K   	 t               | _        | j                  j                          d {   }| j                  j                  |       	 | j                  j                          d {     | j                  j                  | j                    d {   }|S 7 o# t        $ r!}| j                  j                  |        d }~ww xY w7 `7 7#  | j                  j                  | j                    d {  7  }|c cY S xY wwr?   )r   r<   r@   
__aenter__r:   
set_resultBaseExceptionset_exceptionr   	__aexit__r=   )rB   valueexcresults       r-   run_async_cmz)_BlockingAsyncContextManager.run_async_cma   s     	1$wD..3355E
 ))%0	
 ""'')))
 44>>33T5H5HIIFM% 6 	,,S1	 *
 J34>>33T5H5HIIIFMs   D	,B" B B" D	C .C/C 3&D	CD	 B" "	C+CCD	C D	'D:C=;	DD	c                    t               | _        | j                  j                  | j                        | _        | j                  j                         }t        t        |      S r?   )	r   r:   rA   start_task_soonrO   r;   rN   r   r"   rB   cms     r-   	__enter__z&_BlockingAsyncContextManager.__enter__x   sI    #X LL889J9JK&&(D"~r3   c                    |||f| _         | j                  j                  | j                  j                         | j
                  j                         S r?   )r=   rA   callr<   setr;   rN   )rB   &_BlockingAsyncContextManager__exc_type'_BlockingAsyncContextManager__exc_value'_BlockingAsyncContextManager__tracebacks       r-   __exit__z%_BlockingAsyncContextManager.__exit__~   sF     )+{B$**../  ''))r3   N)rC   AsyncContextManager[T_co]rD   BlockingPortal)returnbool | None)r^   r"   )rX   type[BaseException] | NonerY   BaseException | NonerZ   TracebackType | Noner^   r_   )	__name__
__module____qualname____annotations__r=   rE   rO   rT   r[    r3   r-   r9   r9   U   sb     	   .*.* ** *	*
 
*r3   r9   c                      e Zd ZddZdddZy)_BlockingPortalTaskStatusc                    || _         y r?   )_future)rB   futures     r-   rE   z"_BlockingPortalTaskStatus.__init__   s	    r3   Nc                :    | j                   j                  |       y r?   )rk   rH   )rB   rL   s     r-   startedz!_BlockingPortalTaskStatus.started   s    &r3   )rl   r   r?   )rL   objectr^   None)rc   rd   re   rE   rn   rg   r3   r-   ri   ri      s    'r3   ri   c                     e Zd ZdZddZddZddZ	 	 	 	 	 	 	 	 ddZddZddZ	dddZ
	 	 	 	 	 	 	 	 	 	 dd	Z	 	 	 	 	 	 	 	 	 	 	 	 dd
Zedd       Zed d       Z	 	 	 	 	 	 d!dZedd	 	 	 	 	 	 	 d"d       Zedd	 	 	 	 	 	 	 d#d       Zdd	 	 	 	 	 	 	 d$dZedd	 	 	 	 	 	 	 d"d       Zedd	 	 	 	 	 	 	 d#d       Zdd	 	 	 	 	 	 	 d$dZdd	 	 	 	 	 	 	 d%dZ	 	 	 	 d&dZy)'r]   zLAn object that lets external threads run code in an asynchronous event loop.c                2    t               j                         S r?   )r   r]   )clss    r-   __new__zBlockingPortal.__new__   s    ~,,..r3   c                    t        j                         | _        t               | _        t               | _        t               | _        y r?   )		threading	get_ident_event_loop_thread_idr   _stop_eventr   _task_groupr   _cancelled_exc_classrB   s    r-   rE   zBlockingPortal.__init__   s3    1:1D1D1F" 7,.$;$=!r3   c                V   K   | j                   j                          d {    | S 7 wr?   )rz   rG   r|   s    r-   rG   zBlockingPortal.__aenter__   s(     ))+++ 	,s   )')c                   K   | j                          d {    | j                  j                  |||       d {   S 7 )7 wr?   )stoprz   rK   )rB   exc_typeexc_valexc_tbs       r-   rK   zBlockingPortal.__aexit__   s>      iik%%//'6JJJ 	Js   AA $AAAAc                    | j                   t        d      | j                   t        j                         k(  rt        d      y )NzThis portal is not runningz7This method cannot be called from the event loop thread)rx   r'   rv   rw   r|   s    r-   _check_runningzBlockingPortal._check_running   sF    %%-;<<%%)<)<)>>I  ?r3   c                T   K   | j                   j                          d{    y7 w)z#Sleep until :meth:`stop` is called.N)ry   r   r|   s    r-   sleep_until_stoppedz"BlockingPortal.sleep_until_stopped   s     ##%%%s   (&(c                   K   d| _         | j                  j                          |r%| j                  j                  j                          yyw)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

        N)rx   ry   rW   rz   cancel_scopecancel)rB   cancel_remainings     r-   r   zBlockingPortal.stop   sB      &*"))002 s   A
Ac                6   K   d fd}	  ||i |}t        |      rOt               5 |j                         rj                          n|j	                  |       | d {   }d d d        |j                         s|j                  |       	 d y 	 d y 7 5# 1 sw Y   4xY w#  j                  $ r |j                          Y d y t        $ r>}|j                         s|j                  |       t        |t              s Y d }~d y d }~ww xY w# d w xY ww)Nc                    | j                         r?j                  d t        j                         fvrj	                  j
                         y y y r?   )	cancelledrx   rv   rw   rV   r   )fscoperB   s    r-   callbackz+BlockingPortal._call_func.<locals>.callback   sG    {{}!;!;##%D " 		%,,'	"}r3   )r   r   r^   rp   )r   r   r   r   add_done_callbackrH   r{   rI   rJ   
isinstance	Exception)	rB   r*   r+   kwargsrl   r   retvalrM   r   s	   `       @r-   
_call_funczBlockingPortal._call_func   s    	(	4*6*F6" ] *e'')00:#)\F*" ##%!!&)E & E ** * (( 	MMO E  	##%$$S) c9- . E	 Es   DB& 8B"B#B'B& /!D DDBB#B& &DD D	D2D
D D
DD DDc                    t         )a%  
        Spawn a new task using the given callable.

        Implementors 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)rB   r*   r+   r   namerl   s         r-   _spawn_task_from_threadz&BlockingPortal._spawn_task_from_thread   s
    * "!r3   c                     y r?   rg   rB   r*   r+   s      r-   rV   zBlockingPortal.call       r3   c                     y r?   rg   r   s      r-   rV   zBlockingPortal.call  r   r3   c                `    t        t         | j                  |g| j                               S )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

        )r   r!   rQ   rN   r   s      r-   rV   zBlockingPortal.call  s-     H2d224?$?FFHIIr3   N)r   c                    y r?   rg   rB   r*   r   r+   s       r-   
spawn_taskzBlockingPortal.spawn_task       	r3   c                    y r?   rg   r   s       r-   r   zBlockingPortal.spawn_task        	r3   c               N    t        dt                | j                  |g|d|iS )a  
        Start a task in the portal's task group.

        :param func: the target coroutine 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

        .. versionadded:: 2.1
        .. deprecated:: 3.0
           Use :meth:`start_task_soon` instead. If your code needs AnyIO 2 compatibility, you
           can keep using this until AnyIO 4.

        z;spawn_task() is deprecated -- use start_task_soon() insteadr   )r   r1   rQ   r   s       r-   r   zBlockingPortal.spawn_task&  s1    . 	I	
 $t##D;4;d;;r3   c                    y r?   rg   r   s       r-   rQ   zBlockingPortal.start_task_soonC  r   r3   c                    y r?   rg   r   s       r-   rQ   zBlockingPortal.start_task_soonL  r   r3   c               d    | j                          t               }| 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

        )r   r   r   )rB   r*   r   r+   r   s        r-   rQ   zBlockingPortal.start_task_soonR  s2    0 	H$$T4T1=r3   c                   dfd}| j                          t               t              }t               }|j                  |       | j	                  ||d|i||       |j                         fS )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[Any], Any]

        .. versionadded:: 3.0

        c                   j                         sn| j                         rj                          y | j                         r j	                  | j                                y t        d      }j	                  |       y y )Nz1Task exited without calling task_status.started())doner   r   	exceptionrJ   r'   )rl   rM   task_status_futures     r-   	task_donez,BlockingPortal.start_task.<locals>.task_done  sl    %**,##%&--/%%'&44V5E5E5GH&KC '44S9 -r3   task_status)rl   r   r^   rp   )r   r   ri   r   r   rN   )rB   r*   r   r+   r   r   r   r   s          @r-   
start_taskzBlockingPortal.start_tasko  so    (
	: 	%+X/0BCH	I&$$T4-1MtUVW$++---r3   c                    t        ||       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

        )r9   rR   s     r-   wrap_async_context_managerz)BlockingPortal.wrap_async_context_manager  s     ,B55r3   r^   r]   r^   rp   )r   r`   r   ra   r   rb   r^   r_   )F)r   boolr^   rp   )
r*   r   r+   tupler   dict[str, Any]rl   r   r^   rp   )r*   r   r+   r   r   r   r   ro   rl   r   r^   rp   r*   "Callable[..., Awaitable[T_Retval]]r+   ro   r^   r!   r*   Callable[..., T_Retval]r+   ro   r^   r!   )r*   -Callable[..., Awaitable[T_Retval] | T_Retval]r+   ro   r^   r!   )r*   r   r+   ro   r   ro   r^   Future[T_Retval])r*   r   r+   ro   r   ro   r^   r   )r*   r   r+   ro   r   ro   r^   r   )r*   zCallable[..., Awaitable[Any]]r+   ro   r   ro   r^   ztuple[Future[Any], Any])rS   r\   r^   zContextManager[T_co])rc   rd   re   __doc__rt   rE   rG   rK   r   r   r   r   r   r   rV   r   rQ   r   r   rg   r3   r-   r]   r]      s   V/>K,K &K %	K
 
K&3 !!$)!3A!KQ!	!F"" " 	"
 " " 
".    JAJJPJ	J 
 	0  	
 
  KO+4:BH	  	<;< < 	<
 
<: 
 	0  	
 
  KO+4:BH	  	;  	
 
< RV&.1&.:@&.HN&.	 &.P6+6	6r3   r]   c                 6    t        dt               t               S )aL  
    Create a portal for running functions in the event loop thread from external threads.

    Use this function in asynchronous code when you need to allow external threads access to the
    event loop where your asynchronous code is currently running.

    .. deprecated:: 3.0
        Use :class:`.BlockingPortal` directly.

    z_create_blocking_portal() has been deprecated -- use anyio.from_thread.BlockingPortal() directly)r   r1   r]   rg   r3   r-   create_blocking_portalr     s     		
 r3   c              #    K   dfd}t               t        d      5 }|j                  t        j                  || |      }	 t        t        t        t            |g      t               j                         r5j                         }d}	 | 	 	 |j                  |j                  |       |j                          ddd       y# t        $ r" j                          |j                           w xY w# t        $ r d} w xY w# t        $ r Y bw xY w# 	 |j                  |j                  |       w # t        $ r Y w w xY wxY w# 1 sw Y   yxY ww)	a|  
    Start a new event loop in a new thread and run a blocking portal in its main task.

    The parameters are the same as for :func:`~anyio.run`.

    :param backend: name of the backend
    :param backend_options: backend options
    :return: a context manager that yields a blocking portal

    .. versionchanged:: 3.0
        Usage as a context manager is now required.

    c                    K   t               4 d {   } j                         r)j                  |        | j                          d {    d d d       d {    y 7 N7 7 	# 1 d {  7  sw Y   y xY wwr?   )r]   set_running_or_notify_cancelrH   r   )portal_rl   s    r-   
run_portalz)start_blocking_portal.<locals>.run_portal  sp     !# 	4 	4w224!!'*11333	4 	4 	4 4	4 	4 	4 	4sV   A<A!A<5A'A#A'A<A%A<#A'%A<'A9-A0.A95A<r   )backendbackend_options)return_whenFTNr   )r   r   submitr   r.   r   r   r   r   rI   r   r   rN   rV   r   r'   )r   r   r   executor
run_futurerD   cancel_remaining_tasksrl   s          @r-   start_blocking_portalr     sJ    $4 &,XF	A	 (__NN+	 % 

	Xf%
F';<+ ;;=]]_F%*"	
KK-CD 	?   	MMO	 ! )-& $ KK-CD# 9 s   E$E(C
,"EC8D1E	E
+C55E8DD	DEDEED65E6	E	?EE	EEEEr   r   r   )asyncioN)r   strr   zdict[str, Any] | Noner^   z$Generator[BlockingPortal, Any, None])5
__future__r   rv   r   r   concurrent.futuresr   r   r   r   
contextlibr	   r
   typesr   typingr   r   r   r   r   r   r   r   r   r   r   warningsr   _corer   _core._eventloopr   r   r   _core._synchronizationr   _core._tasksr   r   
abc._tasksr    r!   r"   r.   r(   r6   r5   r9   ri   r]   r   r   rg   r3   r-   <module>r      s    "   P P =       Q Q ) 8 ":v7"
,5;6"!1*74=2H 1*h'
 'U6 U6p& GK77/D7)7 7r3   