
    ԋg=                    @   d dl mZ d dlZd dlZd dlZd dlZd dl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 d dlmZmZmZ  ej,                  e      Z G d	 d
      Z G d d      Z G d d      Z e
d       G d d             Z e
d       G d d             Zy)    )annotationsN)defaultdictdeque)_deprecatedparse_timedelta)CommClosedError)time)to_serialize)TimeoutErrorsyncwait_forc                  >    e Zd ZdZd Zd	dZd
dZd	dZd
dZddZ	y)PubSubSchedulerExtensionz>Extend Dask's scheduler with routes to handle PubSub machineryc                   || _         t        t              | _        t        t              | _        t        t              | _        | j                   j                  j                  d| j                  i       | j                   j                  j                  | j                  | j                  | j                  | j                  d       y )Npubsub_add_publisher)pubsub-add-subscriberpubsub-remove-publisherpubsub-remove-subscriber
pubsub-msg)	schedulerr   set
publisherssubscribersclient_subscribershandlersupdateadd_publisherstream_handlersadd_subscriberremove_publisherremove_subscriberhandle_message)selfr   s     2lib/python3.12/site-packages/distributed/pubsub.py__init__z!PubSubSchedulerExtension.__init__   s    "%c*&s+"-c"2&&(>@R@R'ST&&--)-)<)<+/+@+@,0,B,B"11		
    Nc                
   t         j                  d||       | j                  |   j                  |       | j                  |   D ci c]  }|i  c}|| j
                  v xr t        | j
                  |         dkD  dS c c}w )NzAdd publisher: %s %sr   )r   publish-scheduler)loggerdebugr   addr   r   len)r#   nameworkeraddrs       r$   r   z&PubSubSchedulerExtension.add_publisher'   s    +T6:!!&)151A1A$1GH1GD"H1GH!%)@)@!@ "7D++D12Q6
 	
Hs   
B c                   |rjt         j                  d||       | j                  |   j                  |       | j                  |   D ]"  }| j
                  j                  |d||d       $ y |rjt         j                  d||       | j                  |   D ]"  }| j
                  j                  |d|dd       $ | j                  |   j                  |       y y )NzAdd worker subscriber: %s %sr   opaddressr-   zAdd client subscriber: %s %spubsub-publish-schedulerTr2   r-   publish)r)   r*   r   r+   r   r   worker_sendr   r#   r-   r.   clientpubs        r$   r   z'PubSubSchedulerExtension.add_subscriber0   s    LL7vFT"&&v.t,**2vtT -
 LL7vFt,**5tPTU -
 ##D)--f5 r&   c                   || j                   |   v rpt        j                  d||       | j                   |   j                  |       | j                  |   s+| j                   |   s| j                  |= | j                   |= y y y y )NzRemove publisher: %s %s)r   r)   r*   remover   )r#   r-   r.   s      r$   r    z)PubSubSchedulerExtension.remove_publisherB   s|    T__T**LL2D&AOOD!((0##D)$//$2G$$T*OOD) 3H)	 +r&   c                   |rjt         j                  d||       | j                  |   j                  |       | j                  |   D ]"  }| j
                  j                  |d||d       $ n|rt         j                  d||       | j                  |   j                  |       | j                  |   sA| j                  |= | j                  |   D ]"  }| j
                  j                  |d|dd       $ | j                  |   sA| j                  |   s1t         j                  d|       | j                  |= | j                  |= y y y )	NzRemove worker subscriber: %s %sr   r1   zRemove client subscriber: %s %sr4   Fr5   zRemove PubSub topic %s)r)   r*   r   r<   r   r   r7   r   r8   s        r$   r!   z*PubSubSchedulerExtension.remove_subscriberK   s0   LL:D&IT"))&1t,**5&RVW -
 LL:D&I##D)008**40++D1??40CNN.."<$(', 1 %dood.CLL148  &% /D%r&   c                V   t        | j                  |         D ]/  }	 | j                  j                  |   j	                  d||d       1 |r5| j                  |   D ]"  }| j                  j                  |d||d       $ y y # t
        t        f$ r | j                  ||       Y w xY w)Nr   r2   r-   msg)r-   r9   )
