a
    ø£Bel7  ã                   @  s\  d dl mZ d dlZd dlmZmZ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 d dl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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ddœdd„Z+ddddœdd„Z,G dd„ dee* eƒZ-G dd„ de(ƒZ.G dd„ dƒZ/ed&d d!d"d#œd$d%„ƒZ0dS )'é    )ÚannotationsN)Ú	AwaitableÚCallableÚ	Generator)ÚFIRST_COMPLETEDÚFutureÚThreadPoolExecutorÚwait)ÚAbstractContextManagerÚcontextmanager)Úisawaitable)ÚTracebackType)ÚAnyÚAsyncContextManagerÚContextManagerÚGenericÚIterableÚTypeVarÚcastÚoverloadé   )Ú
_eventloop)Úget_async_backendÚget_cancelled_exc_classÚthreadlocals)ÚEvent)ÚCancelScopeÚcreate_task_group)Ú
TaskStatusÚT_RetvalÚT_coú"Callable[..., Awaitable[T_Retval]]Úobject©ÚfuncÚargsÚreturnc                 G  s<   zt j}t j}W n ty*   tdƒ‚Y n0 |j| ||d�S )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©Útoken)r   Úcurrent_async_backendÚcurrent_tokenÚAttributeErrorÚRuntimeErrorZrun_async_from_thread©r$   r%   Zasync_backendr)   © r/   úT/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.9/site-packages/anyio/from_thread.pyÚrun   s    	
r1   úCallable[..., T_Retval]c                 G  s<   zt j}t j}W n ty*   tdƒ‚Y n0 |j| ||d�S )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+   r,   r-   Zrun_sync_from_threadr.   r/   r/   r0   Úrun_sync0   s    	
r3   c                   @  sr   e Zd ZU ded< ded< ded< dZded< d	d
dœdd„Zddœdd„Zddœdd„Zdddddœdd„ZdS )Ú_BlockingAsyncContextManagerr   Ú_enter_futureÚ_exit_futurer   Ú_exit_event)NNNzMtuple[type[BaseException] | None, BaseException | None, TracebackType | None]Ú_exit_exc_infoúAsyncContextManager[T_co]ÚBlockingPortal)Úasync_cmÚportalc                 C  s   || _ || _d S ©N)Ú	_async_cmÚ_portal)Úselfr;   r<   r/   r/   r0   Ú__init__J   s    z%_BlockingAsyncContextManager.__init__úbool | None©r&   c              
   Ã  s²   zt ƒ | _| j ¡ I d H }W n2 tyN } z| j |¡ ‚ W Y d }~nd }~0 0 | j |¡ z*| j ¡ I d H  W | jj	| j
