Ë
    òÏjH=  ã                  ó  — d Z 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 ddl	m
Z
mZmZmZ ddlmZmZ ddlmZ ddlmZmZ dd	lmZmZ  G d
„ d«      Z ej4                  e«      Ze G d„ d«      «       Zddœdd„Z G d„ d«      Zy)aÉ  Stream controller: subscription registry and fan-out for AsyncThreadStream.

`StreamController` manages the set of active subscriptions against one shared
SSE connection, routing events from the shared stream to per-subscription
queues.  It is the centralised place for:

- subscription registration / teardown
- shared-stream lifecycle (open, rotate, close)
- dedup of replayed events across rotations
- fan-out from the shared stream to subscriber queues
é    )ÚannotationsN)ÚOrderedDict)ÚAsyncGeneratorÚAsyncIteratorÚ	AwaitableÚCallable)Ú	dataclassÚfield)ÚAny)ÚEventÚSubscribeParams)ÚAsyncProtocolTransportÚEventStreamHandlec                  ó4   — e Zd ZdZdZdd	d„Zd
d„Zdd„Zd„ Zy)Ú_SeenEventIdsz)LRU set of event ids with bounded memory.)Ú_dataÚ_maxsizec                ó0   — t        «       | _        || _        y ©N)r   r   r   )ÚselfÚmaxsizes     ú\/var/www/html/gaurav-v2/venv/lib/python3.12/site-packages/langgraph_sdk/stream/controller.pyÚ__init__z_SeenEventIds.__init__&   s   € Ü-8«]ˆŒ
Øˆ�ó    c                óô   — || j                   v r| j                   j                  |«       y d | j                   |<   t        | j                   «      | j                  kD  r| j                   j	                  d¬«       y y )NF)Úlast)r   Úmove_to_endÚlenr   Úpopitem©r   Úevent_ids     r   Úaddz_SeenEventIds.add*   s_   € Ø�t—z‘zÑ!Ø�J‰J×"Ñ" 8Ô,ØØ#ˆ�
‰
�8ÑÜˆt�z‰z‹?˜TŸ]™]Ò*Ø�J‰J×Ñ EÐÕ*ð +r   c                ó   — || j                   v S r   )r   r    s     r   Ú__contains__z_SeenEventIds.__contains__2   s   € Ø˜4Ÿ:™:Ð%Ð%r   c                ó,   — t        | j                  «      S r   )Úiterr   ©r   s    r   Ú__iter__z_SeenEventIds.__iter__5   s   € Ü�D—J‘JÓÐr   N)é'  )r   ÚintÚreturnÚNone)r!   Ústrr+   r,   )r!   Úobjectr+   Úbool)	Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú	__slots__r   r"   r$   r(   © r   r   r   r   !   s   „ Ù3à%€Iô ó+ó&ó r   r   c                  óV   — e Zd ZU dZded<   ded<    eej                  ¬«      Zded<   y	)
Ú_SubscriptionzDInternal record for one active subscription on a `StreamController`.r*   Úidr   Úparams)Údefault_factoryzasyncio.QueueÚqueueN)	r0   r1   r2   r3   Ú__annotations__r
   ÚasyncioÚQueuer;   r5   r   r   r7   r7   @   s#   … áNàƒGØÓÙ °·±Ô?€Eˆ=Ô?r   r7   g        )Údelayc             ƒ  ó‚   K  — |rt        j                  |«      ƒ d{  –—†  | j                  «       ƒ d{  –—†  y7 Œ7 Œ­w)zÆClose a handle, optionally after a brief delay.

    Used to detach closing the old stream from the synchronous rotation step
    so the new stream can absorb server-side replayed events first.
    N)r=   ÚsleepÚclose)Úhandler?   s     r   Ú_close_afterrD   P   s5   è ø€ ñ Ü�m‰m˜EÓ"×"Ð"Ø