listr   r   client_commssendKeyErrorr   r!   r   r7   )r#   r-   r@   r.   r9   csubs          r$   r"   z'PubSubSchedulerExtension.handle_messageh   s    d--d34A<++A.33'cB 5 ''-**d3G .  o. <&&D&;<s   ,B"B('B(NN)NNN)NNNN)
__name__
__module____qualname____doc__r%   r   r   r    r!   r"    r&   r$   r   r      s#    H
"
6$*&:r&   r   c                  B    e Zd ZdZd Zd
dZd
dZd
dZd
dZd Z	d	 Z
y)PubSubWorkerExtensionz;Extend Dask's Worker with routes to handle PubSub machineryc                   || _         | j                   j                  j                  | j                  | j                  | j
                  | j                  d       t        t        j                        | _
        t        t        j                        | _        t        t              | _        | | j                   j                  d<   y )N)r   r   r   r4   pubsub)r.   r   r   r   r!   r"   publish_schedulerr   weakrefWeakSetr   r   boolpublish_to_scheduler
extensions)r#   r.   s     r$   r%   zPubSubWorkerExtension.__init__{   s    ##**)-)<)<,0,B,B"11,0,B,B		
 'w7%goo6$/$5!+/x(r&   Nc                J    | j                   |   D ]  }||j                  |<    y Nr   r   )r#   r-   r3   infor:   s        r$   r   z$PubSubWorkerExtension.add_subscriber   s#    ??4(C'+COOG$ )r&   c                F    | j                   |   D ]  }|j                  |=  y rX   rY   )r#   r-   r3   r:   s       r$   r!   z'PubSubWorkerExtension.remove_subscriber   s!    ??4(C( )r&   c                "    || j                   |<   y rX   )rU   )r#   r-   r6   s      r$   rQ   z'PubSubWorkerExtension.publish_scheduler   s    *1!!$'r&   c                   K   | j                   j                  |g       D ]  }|j                  |       d {     y 7 wrX   )r   get_putr#   r-   r@   rF   s       r$   r"   z$PubSubWorkerExtension.handle_message   s7     ##''b1C((3- 2s   4A >A c                b    | j                   j                  j                  | j                         y rX   )r.   loopadd_callbackcleanupr#   s    r$   trigger_cleanupz%PubSubWorkerExtension.trigger_cleanup       %%dll3r&   c                   t        | j                        j                         D ]H  \  }}t        |      rd|d}| j                  j
                  j                  |       | j                  |= J t        | j                        j                         D ]U  \  }}t        |      rd|d}| j                  j
                  j                  |       | j                  |= | j                  |= W y )Nr   r2   r-   r   )	dictr   itemsr,   r.   batched_streamrC   r   rU   )r#   r-   sr@   ps        r$   rd   zPubSubWorkerExtension.cleanup   s    D,,-335GD!q67F**//4$$T*	 6 DOO,224GD!q66E**//4OOD)--d3 5r&   rG   )rH   rI   rJ   rK   r%   r   r!   rQ   r"   rf   rd   rL   r&   r$   rN   rN   x   s(    E0",)2 44r&   rN   c                  *    e Zd ZdZd ZddZd Zd Zy)PubSubClientExtensionz=Extend Dask's Client with handlers to handle PubSub machineryc                    || _         | j                   j                  j                  d| j                  i       t	        t
        j                        | _        y )Nr   )r9   _stream_handlersr   r"   r   rR   rS   r   )r#   r9   s     r$   r%   zPubSubClientExtension.__init__   s=    $$++\4;N;N,OP&w7r&   Nc                   K   | j                   |   D ]  }|j                  |       d {     | j                   |   s)| j                  j                  j	                  d|d       y y 7 ?w)Nzpubsub-remove-subscribersri   )r   r_   r9   scheduler_commrC   r`   s       r$   r"   z$PubSubClientExtension.handle_message   sf     ##D)C((3- * %KK&&++2DA &  s   'A+A)A A+c                b    | j                   j                  j                  | j                         y rX   )r9   rb   rc   rd   re   s    r$   rf   z%PubSubClientExtension.trigger_cleanup   rg   r&   c                    | j                   j                         D ]2  \  }}|r	d|d}| j                  j                  j	                  |       4 y )Nr   ri   )r   rk   r9   rt   rC   )r#   r-   rm   r@   s       r$   rd   zPubSubClientExtension.cleanup   sD    ''--/GD!7F**//4 0r&   rG   )rH   rI   rJ   rK   r%   r"   rf   rd   rL   r&   r$   rp   rp      s    G845r&   rp   z(Client.log_event() or Worker.log_event())use_insteadc                  4    e Zd ZdZddZd Zd Zd Zd ZeZ	y)	Puba7  Publish data with Publish-Subscribe pattern

    This allows clients and workers to directly communicate data between each
    other with a typical Publish-Subscribe pattern.  This involves two
    components,

    Pub objects, into which we put data:

        >>> pub = Pub('my-topic')
        >>> pub.put(123)

    And Sub objects, from which we collect data:

        >>> sub = Sub('my-topic')
        >>> sub.get()
        123

    Many Pub and Sub objects can exist for the same topic.  All data sent from
    any Pub will be sent to all Sub objects on that topic that are currently
    connected.  Pub's and Sub's find each other using the scheduler, but they
    communicate directly with each other without coordination from the
    scheduler.

    Pubs and Subs use the central scheduler to find each other, but not to
    mediate the communication.  This means that there is very little additional
    latency or overhead, and they are appropriate for very frequent data
    transfers.  For context, most data transfer first checks with the scheduler to find which
    workers should participate, and then does direct worker-to-worker
    transfers.  This checking in with the scheduler provides some stability
    guarantees, but also adds in a few extra network hops.  PubSub doesn't do
    this, and so is faster, but also can easily drop messages if Pubs or Subs
    disappear without notice.

    When using a Pub or Sub from a Client all communications will be routed
    through the scheduler.  This can cause some performance degradation.  Pubs
    and Subs only operate at top-speed when they are both on workers.

    Parameters
    ----------
    name: object (msgpack serializable)
        The name of the group of Pubs and Subs on which to participate.
    worker: Worker (optional)
        The worker to be used for publishing data. Defaults to the value of
        ```get_worker()```. If given, ``client`` must be ``None``.
    client: Client (optional)
        Client used for communication with the scheduler. Defaults to
        the value of ``get_client()``. If given, ``worker`` must be ``None``.

    Examples
    --------
    >>> pub = Pub('my-topic')
    >>> sub = Sub('my-topic')
    >>> pub.put([1, 2, 3])
    >>> sub.get()
    [1, 2, 3]

    You can also use sub within a for loop:

    >>> for msg in sub:  # doctest: +SKIP
    ...     print(msg)

    or an async for loop

    >>> async for msg in sub:  # doctest: +SKIP
    ...     print(msg)

    Similarly the ``.get`` method will return an awaitable if used by an async
    client or within the IOLoop thread of a worker

    >>> await sub.get()  # doctest: +SKIP

    You can see the set of connected worker subscribers by looking at the
    ``.subscribers`` attribute:

    >>> pub.subscribers
    {'tcp://...': {},
     'tcp://...': {}}

    See Also
    --------
    Sub
    Nc                   ||ddl m}m} 	  |       }t	               | _        || _        || _        |s|sJ | j                  r7| j                  j                  | _        | j                  j                  | _	        nB| j                  r6| j                  j                  | _        | j                  j                  | _	        || _
        d| _        g | _        | j                  j                  | j                         | j                  rm| j                  j                  d   }| j                  j                  |j                   |   j"                  |        t%        j&                  | |j(                         y y # t        $ r  |       }Y ow xY w)Nr   
