U
    (–€h¨   ã                   @  sÜ   d dl mZ dZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
Z
d dlmZmZmZmZmZmZ d dlmZmZmZ d dlmZ ddlmZ G d	d
„ d
ejƒZedƒZeG dd„ dƒƒZdddœdd„Zdd„ ZdS )é    )Úannotations)ÚRunnerÚrunN)ÚAbstractEventLoopÚ
coroutinesÚeventsÚ
exceptionsÚtasksÚ	constants)ÚAnyÚTypeVarÚfinal)ÚSelfé   )Útask_factoryc                   @  s   e Zd ZdZdZdZdS )Ú_StateÚcreatedZinitializedÚclosedN)Ú__name__Ú
__module__Ú__qualname__ÚCREATEDÚINITIALIZEDÚCLOSED© r   r   ú5/tmp/pip-unpacked-wheel-rrqp3fat/taskgroup/runners.pyr      s   r   Ú_Tc                   @  sŠ   e Zd ZdZdddœddddœdd	„Zd
dœdd„Zdd„ Zddœdd„Zddœdd„Zddœddddœdd„Z	ddœdd„Z
dd„ ZdS ) r   a5  A context manager that controls event loop life cycle.

    The context manager always creates a new event loop,
    allows to run async functions inside it,
    and properly finalizes the loop at the context manager exit.

    If debug is True, the event loop will be run in debug mode.
    If loop_factory is passed, it is used for new event loop creation.

    asyncio.run(main(), debug=True)

    is a shortcut for

    with asyncio.Runner(debug=True) as runner:
        runner.run(main())

    The run() method can be called multiple times within the runner's context.

    This can be useful for interactive console (e.g. IPython),
    unittest runners, console tools, -- everywhere when async code
    is called from existing sync framework and where the preferred single
    asyncio.run() call doesn't work.

    N©ÚdebugÚloop_factoryzbool | Nonez6collections.abc.Callable[[], AbstractEventLoop] | NoneÚNone)r   r   Úreturnc                C  s0   t j| _|| _|| _d | _d | _d| _d| _d S )Nr   F)	r   r   Ú_stateÚ_debugÚ_loop_factoryÚ_loopÚ_contextÚ_interrupt_countÚ_set_event_loop)Úselfr   r   r   r   r   Ú__init__?   s    zRunner.__init__r   )r!   c                 C  s   |   ¡  | S ©N)Ú
_lazy_init©r)   r   r   r   Ú	__enter__M   s    zRunner.__enter__c                 C  s   |   ¡  d S r+   )Úclose)r)   Úexc_typeÚexc_valÚexc_tbr   r   r   Ú__exit__Q   s    zRunner.__exit__c              	   C  s    | j tjk	rdS | j}|dk	s"t‚zPt
|ƒ | | ¡ ¡ tjdkrX| | tj¡¡ ntjdkrp| | ¡ ¡ W 5 | jr„t d¡ | ¡  d| _tj	| _ X dS )zShutdown and close event loop.N)é   é   )r4   é	   )r"   r   r   r%   ÚAssertionErrorr(   r   Úset_event_loopr/   r   Ú_cancel_all_tasksÚrun_until_completeZshutdown_asyncgensÚsysÚversion_infoZshutdown_default_executorr
   ZTHREAD_JOIN_TIMEOUT)r)   Úloopr   r   r   r/   T   s$    

ÿ