�,‰,‹.×Ñð 	#øØús   ‚?�;ž?µ=¶?½?c                  ó  — e Zd ZdZdddddddœ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd	„Zddd
œ	 	 	 	 	 	 	 dd„Zdd„Zdd„Zd d„ZeZ	eZ
	 	 	 	 d!d„Zdd„ZeZdd„Zd"d„Zd#d„Zd$d„Zd$d„Z	 d%	 	 	 d&d„Zd'd„Zd(d„Zd'd„Zd)d„Zd*d„Zy)+ÚStreamControllera  Manages subscriptions and fan-out against one shared SSE connection.

    Responsibilities:
      - subscription registry (register / unregister)
      - shared-stream lifecycle (open on first subscribe, rotate on filter widen)
      - dedup of replayed events via a bounded LRU `_SeenEventIds`
      - fan-out from the shared stream to per-subscription queues

    Args:
        transport: the `AsyncProtocolTransport` bound to this thread session.
        run_start_gate: zero-argument async callable that resolves once the
            current `run.start` has committed server-side (no-op when no
            run is in flight).
        max_queue_size: per-subscription queue bound (default 1024).
        seen_event_ids_max: LRU cap for the dedup set (default 10_000).
    Ni   r)   é   gš™™™™™¹?g       @)Úrun_start_gateÚmax_queue_sizeÚseen_event_ids_maxÚmax_reconnect_attemptsÚreconnect_backoff_baseÚreconnect_backoff_capc               óì   — || _         || _        t        |¬«      | _        d| _        i | _        d | _        d | _        d | _        t        «       | _
        d| _        d | _        || _        || _        || _        y )N©r   é   F)Ú
_transportÚ_max_queue_sizer   Ú_seen_event_idsÚ_next_subscription_idÚ_subscriptionsÚ_shared_streamÚ_shared_stream_filterÚ_fanout_taskÚsetÚ_rotation_close_tasksÚ_closedÚ_cursorÚ_max_reconnect_attemptsÚ_reconnect_backoff_baseÚ_reconnect_backoff_cap)r   Ú	transportrH   rI   rJ   rK   rL   rM   s           r   r   zStreamController.__init__r   sy   € ð $ˆŒØ-ˆÔÜ,Ð5GÔHˆÔØ%&ˆÔ"Ø8:ˆÔØ8<ˆÔØ<@ˆÔ"Ø7;ˆÔÜ>A»eˆÔ"ØˆŒØ#'ˆŒØ'=ˆÔ$Ø'=ˆÔ$Ø&;ˆÕ#r   )Ú
namespacesÚdepthc               óZ   — dt        |«      i}|�||d<   |�||d<   | j                  |«      S )a  Open a typed subscription against the shared SSE.

        Returns an async iterator that yields raw `Event` dicts matching the
        given filter. Multiple concurrent subscribes share one HTTP connection
        whose union expands or rotates as subscriptions come and go.
        Úchannelsra   rb   )ÚlistÚ_subscription_iter)r   rd   ra   rb   r9   s        r   Ú	subscribezStreamController.subscribe�   sB   € ð $.¬t°H«~Ð">ˆØÐ!Ø#-ˆF�<Ñ ØÐØ#ˆF�7‰OØ×&Ñ& vÓ.Ð.r   c              ƒ  óò  K  — | j                   ryd| _         | j                  �_| j                  j                  «        t        j                  t
        t        j                  «      5  | j                  ƒ d{  –—†  ddd«       | j                  �"| j                  j                  «       ƒ d{  –—†  | j                  r(t        j                  | j                  ddiŽƒ d{  –—†  yy7 Œo# 1 sw Y   ŒnxY w7 ŒG7 Œ­w)z?Tear down the controller, awaiting any pending rotation closes.NTÚreturn_exceptions)r[   rX   ÚcancelÚ
contextlibÚsuppressÚ	Exceptionr=   ÚCancelledErrorrV   rB   rZ   Úgatherr'   s    r   rB   zStreamController.close¤   sÉ   è ø€ à�<Š<ØØˆŒØ×ÑÐ(Ø×Ñ×$Ñ$Ô&Ü×$Ñ$¤Y´×0FÑ0FÕGØ×'Ñ'×'Ð'÷ Hà×ÑÐ*Ø×%Ñ%×+Ñ+Ó-×-Ð-Ø×%Ò%Ü—.‘. $×"<Ñ"<ÐUÐPTÑU×UÑUð &ð (ø÷ HÐGúð .øàUúsN   ‚A#C7Á%C'Á5C%Á6C'Á:1C7Â+C3Â,2C7ÃC5ÃC7Ã%C'Ã'C0Ã,C7Ã5C7c                óÎ   — t        | j                  |t        j                  | j                  ¬«      ¬«      }| xj                  dz  c_        || j
                  |j                  <   |S )zDAllocate a subscription id, create a bounded queue, add to registry.rO   )r8   r9   r;   rP   )r7   rT   r=   r>   rR   rU   r8   )r   r9   Úsubs      r   Ú_register_subscriptionz'StreamController._register_subscription¶   sV   € äØ×)Ñ)ØÜ—-‘-¨×(<Ñ(<Ô=ô