get_client
get_workerFrP   )distributedr|   r}   	Exceptionrj   r   r.   r9   r   rb   r-   _started_bufferrc   _startrV   r   r+   rR   finalizerf   )r#   r-   r.   r9   r|   r}   rP   s          r$   r%   zPub.__init__  s/   >fn:&#  6;;![[22DN((DI[[![[22DN((DI			t{{+;;[[++H5FII""6#4#4T#:#>#>ET6#9#9: )  &#&s   E1 1FFc                  K   | j                   r| j                  j                  | j                  | j                   j                         d {   }| j                   j
                  d   }| j                  j                  |d          |d   |j                  | j                  <   d| _	        | j                  D ]  }| j                  |        | j                  d d = y 7 w)N)r-   r.   rP   r   r(   T)r.   r   r   r-   r3   rV   r   r   rU   r   r   put)r#   resultrP   r@   s       r$   r   z
Pub._start=  s     ;;>>>>YYt{{':': ?  F [[++H5F##F=$9:5;<O5PF''		2<<CHHSM  LLOs   AC CBC c                
   | j                   s| j                  j                  |       y d| j                  t	        |      d}| j
                  r| j                  D ]  }| j
                  j                  ||         | j
                  j                  d   j                  | j                     r&| j
                  j                  j                  |       y y | j                  r&| j                  j                  j                  |       y y )Nr   r?   rP   )r   r   appendr-   r
   r.   r   send_to_workerrV   rU   rl   rC   r9   rt   )r#   r@   datarF   s       r$   r_   zPub._putL  s    }}LL$"DIIl3>OP;;''**35 ( {{%%h/DDTYYO**//5 P[[KK&&++D1 r&   c                P    | j                   j                  | j                  |       y)z2Publish a message to all subscribers of this topicN)rb   rc   r_   r#   r@   s     r$   r   zPub.put\  s    		tyy#.r&   c                "    d| j                    dS )Nz<Pub: >r-   re   s    r$   __repr__zPub.__repr__`      		{!$$r&   rG   )