Ž I d H }|S | jj	| j
Ž I d H }|     Y S 0 d S r=   )r   r7   r>   Ú
__aenter__ÚBaseExceptionr5   Úset_exceptionÚ
set_resultr	   Ú	__aexit__r8   )r@   ÚvalueÚexcÚresultr/   r/   r0   Úrun_async_cmN   s    ÿz)_BlockingAsyncContextManager.run_async_cmr    c                 C  s,   t ƒ | _| j | j¡| _| j ¡ }tt|ƒS r=   )	r   r5   r?   Ústart_task_soonrL   r6   rK   r   r    ©r@   Úcmr/   r/   r0   Ú	__enter__e   s    
z&_BlockingAsyncContextManager.__enter__útype[BaseException] | NoneúBaseException | NoneúTracebackType | None)Ú&_BlockingAsyncContextManager__exc_typeÚ'_BlockingAsyncContextManager__exc_valueÚ'_BlockingAsyncContextManager__tracebackr&   c                 C  s&   |||f| _ | j | jj¡ | j ¡ S r=   )r8   r?   Úcallr7   Úsetr6   rK   )r@   rT   rU   rV   r/   r/   r0   Ú__exit__k   s    z%_BlockingAsyncContextManager.__exit__N)	Ú__name__Ú
__module__Ú__qualname__Ú__annotations__r8   rA   rL   rP   rY   r/   r/   r/   r0   r4   B   s   
þ
r4   c                   @  s,   e Zd Zddœdd„Zddddœd	d
„ZdS )Ú_BlockingPortalTaskStatusr   ©Úfuturec                 C  s
   || _ d S r=   )Ú_future)r@   r`   r/   r/   r0   rA   w   s    z"_BlockingPortalTaskStatus.__init__Nr"   ÚNone)rI   r&   c                 C  s   | j  |¡ d S r=   )ra   rG   )r@   rI   r/   r/   r0   Ústartedz   s    z!_BlockingPortalTaskStatus.started)N)rZ   r[   r\   rA   rc   r/   r/   r/   r0   r^   v   s   r^   c                   @  sh  e Zd ZdZd dœdd„Zddœdd„Zd dœdd	„Zd
ddddœdd„Zddœdd„Zddœdd„Z	d@dddœdd„Z
ddddddœdd „Zdd!dd"ddd#œd$d%„Zed&d"d'd(œd)d*„ƒZed+d"d'd(œd,d*„ƒZd-d"d'd(œd.d*„Zed/d0œd&d"d"d1d2œd3d4„ƒZed/d0œd+d"d"d1d2œd5d4„ƒZd/d0œd-d"d"d1d2œd6d4„Zd/d0œd7d"d"d8d2œd9d:„Zd;d<d=œd>d?„Zd/S )Ar:   zLAn object that lets external threads run code in an asynchronous event loop.rC   c                 C  s
   t ƒ  ¡ S r=   )r   Zcreate_blocking_portal)Úclsr/   r/   r0   Ú__new__�   s    zBlockingPortal.__new__rb   c                 C  s&   t  ¡ | _tƒ | _tƒ | _tƒ | _d S r=   )	Ú	threadingÚ	get_identÚ_event_loop_thread_idr   Ú_stop_eventr   Ú_task_groupr   Ú_cancelled_exc_class©r@   r/   r/   r0   rA   „   s    
zBlockingPortal.__init__c                 Ã  s   | j  ¡ I d H  | S r=   )rj   rD   rl   r/   r/   r0   rD   Š   s    zBlockingPortal.__aenter__rQ   rR   rS   rB   )Úexc_typeÚexc_valÚexc_tbr&   c                 Ã  s$   |   ¡ I d H  | j |||¡I d H S r=   )Ústoprj   rH   )r@   rm   rn   ro   r/   r/   r0   rH   Ž   s    zBlockingPortal.__aexit__c                 C  s,   | j d u rtdƒ‚| j t ¡ kr(tdƒ‚d S )NzThis portal is not runningz7This method cannot be called from the event loop thread)rh   r-   rf   rg   rl   r/   r/   r0   Ú_check_running—   s    
ÿzBlockingPortal._check_runningc                 Ã  s   | j  ¡ I dH  dS )z#Sleep until :meth:`stop` is called.N)ri   r	   rl   r/   r/   r0   Úsleep_until_stoppedŸ   s    z"BlockingPortal.sleep_until_stoppedFÚbool)Úcancel_remainingr&   c                 Ã  s$   d| _ | j ¡  |r | jj ¡  dS )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)rh   ri   rX   rj   Zcancel_scopeÚcancel)r@   rt   r/   r/   r0   rp   £   s    
zBlockingPortal.stopr   Útuplezdict[str, Any]r   )r$   r%   Úkwargsr`   r&   c              
   ƒ  s  dddœ‡ ‡fdd„}zæzf||i |¤Ž}t |ƒr|tƒ �6‰ | ¡ rJˆ  ¡  n
| |¡ |I d H }W d   ƒ n1 sr0    Y  W nd ˆjy¢   | ¡  | ¡  Y nT tyâ } z*| ¡ sÂ| |¡ t	|t
ƒsÎ‚ W Y d }~nd }~0 0 | ¡ sö| |¡ W d ‰ nd ‰ 0 d S )Nr   rb   )Úfr&   c                   s*   |   ¡ r&ˆjd t ¡ fvr&ˆ ˆ j¡ d S r=   )Ú	cancelledrh   rf   rg   rW   ru   )rx   ©Úscoper@   r/   r0   Úcallback¶   s
    þz+BlockingPortal._call_func.<locals>.callback)r   r   ry   ru   Úadd_done_callbackrk   Úset_running_or_notify_cancelrE   rF   Ú
