
    ԋg(                        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 d dlmZ  ej                   e      Z G d d	      Z G d
 d      Zy)    )annotationsN)defaultdict)parse_timedelta)Future)Deadlinewait_for)
get_clientc                  F    e Zd ZdZd Zd
dZddZddZddZddZ	dd	Z
y)QueueExtensionzAn extension for the scheduler to manage queues

    This adds the following routes to the scheduler

    *  queue_create
    *  queue_release
    *  queue_put
    *  queue_get
    *  queue_size
    c                   || _         t               | _        t               | _        t	        t
              | _        | j                   j                  j                  | j                  | j                  | j                  | j                  d       | j                   j                  j                  | j                  | j                  d       y )N)queue_create	queue_put	queue_getqueue_qsize)queue-future-releasequeue_release)	schedulerdictqueuesclient_refcountr   intfuture_refcounthandlersupdatecreateputgetqsizestream_handlersfuture_releaserelease)selfr   s     2lib/python3.12/site-packages/distributed/queues.py__init__zQueueExtension.__init__   s    "f#v*3/&& $!XX!XX#zz		
 	&&--%)%8%84<<X	
    Nc                    t         j                  d|        || j                  vr3t        j                  |      | j                  |<   d| j
                  |<   y | j
                  |xx   dz  cc<   y )NzQueue name: )maxsize   )loggerdebugr   asyncioQueuer   r"   nameclientr'   s       r#   r   zQueueExtension.create0   s^    |D6*+t{{" 'g >DKK)*D  &  &!+&r%   c                b   || j                   vry | j                  |xx   dz  cc<   | j                  |   dk(  rr| j                  |= | j                   |   j                  }| j                   |= |D cg c]  }|d   dk(  s|d    }}|r!| j                  j	                  |d|z         y y y c c}w )Nr(   r   typer   valuequeue-%skeysr/   )r   r   _queuer   client_releases_keys)r"   r.   r/   futuresdr5   s         r#   r!   zQueueExtension.release8   s    t{{"T"a'"%*$$T*kk$'..GD!(/I11V93HAgJDI33jSWFW3X  + Js   0B,>B,c                  K   t        j                  |      }||| j                  j                  vrQt	        j
                  d       d {    |j                  rt        d| d      || j                  j                  vrQd|d}| j                  ||fxx   dz  cc<   | j                  j                  |gd|z         nd	|d}t        | j                  |   j                  |      |j                  
       d {    y 7 7 w)Ng{Gz?zTask z unknown to scheduler.r   )r1   r2   r(   r3   r4   msgpacktimeout)r   afterr   tasksr+   sleepexpiredTimeoutErrorr   client_desires_keysr   r   r   	remaining)r"   r.   keydatar/   r=   deadlinerecords           r#   r   zQueueExtension.putE   s     >>'*?T^^111mmD)))##&se3I'JKK T^^111
 '5F  s+q0+NN..SE*tBS.T'$7Ft{{4(,,V4h>P>PQQQ * 	Rs+   AD
D7DA;D>D?DDc                    | j                   j                  |g|       | j                  ||fxx   dz  cc<   | j                  ||f   dk(  r1| j                   j                  |gd|z         | j                  ||f= y y )Nr4   r(   r   r3   )r   rC   r   r7   )r"   r.   rE   r/   s       r#   r    zQueueExtension.future_releaseT   s    **f*ET3Y'1,'c	*a/NN//cU:PTCT/U$$T3Y/ 0r%   c                "   K    fd}|r j                   |   }g }|du rK|j                         s|j                          d {   }|j                  |       |j                         s:nH|d}	t	        |	      t        |      D ]+  }
|j                          d {   }|j                  |       - |D cg c]
  } ||       }}|S t         j                   |   j                         |       d {   } ||      }|S 7 7 jc c}w 7 w)Nc                $   | d   dk(  r| j                         } | d   }j                  j                  j                  |      }||j                  nd}|| d<   |dk(  r2|j
                  j                  | d<   |j
                  j                  | d<   | S )	zAdd task status if knownr1   r   r2   loststateerred	exception	traceback)copyr   r?   r   rM   exception_blamerO   rP   )rH   rE   tsrM   r"   s       r#   processz#QueueExtension.get.<locals>.process\   s    f~)Wo^^))--c2$&N"'wG#*,*<*<*F*FF;'*,*<*<*F*FF;'Mr%   TzNDask queues don't support simultaneous use of integer batch sizes and timeoutsr<   )r   emptyr   appendNotImplementedErrorranger   )r"   r.   r/   r=   batchrT   qoutrH   msg_os   `           r#   r   zQueueExtension.get[   s     	 D!AC}'')#$557]FJJv& '') &;  .c22uA#$557]FJJv& & (++s!71:sC+J#DKK$5$9$9$;WMMFV_FM# + ++ NsH   A DD%D*1DDD7D/D5D6DDDc                <    | j                   |   j                         S N)r   r   )r"   r.   r/   s      r#   r   zQueueExtension.qsize   s    {{4 &&((r%   NNr   )NN)NNNNN)NNN)NNNF)__name__