zRunner.closer   c                 C  s   |   ¡  | jdk	st‚| jS )zReturn embedded event loop.N)r,   r%   r7   r-   r   r   r   Úget_loopk   s    zRunner.get_loop©Úcontextz'collections.abc.Coroutine[Any, Any, _T]zcontextvars.Context | Noner   )Úcoror@   r!   c             
   C  sd  t  |¡std |¡ƒ‚t ¡ dk	r,tdƒ‚|  ¡  | jdk	sBt	‚|dkrP| j
}t| j||d�}t ¡ t ¡ krÀt tj¡tjkrÀtj| j|d�}zt tj|¡ W qÄ tk
r¼   d}Y qÄX nd}d| _zfz| j |¡W W ¢TS  tjk
�r,   | jdk�r&t|ddƒ}|dk	�r&|ƒ dk�r&tƒ ‚‚ Y nX W 5 |dk	�r^t tj¡|k�r^t tjtj¡ X dS )z/Run a coroutine inside the embedded event loop.z"a coroutine was expected, got {!r}Nz7Runner.run() cannot be called from a running event loopr?   )Ú	main_taskr   Úuncancel)r   ÚiscoroutineÚ
ValueErrorÚformatr   Ú_get_running_loopÚRuntimeErrorr,   r%   r7   r&   Ú_task_factoryÚ	threadingÚcurrent_threadÚmain_threadÚsignalÚ	getsignalÚSIGINTÚdefault_int_handlerÚ	functoolsÚpartialÚ
_on_sigintr'   r:   r   ZCancelledErrorÚgetattrÚKeyboardInterrupt)r)   rA   r@   ÚtaskZsigint_handlerrC   r   r   r   r   q   sF    
ÿÿþÿþz
Runner.runc                 C  s–   | j tjkrtdƒ‚| j tjkr$d S | jd krRt ¡ | _| j	s\t 
| j¡ d| _	n
|  ¡ | _| jd k	rt| j | j¡ | j t¡ t ¡ | _tj| _ d S )NzRunner is closedT)r"   r   r   rH   r   r$   r   Znew_event_loopr%   r(   r8   r#   Z	set_debugZset_task_factoryrI   ÚcontextvarsZcopy_contextr&   r-   r   r   r   r,   §   s    




zRunner._lazy_initc                 C  sT   | j d k	st‚|  jd7  _| jdkrJ| ¡ sJ| ¡  | j  dd„ ¡ d S tƒ ‚d S )Nr   c                   S  s   d S r+   r   r   r   r   r   Ú<lambda>Á   ó    z#Runner._on_sigint.<locals>.<lambda>)r%   r7   r'   ÚdoneÚcancelZcall_soon_threadsaferU   )r)   ÚsignumÚframerB   r   r   r   rS   »   s    zRunner._on_sigint)r   r   r   Ú__doc__r*   r.   r3   r/   r>   r   r,   rS   r   r   r   r   r   "   s   ü
ü6r   r   c             
   C  sB   t  ¡ dk	rtdƒ‚t||d��}| | ¡W  5 Q R £ S Q R X dS )az  Execute the coroutine and return the result.

    This function runs the passed coroutine, taking care of
    managing the asyncio event loop, finalizing asynchronous
    generators and closing the default executor.

    This function cannot be called when another asyncio event loop is
    running in the same thread.

    If debug is True, the event loop will be run in debug mode.

    This function always creates a new event loop and closes it at the end.
    It should be used as a main entry point for asyncio programs, and should
    ideally only be called once.

    The executor is given a timeout duration of 5 minutes to shutdown.
    If the executor hasn't finished within that duration, a warning is
    emitted and the executor is closed.

    Example:

        async def main():
            await asyncio.sleep(1)
            print('hello')

        asyncio.run(main())
    Nz8asyncio.run() cannot be called from a running event loopr   )r   rG   rH   r   r   )Úmainr   r   Úrunnerr   r   r   r   Æ   s    r   c                 C  st   t  | ¡}|sd S |D ]}| ¡  q|  t j|ddiŽ¡ |D ]0}| ¡ rLq>| ¡ d k	r>|  d| ¡ |dœ¡ q>d S )NZreturn_exceptionsTz1unhandled exception during asyncio.run() shutdown)ÚmessageÚ	exceptionrV   )r	   Z	all_tasksr[   r:   ZgatherZ	cancelledrb   Zcall_exception_handler)r=   Z	to_cancelrV   r   r   r   r9   ê   s     

ýÿr9   ) Ú
__future__r   Ú__all__r;   Úcollections.abcÚcollectionsrW   ÚenumrQ   rM   rJ   Zasyncior   r   r   r   r	   r
   Útypingr   r   r   Ztyping_extensionsr   r   rI   ÚEnumr   r   r   r   r9   r   r   r   r   Ú<module>   s&     $$