isinstanceÚ	ExceptionrG   )r@   r$   r%   rw   r`   r|   ÚretvalrJ   r/   rz   r0   Ú
_call_func³   s(    

,

zBlockingPortal._call_funcztuple[Any, ...]r"   )r$   r%   rw   Únamer`   r&   c                 C  s   t ‚dS )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

        N)ÚNotImplementedError)r@   r$   r%   rw   rƒ   r`   r/   r/   r0   Ú_spawn_task_from_thread×   s    z&BlockingPortal._spawn_task_from_threadr!   r   r#   c                 G  s   d S r=   r/   ©r@   r$   r%   r/   r/   r0   rW   î   s    zBlockingPortal.callr2   c                 G  s   d S r=   r/   r†   r/   r/   r0   rW   ò   s    z-Callable[..., Awaitable[T_Retval] | T_Retval]c                 G  s   t t| j|g|¢R Ž  ¡ ƒ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   rM   rK   r†   r/   r/   r0   rW   ö   s    N)rƒ   zFuture[T_Retval])r$   r%   rƒ   r&   c                G  s   d S r=   r/   ©r@   r$   rƒ   r%   r/   r/   r0   rM     s    zBlockingPortal.start_task_soonc                G  s   d S r=   r/   r‡   r/   r/   r0   rM     s    c                G  s$   |   ¡  tƒ }|  ||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

        )rq   r   r…   )r@   r$   rƒ   r%   rx   r/   r/   r0   rM     s    zCallable[..., Awaitable[Any]]ztuple[Future[Any], Any]c                  s\   dddœ‡ fdd„}|   ¡  tƒ ‰ tˆ ƒ}tƒ }| |¡ |  ||d|i||¡ |ˆ  ¡ 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

        r   rb   )r`   r&   c                   sH   ˆ   ¡ sD|  ¡ rˆ  ¡  n*|  ¡ r2ˆ  |  ¡ ¡ ntdƒ}ˆ  |¡ d S )Nz1Task exited without calling task_status.started())Údonery   ru   Ú	exceptionrF   r-   )r`   rJ   ©Ztask_status_futurer/   r0   Ú	task_doneJ  s    
ÿz,BlockingPortal.start_task.<locals>.task_doneÚtask_status)rq   r   r^   r}   r…   rK   )r@   r$   rƒ   r%   r‹   rŒ   rx   r/   rŠ   r0   Ú
start_task3  s    
zBlockingPortal.start_taskr9   zContextManager[T_co])rO   r&   c                 C  s
   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

        )r4   rN   r/   r/   r0   Úwrap_async_context_manager^  s    z)BlockingPortal.wrap_async_context_manager)F)rZ   r[   r\   Ú__doc__re   rA   rD   rH   rq   rr   rp   r‚   r…   r   rW   rM   r�   rŽ   r/   r/   r/   r0   r:   ~   s4   	$üÿ	ü!ü+r:   ÚasyncioÚstrzdict[str, Any] | Nonez$Generator[BlockingPortal, Any, None])ÚbackendÚbackend_optionsr&   c                 #  s8  ddœ‡ fdd„}t ƒ ‰ tdƒ�� }|jtj|| |d�}ztttt  |ˆ gƒtd� W n$ t	yz   ˆ  
¡  | 
¡  ‚ Y n0 ˆ  ¡ �rˆ  ¡ }d}zNz
|V  W n t	y¶   d	}‚ Y n0 W z| |j|¡ W n tyÞ   Y n0 n*z| |j|¡ W n t�y   Y n0 0 | ¡  W d
  ƒ n1 �s*0    Y  d
S )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.

    rb   rC   c               	   “  s^   t ƒ 4 I d H š6} ˆ  ¡ r0ˆ  | ¡ |  ¡ I d H  W d   ƒI d H  qZ1 I d H sP0    Y  d S r=   )r:   r~   rG   rr   )Zportal_r_   r/   r0   Ú
run_portal‚  s    
z)start_blocking_portal.<locals>.run_portalr   )r’   r“   )Úreturn_whenFTN)r   r   Úsubmitr   r1   r	   r   r   r   rE   ru   rˆ   rK   rW   rp   r-   )r’   r“   r”   ÚexecutorZ
run_futurer<   Zcancel_remaining_tasksr/   r_   r0   Ústart_blocking_portalp  sF    üþ



ýr˜   )r�   N)1Ú
__future__r   rf   Úcollections.abcr   r   r   Úconcurrent.futuresr   r   r   r	   Ú
contextlibr
   r   Úinspectr   Útypesr   Útypingr   r   r   r   r   r   r   r   Z_corer   Z_core._eventloopr   r   r   Z_core._synchronizationr   Z_core._tasksr   r   Z
abc._tasksr   r   r    r1   r3   r4   r^   r:   r˜   r/   r/   r/   r0   Ú<module>   s.   (4 s ÿ