ˆð
 	×"Ò" aÑ'Õ"Ø&)ˆ×Ñ˜CŸF™FÑ#Øˆ
r   c                ó<   — | j                   j                  |d«       y)zARemove a subscription from the registry. No-op if already absent.N)rU   Úpop)r   Úsubscription_ids     r   Ú_unregister_subscriptionz)StreamController._unregister_subscriptionÁ   s   € à×Ñ×Ñ °Õ6r   c               óª  K  — | j                  |«      }	 | j                  r	 | j                  |j                  «       y | j	                  |«      ƒ d {  –—†  | j                  «        	 |j                  j                  «       ƒ d {  –—† }|€	 | j                  |j                  «       y |­–— ŒG7 Œ\7 Œ+# | j                  |j                  «       w xY w­wr   )rr   r[   rv   r8   Ú_reconcile_streamÚ_ensure_fanout_runningr;   Úget)r   r9   rq   Úitems       r   rf   z#StreamController._subscription_iterÉ   sº   è ø€ ð ×)Ñ)¨&Ó1ˆð	2Ø�|Š|Øð ×)Ñ)¨#¯&©&Õ1ð ×(Ñ(¨Ó0×0Ð0Ø×'Ñ'Ô)ØØ ŸY™YŸ]™]›_×,�Ø�<Øð ×)Ñ)¨#¯&©&Õ1ð “
ð	 ð 1øð -ùð
 ×)Ñ)¨#¯&©&Õ1üsJ   ‚C•B3 ¢C¾B3 ÁB/Á2B3 ÂB1ÂB3 ÂCÂ)B3 Â1B3 Â3CÃCc                ó¢   — | j                   �| j                   j                  «       r)t        j                  | j	                  «       «      | _         y y r   )rX   Údoner=   Úcreate_taskÚ_fanoutr'   s    r   ry   z'StreamController._ensure_fanout_runningÞ   s>   € Ø×ÑÐ$¨×(9Ñ(9×(>Ñ(>Ô(@Ü '× 3Ñ 3°D·L±L³NÓ CˆDÕð )Ar   c              ƒ  óÖ  K  — ddl m} | j                  �sS| j                  }|€y	 | j	                  |j
                  «      2 3 d{  –—† }| j                  r nXt        | j                  j                  «       «      D ]1  } |||j                  «      sŒ|j                  j                  |«       Œ3 Œo| j                  |u r�|j                  ƒ d{  –—† }|�†t!        |t"        j$                  «      sl| j                  s`t'        j(                  t        «      5  | j                  j+                  «       ƒ d{  –—†  ddd«       | j-                  «       ƒ d{  –—† }|r�ŒQn| j                  s�ŒS| j                  j                  «       D ]  }|j                  j                  d«       Œ y7 �Œ_6 Œù# t        $ r!}t        j                  d|«       Y d}~�Œd}~ww xY w7 �Œ	7 Œ§# 1 sw Y   Œ¦xY w7 Œ•­w)a2  Single consumer of the shared SSE; routes events to subscriptions.

        Why: rotation in `_reconcile_stream` replaces `_shared_stream` mid-loop.
        Re-read `self._shared_stream` on each outer iteration so we always
        consume from the current handle. The old handle's iterator exhausts
        naturally after `_close_after` closes it.

        On a post-ready transport drop (non-cancelled error in `shared.done`),
        attempts to reconnect up to `_max_reconnect_attempts` times before
        giving up and closing subscriber queues.
        r   )Úmatches_subscriptionNztransport drop in fanout: %r)Ú!langgraph_sdk.stream.subscriptionr�   r[   rV   Ú_dedup_iterÚeventsre   rU   Úvaluesr9   r;   Ú
put_nowaitrm   Ú_loggerÚdebugr}   Ú
isinstancer=   rn   rk   rl   rB   Ú_reconnect_shared_stream)r   r�   ÚsharedÚeventrq   Údrop_errÚerrÚreconnecteds           r   r   zStreamController._fanoutå   sˆ  è ø€ õ 	Kà—,“,Ø×(Ñ(ˆFØˆ~ØðHØ#'×#3Ñ#3°F·M±MÔ#B÷ 8˜%Ø—|’|ÙÜ# D×$7Ñ$7×$>Ñ$>Ó$@ÖA˜Ù/°°s·z±zÕBØŸI™I×0Ñ0°Õ7ñ  Bð ×"Ñ" fÑ,Ø"ŸK™K×'�à�OÜ& s¬G×,BÑ,BÔCØ ŸLšLä#×,Ñ,¬YÕ7Ø"×1Ñ1×7Ñ7Ó9×9Ð9÷ 8à(,×(EÑ(EÓ(G×"G�KÙ"Ù Øð5 —,”,ð< ×&Ñ&×-Ñ-Ö/ˆCØ�I‰I× Ñ  Õ&ñ 0ð38ùÐ#Bùô ò HÜ—‘Ð<¸h×GÒGûðHúð (ùð :ø÷ 8Ð7úà"Gús¢   ‚#G)¦F) ÁF'ÁF$ÁF'Á	AF) ÂF) Â0G)ÃGÃAG)ÄGÄ1GÄ2GÄ6G)ÅG'ÅG)Å);G)Æ$F'Æ'F) Æ)	GÆ2GÇG)ÇGÇG)ÇGÇG$Ç G)c              ƒ  óÖ   K  — | j                   }| j                  }t        ||d|z  z  «      }t        j                  d|dz  «      }t        j                  ||z   «      ƒ d{  –—†  y7 Œ­w)zJSleep with exponential backoff and jitter for reconnect attempt *attempt*.é   r   g      Ð?N)r^   r_   ÚminÚrandomÚuniformr=   rA   )r   ÚattemptÚbaseÚcapr?   Újitters         r   Ú_reconnect_sleepz!StreamController._reconnect_sleep  s[   è ø€ à×+Ñ+ˆØ×)Ñ)ˆÜ�C˜  G¡Ñ,Ó-ˆÜ—‘  5¨4¡<Ó0ˆÜ�m‰m˜E F™NÓ+×+Ò+ús   ‚AA)Á!A'Á"A)c              ƒ  ó„  K  — | j                   }|€yt        | j                  «      D ]W  }| j                  r y	 | j                  j                  | j                  |«      «      }|j                  ƒ d{  –—†  || _         y y7 Œ# t        j                  $ r ‚ t        $ r | j                  |«      ƒ d{  –—†7   Y Œ•w xY w­w)zØAttempt to reopen the shared stream after a transport drop.

        Returns True if a new stream was successfully opened, False if all
        reconnect attempts were exhausted or the controller was closed.
        NFT)rW   Úranger]   r[   rQ   Úopen_event_streamÚ_filter_with_sinceÚreadyr=   rn   rm   r™   rV   )r   Úbase_filterr•   Ú