rH   rI   rJ   rK   r%   r   r_   r   r   __str__rL   r&   r$   ry   ry      s)    Qf;>2 /% Gr&   ry   zClient.subscribe_topic()c                  `    e Zd ZdZddZed        ZddZeZddZ	e	xZ
Zd Zd Zd	 Zd
 ZeZy)SubzbSubscribe to a Publish/Subscribe topic

    See Also
    --------
    Pub: for full docstring
    Nc                   ||ddl m}m} 	  |       }|| _        || _        | j                  r| j                  j                  | _        n'| j
                  r| j
                  j                  | _        || _        t               | _	        | j                  r| j                  j                  d   }n%| j
                  r| j
                  j                  d   }| j                  j                  j                  |   j                  |        d| j                  d}| j                  r;| j                  j                  | j                  j                  j                  |       nQ| j
                  r;| j                  j                  | j
                  j                   j                  |       n
t               t#        j$                  | |j&                         y # t        $ r  |       }Y w xY w)Nr   r{   rP   r   ri   )distributed.workerr|   r}   r   r.   r9   rb   r-   r   bufferrV   rc   r   r+   rl   rC   rt   rR   r   rf   )r#   r-   r.   r9   r|   r}   rP   r@   s           r$   r%   zSub.__init__o  s_   >fnA&# ;;((DI[[((DI	g;;[[++H5F[[[[++H5F		v11$7;;TB,dii@;;II""4;;#=#=#B#BCH[[II""4;;#=#=#B#BCH+v5565  &#&s   G G"!G"c                    	 | j                   S # t        $ r( t        j                         | _         | j                   cY S w xY wrX   )
_conditionAttributeErrorasyncio	Conditionre   s    r$   	conditionzSub.condition  s:    	#??" 	#%//1DO??"	#s    .??c                   K   t               } j                  si||t               |z
  z
  }|dk  rt               d } fd}	 t         |       |       d {     j                  j                           j                  si j                  j                         S 7 E#  j                  j                          w xY ww)Nr   c                    K    j                   j                          d {     j                   j                          d {    y 7 '7 wrX   )r   acquirewaitre   s   r$   _zSub._get.<locals>._  s<     nn,,...nn))+++ /+s!   AA	!AAAA)r	   r   r   r   r   releasepopleft)r#   timeoutstarttimeout2r   s   `    r$   _getzSub._get  s     ++""dfun5a<&.(,)qsH---&&( ++" {{""$$	 .&&(s5   ?B>B BB &B>B>B B;;B>c                   t        |      }| j                  r'| j                  j                  | j                  |      S | j                  j
                  t        j                         k(  r| j                         S | j                  r| j                  j                         S t        | j                  | j                  |      S )a6  Get a single message

        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   )r   r9   r   r   r.   	thread_id	threading	get_identr   r   rb   )r#   r   s     r$   r^   zSub.get  s     "'*;;;;##DIIw#??[[""i&9&9&;;99;{{{{**,,		499g>>r&   c                    | S rX   rL   re   s    r$   __iter__zSub.__iter__      r&   c                    | S rX   rL   re   s    r$   	__aiter__zSub.__aiter__  r   r&   c                   K   | j                   j                  |       | j                  4 d {    | j                  j                          d d d       d {    y 7 /7 # 1 d {  7  sw Y   y xY wwrX   )r   r   r   notifyr   s     r$   r_   zSub._put  sD     3>>>NN!!# ">>>>>>sD   ,A7AA7A"A7A A7 A7"A4(A+)A40A7c                "    d| j                    dS )Nz<Sub: r   r   re   s    r$   r   zSub.__repr__  r   r&   rG   rX   )rH   rI   rJ   rK   r%   propertyr   r   	__anext__r^   next__next__r   r   r_   r   r   rL   r&   r$   r   r   f  sY     7D # #%* I?( D8$
% Gr&   r   )
__future__r   r   loggingr   rR   collectionsr   r   
dask.utilsr   r   distributed.corer   distributed.metricsr	   distributed.protocol.serializer
   distributed.utilsr   r   r   	getLoggerrH   r)   r   rN   rp   ry   r   rL   r&   r$   <module>r      s    "     * 3 , $ 7 : :			8	$b bJ24 24j5 58 CDY Y EYx 34m m 5mr&   