
    ԋgX!                        d dl mZ d dlZd dlZd dlZd dl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  ej"                  e      Z G d d	      Z G d
 d      Zy)    )annotationsN)defaultdict)suppress)parse_timedelta)TimeoutError
log_errorswait_for)
get_clientc                  j    e Zd ZdZd Zed
d       Zedd       Zedd       Zedd       Z	d Z
d	 Zy)EventExtensiona  An extension for the scheduler to manage Events

    This adds the following routes to the scheduler

    *  event_wait
    *  event_set
    *  event_clear
    *  event_is_set

    In principle, the implementation logic is quite simple
    as we can reuse the asyncio.Event as much as possible:
    we keep a mapping from name to an asyncio.Event and call
    every function (wait, set, clear, is_set) directly on these
    events.

    However, this would cause a memory leak: created events in the
    dictionary are never removed.
    For this, we also keep a counter for the number of waiters on
    a specific event.
    If an event is set, we need to keep track of this state so
    we can not remove it (the default flag is false).
    If it is unset but there are waiters, we can also not remove
    it, as those waiters would then have dangling futures.
    Therefore the only time we can remove the event from our dict
    is when the number of waiters is 0 and the event flag is cleared.
    c                   || _         t        t        j                        | _        t        t
              | _        | j                   j                  j                  | j                  | j                  | j                  | j                  d       y )N)
event_wait	event_setevent_clearevent_is_set)	schedulerr   asyncioEvent_eventsint_waiter_counthandlersupdater   r   r   r   )selfr   s     1lib/python3.12/site-packages/distributed/event.py__init__zEventExtension.__init__-   se    ""7==1 )-&&"oo!^^#// $ 1 1		
    Nc                  K   | j                  |      }| j                  |   }|j                         }|t        ||      }| j                  |xx   dz  cc<   	 | d{    	 | j                  |xx   dz  cc<   | j                  |   s!|j                         s| j                  |       y7 M# t
        $ rL Y | j                  |xx   dz  cc<   | j                  |   s#|j                         s| j                  |       yyyw xY w# | j                  |xx   dz  cc<   | j                  |   s#|j                         s| j                  |       w w w xY ww)zWait until the event is set to true.
        Returns false, when this did not happen in the given time
        and true otherwise.
        N   FT)_normalize_namer   waitr	   r   r   is_set_delete_event)r   nametimeouteventfutures        r   r   zEventExtension.event_wait>   sI     ##D)T"fg.F4 A% 	)LL t$)$%%d+ELLN ""4(  	t$)$%%d+ELLN ""4(	 5C+	 t$)$%%d+ELLN ""4(	 5C+sQ   AEB. B,B. $AE,B. .	D7D 8A