new_streams       r   rŠ   z)StreamController._reconnect_shared_stream  sÀ   è ø€ ð ×0Ñ0ˆØÐØÜ˜T×9Ñ9Ö:ˆGØ�|Š|Ùð	Ø!Ÿ_™_×>Ñ>Ø×+Ñ+¨KÓ8ó�
ð !×&Ñ&×&Ð&ð #-ˆDÔÙð ;ð ð 'ùÜ×)Ñ)ò ØÜò Ø×+Ñ+¨GÓ4×4Ñ4ÙðüsF   ‚6C ¹9BÁ2BÁ3BÁ7C ÂBÂ0B=Â4B7Â5B=Â:C Â<B=Â=C c              ƒ  ó  K  — ddl m} | j                  �)| j                  � || j                  t	        |«      «      ry| j                  |¬«      }| j                  j                  | j                  |«      «      }| j                  }|| _        || _        |j                  ƒ d{  –—†  |�_t        j                  t        |«      «      }| j                  j                  |«       |j                  | j                  j                   «       yy7 Œf­w)aT  Ensure the shared SSE covers `candidate_filter`. Rotate if not.

        Open-new-before-close-old: any events buffered server-side between
        the two opens are replayed on the new SSE, and `_seen_event_ids`
        dedupes the overlap. Awaits `new_stream.ready` so the HTTP connection
        is established before returning.
        r   )Úfilter_coversN)Úextra)r‚   r¢   rV   rW   ÚdictÚ_compute_current_unionrQ   rœ   r�   rž   r=   r~   rD   rZ   r"   Úadd_done_callbackÚdiscard)r   Úcandidate_filterr¢   Ú
