o
    ;i                     @   s*   d dl Z d dlZd dlZG dd dZdS )    Nc                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )UserCodeEventLoopa  Run an async event loop as a context manager and handle signals.

    This will run all *user supplied* async code, i.e. async functions, as well as async enter/exit managers

    The following signals are handled while a coroutine is running on the event loop until
    completion (and then handlers are deregistered):

    - `SIGUSR1`: converted to an async task cancellation. Note that this only affects the event
      loop, and the signal handler defined here doesn't run for sync functions.
    - `SIGINT`: Unless the global signal handler has been set to SIGIGN, the loop's signal handler
        is set to cancel the current task and raise KeyboardInterrupt to the caller.
    c                 C   s   t  | _t | _| S N)asyncionew_event_looploopsettasks)self r
   W/home/ubuntu/.local/lib/python3.10/site-packages/modal/_runtime/user_code_event_loop.py	__enter__   s   
zUserCodeEventLoop.__enter__c                 C   sX   | j | j   tjd d dkr| j | j   | jD ]}|  q| j   d S )N      	   )	r   run_until_completeshutdown_asyncgenssysversion_infoshutdown_default_executorr   cancelclose)r	   exc_type	exc_value	tracebacktaskr
   r
   r   __exit__   s   

zUserCodeEventLoop.__exit__c                 C   s*   | j |}| j| || jj |S r   )r   create_taskr   addadd_done_callbackdiscard)r	   coror   r
   r
   r   r   %   s   zUserCodeEventLoop.create_taskc              	      s,  t j| jdd _ fdd}ttjtjk}|s% jtj| t	j
d d dkr9 jtjjd n	 jtjj zAz jW W  jtj |s\ jtj S S  t jyn    jdkrlt Y nw W  jtj |s jtj d S d S  jtj |s jtj w w )N)r   r   c                      s*     j d7  _  j dkr  d S t )N   )_sigintsr   KeyboardInterruptr
   r	   r   r
   r   _sigint_handler/   s
   
z.UserCodeEventLoop.run.<locals>._sigint_handlerr   r   zInput was cancelled by user)r   ensure_futurer   r#   signal	getsignalSIGINTSIG_IGNadd_signal_handlerr   r   SIGUSR1r   r   remove_signal_handlerCancelledErrorr$   )r	   r!   r&   ignore_sigintr
   r%   r   run+   s:   
zUserCodeEventLoop.runN)__name__
__module____qualname____doc__r   r   r   r1   r
   r
   r
   r   r      s    
r   )r   r(   r   r   r
   r
   r
   r   <module>   s   