EDD AEEc                `    | j                  |      }| j                  |   j                          y)zhSet the event with the given name to true.

        All waiters on this event will be notified.
        N)r    r   setr   r$   s     r   r   zEventExtension.event_set[   s+     ##D) 	T r   c                    | j                  |      }| j                  |   s| j                  |       y|| j                  v sJ | j                  |   }|j	                          y)z+Set the event with the given name to false.N)r    r   r#   r   clear)r   r$   r&   s      r   r   zEventExtension.event_clearf   s]     ##D)!!$' t$ 4<<'''LL&EKKMr   c                |    | j                  |      }|| j                  vry| j                  |   j                         S )NF)r    r   r"   r*   s     r   r   zEventExtension.event_is_set{   s;    ##D)
 t||#||D!((**r   c                <    t        |t              rt        |      }|S )z*Helper function to normalize an event name)
isinstancelisttupler*   s     r   r    zEventExtension._normalize_name   s    dD!;Dr   c                    t        t              5  | j                  |= ddd       t        t              5  | j                  |= ddd       y# 1 sw Y   /xY w# 1 sw Y   yxY w)z"Helper function to delete an eventN)r   KeyErrorr   r   r*   s     r   r#   zEventExtension._delete_event   sK     h""4(  hT"    s   AAAA!NNN)__name__
__module____qualname____doc__r   r   r   r   r   r   r    r#    r   r   r   r      sf    6
"  8 ! !  ( 	+ 	+#r   r   c                  T    e Zd ZdZddZed        Zd Zd ZddZ	d Z
d	 Zd
 Zd Zy)r   a  Distributed Centralized Event equivalent to asyncio.Event

    An event stores a single flag, which is set to false on start.
    The flag can be set to true (using the set() call) or back to false
    (with the clear() call).
    Every call to wait() blocks until the event flag is set to true.

    Parameters
    ----------
    name: string (optional)
        Name of the event.  Choosing the same name allows two
        disconnected processes to coordinate an event.
        If not given, a random name will be generated.
    client: Client (optional)
        Client to use for communication with the scheduler.
        If not given, the default global client will be used.

    Examples
    --------
    >>> event_1 = Event('a')  # doctest: +SKIP
    >>> event_1.wait(timeout=1)  # doctest: +SKIP
    >>> # in another process
    >>> event_2 = Event('a')  # doctest: +SKIP
    >>> event_2.set() # doctest: +SKIP
    >>> # now event_1 will stop waiting
    Nc                f    || _         |xs! dt        j                         j                  z   | _        y )Nzevent-)_clientuuiduuid4hexr$   )r   r$   clients      r   r   zEvent.__init__   s&    7Htzz|'7'77	r   c                    | j                   s	 t               | _         | j                   S | j                   S # t        $ r Y | j                   S w xY wr5   )r=   r
   
ValueErrorr   s    r   rA   zEvent.client   sJ    ||)| ||t||  ||s   5 	AAc                8      fd} |       j                         S )zasync constructor

        Make it possible to write

        >>> event = await Event("x") # doctest: +SKIP

        even though no waiting is implied
        c                    K    S wr5   r:   rD   s   r   _zEvent.__await__.<locals>._   s     Ks   )	__await__)r   rG   s   ` r   rH   zEvent.__await__   s    	 s}}r   c                J    | j                   st        t        |        d      y )Nz object not properly initialized. This can happen if the object is being deserialized outside of the context of a Client or Worker.)rA   RuntimeErrortyperD   s    r   _verify_runningzEvent._verify_running   s.    {{:, ' '  r   c                    | j                          t        |      }| j                  j                  | j                  j                  j
                  | j                  |      }|S )a  Wait until the event is set.

        Parameters
        ----------
        timeout : number or string or timedelta, optional
            Seconds to wait on the event in the scheduler.  This does not
            include local coroutine time, network transfer time, etc..
            Instead of number of seconds, it is also possible to specify
            a timedelta in string format, e.g. "200ms".

        Examples
        --------
        >>> event = Event('a')  # doctest: +SKIP
        >>> event.wait(timeout="1s")  # doctest: +SKIP

        Returns
        -------
        True if the event was set of false, if a timeout happened
        )r$   r%   )rL   r   rA   syncr   r   r$   )r   r%   results      r   r!   z
Event.wait   sU    ( 	!'*!!KK!!,,499g " 
 r   c                    | j                          | j                  j                  | j                  j                  j                  | j
                        S )zVClear the event (set its flag to false).

        All waiters will now block.
        r$   )rL   rA   rN   r   r   r$   rD   s    r   r,   zEvent.clear   s>    
 	{{ 5 5 A A		RRr   c                    | j                          | j                  j                  | j                  j                  j                  | j
                        }|S )zZSet the event (set its flag to false).

        All waiters will now be released.
        rQ   )rL   rA   rN   r   r   r$   r   rO   s     r   r)   z	Event.set   sB    
 	!!$++"7"7"A"A		!Rr   c                    | j                          | j                  j                  | j                  j                  j                  | j
                        }|S )zCheck if the event is setrQ   )rL   rA   rN   r   r   r$   rS   s     r   r"   zEvent.is_set  s@    !!$++"7"7"D"D499!Ur   c                (    t         | j                  ffS r5   )r   r$   rD   s    r   
__reduce__zEvent.__reduce__  s    		|$$r   r4   r5   )r6   r7   r8   r9   r   propertyrA   rH   rL   r!   r,   r)   r"   rV   r:   r   r   r   r      sD    68  8S%r   r   )
__future__r   r   loggingr>   collectionsr   
contextlibr   
dask.utilsr   distributed.utilsr   r   r	   distributed.workerr
   	getLoggerr6   loggerr   r   r:   r   r   <module>ra      sN    "    #  & @ @ )			8	$D# D#Nt% t%r   