new_filterr    Ú
old_streamÚtasks          r   rx   z"StreamController._reconcile_stream?  sô   è ø€ õ 	Dð ×ÑÐ+Ø×*Ñ*Ð6Ù˜d×8Ñ8¼$Ð?OÓ:PÔQàà×0Ñ0Ð7GÐ0ÓHˆ
Ø—_‘_×6Ñ6Ø×#Ñ# JÓ/ó
ˆ
ð ×(Ñ(ˆ
Ø(ˆÔØ%/ˆÔ"Ø×Ñ×ÐØÐ!Ü×&Ñ&¤|°JÓ'?Ó@ˆDØ×&Ñ&×*Ñ*¨4Ô0Ø×"Ñ" 4×#=Ñ#=×#EÑ#EÕFð "ð 	ús   ‚B!DÂ#D
Â$A'Dc              ƒ  ó@   K  — | j                  |«      ƒ d{  –—† S 7 Œ­w)z%Public alias for `_reconcile_stream`.N)rx   )r   r¨   s     r   Úreconcile_streamz!StreamController.reconcile_stream]  s   è ø€ à×+Ñ+Ð,<Ó=×=Ð=Ð=ús   ‚—˜c                óÔ   — ddl m} | j                  j                  «       D �cg c]  }t	        |j
                  «      ‘Œ }}|�|j                  t	        |«      «        ||«      S c c}w )Nr   )Úcompute_union_filter)r‚   r¯   rU   r…   r¤   r9   Úappend)r   r£   r¯   rq   Úfilterss        r   r¥   z'StreamController._compute_current_uniona  sg   € õ 	Kð )-×(;Ñ(;×(BÑ(BÔ(Dó)