__module____qualname____doc__r$   r   r!   r   r    r   r    r%   r#   r   r      s-    	
&,YR0&P)r%   r   c                  x    e Zd ZdZddZd Zed        Zd Zd Z	d Z
dd	Zdd
ZddZd ZddZd Zd Zd Zy)r,   a^  Distributed Queue

    This allows multiple clients to share futures or small bits of data between
    each other with a multi-producer/multi-consumer queue.  All metadata is
    sequentialized through the scheduler.

    Elements of the Queue must be either Futures or msgpack-encodable data
    (ints, strings, lists, dicts).  All data is sent through the scheduler so
    it is wise not to send large objects.  To share large objects scatter the
    data and share the future instead.

    .. warning::

       This object is experimental

    Parameters
    ----------
    name: string (optional)
        Name used by other clients and the scheduler to identify the queue. If
        not given, a random name will be generated.
    client: Client (optional)
        Client used for communication with the scheduler.
        If not given, the default global client will be used.
    maxsize: int (optional)
        Number of items allowed in the queue. If 0 (the default), the queue
        size is unbounded.

    Examples
    --------
    >>> from dask.distributed import Client, Queue  # doctest: +SKIP
    >>> client = Client()  # doctest: +SKIP
    >>> queue = Queue('x')  # doctest: +SKIP
    >>> future = client.submit(f, x)  # doctest: +SKIP
    >>> queue.put(future)  # doctest: +SKIP

    See Also
    --------
    Variable: shared variable between clients
    Nc                    || _         |xs! dt        j                         j                  z   | _        || _        | j                          y )Nzqueue-)_clientuuiduuid4hexr.   r'   _maybe_startr-   s       r#   r$   zQueue.__init__   s9    7Htzz|'7'77	r%   c                    | j                   re| j                   j                  r)t        j                  | j	                               | _        y | j                   j                  | j                         y y r`   )r/   asynchronousr+   ensure_future_start_startedsyncr"   s    r#   rm   zQueue._maybe_start   sI    ;;{{'' ' 5 5dkkm D  -	 r%   c                    | j                   s	 t               | _         | j                   S | j                   S # t        $ r Y | j                   S w xY wr`   )ri   r	   
ValueErrorrt   s    r#   r/   zQueue.client   sJ    ||)| ||t||  ||s   5 	AA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.)r/   RuntimeErrorr1   rt   s    r#   _verify_runningzQueue._verify_running   s.    {{:, ' '  r%   c                   K   | j                   j                  j                  | j                  | j                         d {    | S 7 w)N)r.   r'   )r/   r   r   r.   r'   rt   s    r#   rq   zQueue._start   s<     kk##00dii0VVV 	Ws   ?A
AA
c                      j                          t         d      r j                  j                         S  fd} |       j                         S )Nrr   c                    K    S wr`   rf   rt   s   r#   r]   zQueue.__await__.<locals>._   s     s   )rm   hasattrrr   	__await__)r"   r]   s   ` r#   r~   zQueue.__await__   sA    4$==**,, 3==?"r%   c                2  K   t        |t              rE| j                  j                  j	                  |j
                  || j                         d {    y | j                  j                  j	                  ||| j                         d {    y 7 @7 w)N)rE   r=   r.   )rF   r=   r.   )