Ù(D ŒD�—‘ÕÐ(Dð 	ð )
ð ÐØ�N‰Nœ4 ›;Ô'Ù# GÓ,Ð,ùò)
s   £A%c                ó&   — | j                  |«       y)zCAdvance the reconnect cursor from a command response meta sequence.N)Ú_observe_seq©r   Úseqs     r   Úobserve_applied_through_seqz,StreamController.observe_applied_through_seqq  s   € à×Ñ˜#Õr   c                óD   — | j                  |j                  d«      «       y )Nrµ   )r³   rz   )r   rŒ   s     r   Ú_observe_eventzStreamController._observe_eventu  s   € Ø×Ñ˜%Ÿ)™) EÓ*Õ+r   c                ól   — t        |t        «      r$| j                  �|| j                  kD  r|| _        y y y r   )r‰   r*   r\   r´   s     r   r³   zStreamController._observe_seqx  s0   € Ü�cœ3Ô T§\¡\Ð%9¸SÀ4Ç<Á<Ò=OØˆD�Lð >PÐr   c                óR   — t        |«      }| j                  �| j                  |d<   |S )NÚsince)r¤   r\   )r   r9   Úouts      r   r�   z#StreamController._filter_with_since|  s'   € Ü�6‹lˆØ�<‰<Ð#ØŸ<™<ˆC�‰LØˆ
r   c               óÐ   K  — |2 3 d {  –—† }|j                  d«      }|�*|| j                  v rŒ+| j                  j                  |«       | j                  |«       |­–— Œ]7 ŒX6 y ­w)Nr!   )rz   rS   r"   r¸   )r   ÚsourcerŒ   r!   s       r   rƒ   zStreamController._dedup_iter†  sd   è ø€ Ù!÷ 	�%Ø—y‘y Ó,ˆHØÐ#Ø˜t×3Ñ3Ñ3ØØ×$Ñ$×(Ñ(¨Ô2Ø×Ñ Ô&ØŒKð	ø™6ùs&   ‚A&…A$‰A"ŠA$�AA&Á"A$Á$A&)r`   r   rH   z$Callable[[], Awaitable[None]] | NonerI   r*   rJ   r*   rK   r*   rL   ÚfloatrM   r¿   r+   r,   )rd   z	list[str]ra   zlist[list[str]] | Nonerb   z
int | Noner+   úAsyncIterator[Event])r+   r,   )r9   r   r+   r7   )ru   r*   r+   r,   )r9   r   r+   zAsyncGenerator[Event, None])r•   r*   r+   r,   )r+   r/   )r¨   r   r+   r,   r   )r£   zSubscribeParams | Noner+   údict[str, Any])rµ   r   r+   r,   )rŒ   r   r+   r,   )r9   rÁ   r+   rÁ   )r¾   rÀ   r+   rÀ   )r0   r1   r2   r3   r   rg   rB   rr   rv   Úregister_subscriptionÚunregister_subscriptionrf   ry   Úensure_fanout_runningr   r™   rŠ   rx   r­   r¥   r¶   r¸   r³   r�   rƒ   r5   r   r   rF   rF   `   s6  „ ñð* @DØ"Ø"(Ø&'Ø(+Ø'*ñ<ð *ð<ð =ð	<ð
 ð<ð  ð<ð !$ð<ð !&ð<ð  %ð<ð 
ó<ðD .2Ø ñ/àð/ð +ð	/ð
 ð/ð 
ó/ó(Vó$	ó7ð
 3ÐØ6Ðð2Ø%ð2à	$ó2ó*Dð
 3Ðó-'ó^,óóFGó<>ð
 /3ð
-Ø+ð
-à	ó
-ó ó,óóôr   rF   )rC   r   r?   r¿   r+   r,   ) r3   Ú
__future__r   r=   rk   Úloggingr“   Úcollectionsr   Úcollections.abcr   r   r   r   Údataclassesr	   r
   Útypingr   Úlangchain_protocolr   r   Úlanggraph_sdk.stream.transportr   r   r   Ú	getLoggerr0   r‡   r7   rD   rF   r5   r   r   Ú<module>rÎ      s‚   ðñ
õ #ã Û Û Û Ý #ß NÓ Nß (Ý ç 5ç T÷ ñ  ð8 ˆ'×
Ñ
˜HÓ
%€ð ÷@ð @ó ð@ð EHõ ÷ nò nr   