isinstancer   r/   r   r   rE   r.   )r"   r2   r=   s      r#   _putz
Queue._put   s     eV$++''11IIwTYY 2    ++''11G$)) 2   	s$   ABB:BBBBc                    | j                          t        |      } | j                  j                  | j                  |fd|i|S )a9  Put data into the queue

        Parameters
        ----------
        timeout : number or string or timedelta, optional
            Time in seconds to wait before timing out.
            Instead of number of seconds, it is also possible to specify
            a timedelta in string format, e.g. "200ms".
        r=   )ry   r   r/   rs   r   )r"   r2   r=   kwargss       r#   r   z	Queue.put   sA     	!'*t{{		5L'LVLLr%   c                    | j                          t        |      } | j                  j                  | j                  f||d|S )a4  Get data from the queue

        Parameters
        ----------
        timeout : number or string or timedelta, optional
            Time in seconds to wait before timing out.
            Instead of number of seconds, it is also possible to specify
            a timedelta in string format, e.g. "200ms".
        batch : boolean, int (optional)
            If True then return all elements currently waiting in the queue.
            If an integer than return that many elements from the queue
            If False (default) then return one item at a time
        )r=   rY   )ry   r   r/   rs   _get)r"   r=   rY   r   s       r#   r   z	Queue.get   sA     	!'*t{{		R7%R6RRr%   c                p    | j                           | j                  j                  | j                  fi |S )z'Current number of elements in the queue)ry   r/   rs   _qsize)r"   r   s     r#   r   zQueue.qsize  s.    t{{6v66r%   c                    K    j                   j                  j                  | j                  |       d {   } fd}|du r
 ||      }|S t	        t        ||            }|S 7 .w)N)r=   r.   rY   c                   | d   dk(  rvt        | d   j                  | d         }| d   dk(  r"|j                  j                  | d   | d          j                  j	                  d	j
                  | d   d
       |S | d   }|S )Nr1   r   r2   rM   )rM   rN   rO   rP   r   )opr.   rE   )r   r/   _state	set_error_send_to_schedulerr.   )r9   r2   r"   s     r#   rT   zQueue._get.<locals>.process  s    yH$qz4;;ajIW:(LL**1[>1[>J..1499QwZX L '
Lr%   F)r/   r   r   r.   listmap)r"   r=   rY   resprT   results   `     r#   r   z
Queue._get  sq     [[**44$))5 5 
 
	 E>T]F  #gt,-F-
s   6A*A(/A*c                   K   | j                   j                  j                  | j                         d {   }|S 7 w)N)r.   )r/   r   r   r.   )r"   r   s     r#   r   zQueue._qsize%  s5     {{,,88dii8HH Is   4?=?c                    | j                          | j                  j                  dk(  r)| j                  j                  d| j                  d       y y )Nrunningr   )r   r.   )ry   r/   statusr   r.   rt   s    r#   closezQueue.close)  s@    ;;*KK**/499+UV +r%   c                J    t        |       | j                  d | j                  ffS r`   )r1   r.   r'   rt   s    r#   
__reduce__zQueue.__reduce__.  s     DzDIItT\\:::r%   ra   r`   )NF)rb   rc   rd   re   r$   rm   propertyr/   ry   rq   r~   r   r   r   r   r   r   r   r   rf   r%   r#   r,   r,      s`    &P.  	#MS$7
2W
;r%   r,   )
__future__r   r+   loggingrj   collectionsr   
dask.utilsr   distributed.clientr   distributed.utilsr   r   distributed.workerr	   	getLoggerrb   r)   r   r,   rf   r%   r#   <module>r      sK    "    # & % 0 )			8	$s) s)lh; h;r%   