
    (i6                         d dl Z d dlZd dlmZmZmZmZmZmZm	Z	m
Z
 d dlmZ d dlmZmZmZmZmZ d dlmZ d dlmZmZ d dlmZmZ erd dlmZ d d	lmZmZ  G d
 d      Z y)    N)TYPE_CHECKINGAnyListSequenceSetUnioncastoverload)HexStr) SubscriptionHandlerTaskExceptionSubscriptionProcessingFinishedTaskNotRunningWeb3TypeErrorWeb3ValueError)SubscriptionContainer) FormattedEthSubscriptionResponseRPCResponse)EthSubscriptionEthSubscriptionContext)	AsyncWeb3)PersistentConnectionProviderRequestProcessorc                   D   e Zd ZU dZ ej
                  d      Zej                  ed<   ddZ	de
e   ddfdZde
e   ddfd	Zde
e   ddfd
ZddZddZedee
e      fd       Zdede
e   fdZdede
e   fdZede
e   defd       Zedee
e      dee   fd       Zdee
e   ee
e      f   deeee   f   fdZede
e   defd       Zededefd       Zedeee
e   ef      defd       Zdee
e   eeee
e   ef      f   defdZdefdZd deddfdZy)!SubscriptionManagerz
    The ``SubscriptionManager`` is responsible for subscribing, unsubscribing, and
    managing all active subscriptions for an ``AsyncWeb3`` instance. It is also
    used for processing all subscriptions that have handler functions.
    z.web3.providers.persistent.subscription_managerloggerreturnNc                     || _         t        d|j                        | _        t	               | _        d| _        d| _        t               | _	        | j
                  | j                  j                  _        d| _        y )Nr   F   r   )_w3r	   provider	_providerr   _subscription_containerparallelizetask_timeoutset_tasks_request_processortotal_handler_calls)selfw3s     _/var/www/br/venv/lib/python3.12/site-packages/web3/providers/persistent/subscription_manager.py__init__zSubscriptionManager.__init__8   si    <bkkJ'<'>$ !14
 (( 	))A )*     subscriptionc                 :    | j                   j                  |       y N)r"   add_subscriptionr)   r.   s     r+   _add_subscriptionz%SubscriptionManager._add_subscriptionK   s    $$55lCr-   c                 :    | j                   j                  |       y r0   )r"   remove_subscriptionr2   s     r+   _remove_subscriptionz(SubscriptionManager._remove_subscriptionN   s    $$88Fr-   c                 V   |j                   |j                  k(  rVd}| j                  |j                        8|j                   d| |_        |dz  }| j                  |j                        7y y |j                  | j                  j
                  v rt        d|j                         y )N   #r   zUSubscription label already exists. Subscriptions must have unique labels.
    label: )label_default_labelget_by_label_labelr"   subscriptions_by_labelr   )r)   r.   is      r+   _validate_and_normalize_labelz1SubscriptionManager._validate_and_normalize_labelQ   s    !<!<<A##L$7$78D)5)D)D(EQqc&J#Q ##L$7$78D
 ##//FFG %++7+>+>*?A Gr-   c           	         |j                         r>|j                         s-	 |j                          | j                  j	                  |       yyy# t
        $ rh}| j                  j                  d       | j                  j                  j                  j                  t        |t        |                   Y d}~yd}~ww xY w)z
        Callback when a handler task completes. Similar to _message_listener_callback.
        Puts handler exceptions into the queue to be raised in the main loop, else
        removes the task from the set of active tasks.
        z.Subscription handler task raised an exception.)messageN)done	cancelledresultr&   discard	Exceptionr   	exceptionr!   r'   _handler_subscription_queue
put_nowaitr   str)r)   taskes      r+   _handler_task_callbackz*SubscriptionManager._handler_task_callbackc   s     99;t~~/##D)  0;  %%&VW11MMXX4T3q6J s   +A 	CAB<<Cc                   K   | j                   sy| j                  j                  dt        | j                                | j                   D ]#  }|j	                         r|j                          % | j                   j                          yw)z(Cancel and clean up all remaining tasks.Nz!Cleaning up %d remaining tasks...)r&   r   debuglenrC   cancelclear)r)   rL   s     r+   _cleanup_remaining_tasksz,SubscriptionManager._cleanup_remaining_taskss   se     {{=s4;;?OPKK 	D99;	 	s   AB-Bc                 .    | j                   j                  S r0   )r"   subscriptions)r)   s    r+   rV   z!SubscriptionManager.subscriptions   s    ++999r-   sub_idc                 8    | j                   j                  |      S r0   )r"   	get_by_id)r)   rW   s     r+   rY   zSubscriptionManager.get_by_id   s    ++55f==r-   r:   c                 8    | j                   j                  |      S r0   )r"   r<   )r)   r:   s     r+   r<   z SubscriptionManager.get_by_label   s    ++88??r-   rV   c                    K   y wr0    r)   rV   s     r+   	subscribezSubscriptionManager.subscribe   	        c                    K   y wr0   r\   r]   s     r+   r^   zSubscriptionManager.subscribe   s      	r`   c                   K   t        |t              r| |_        | j                  |        | j                  j
                  j                  |j                    d{   }||_        | j                  |       | j                  j                  d|j                  |       |S t        |t              rLt        |      dk(  rt        d      g }|D ]*  }|j!                  | j#                  |       d{          , |S t%        d      7 7 w)z
        Used to subscribe to a single or multiple subscriptions.

        :param subscriptions: A single subscription or a sequence of subscriptions.
        :type subscriptions: Union[EthSubscription, Sequence[EthSubscription]]
        :return:
        NzASuccessfully subscribed to subscription:
    label: %s
    id: %sr   No subscriptions provided.z7Expected a Subscription or a sequence of Subscriptions.)
isinstancer   managerr@   r   eth
_subscribesubscription_params_idr3   r   infor:   r   rQ   r   appendr^   r   )r)   rV   rW   sub_idssubs        r+   r^   zSubscriptionManager.subscribe   s      m_5$(M!..}=2488<<22M4U4UVVF &M""=1KKU##
 Mx0=!Q&$%ABB$&G$ :T^^C%889:NUVV# W  9s%   ADDBD0D

1D
Dc                    K   y wr0   r\   r]   s     r+   unsubscribezSubscriptionManager.unsubscribe   r_   r`   c                    K   y wr0   r\   r]   s     r+   ro   zSubscriptionManager.unsubscribe   r_   r`   c                    K   y wr0   r\   r]   s     r+   ro   zSubscriptionManager.unsubscribe   s     
 	r`   c                 2  K   t        |t              st        |t              rDt        |t              r#|}| j                  |      }|t	        d|       || j
                  vr%t	        d|j                   d|j                         | j                  j                  j                  |j                         d{   r1| j                  |       | j                  j                  d|j                  |j                         t        | j                   j"                        dk(  rA| j$                  j&                  j(                  }|j+                  t-                      d{    yt        |t.              r{t        |      dk(  rt	        d      g }t1        |      }|D ]E  }t        |t              rt3        |      }|j5                  | j7                  |       d{          G t9        |      S | j                  j;                  d	|       y
7 T7 7 7w)a  
        Used to unsubscribe from one or multiple subscriptions.

        :param subscriptions: The subscription(s) to unsubscribe from.
        :type subscriptions: Union[EthSubscription, Sequence[EthSubscription], HexStr,
            Sequence[HexStr]]
        :return: ``True`` if unsubscribing to all was successful, ``False`` otherwise
            with a warning.
        :rtype: bool
        NzTSubscription not found or is not being managed by the subscription manager.
    id: zWSubscription not found or is not being managed by the subscription manager.
    label: z	
    id: zESuccessfully unsubscribed from subscription:
    label: %s
    id: %sr   Trc   z;Failed to unsubscribe from subscription
    subscription=%sF)rd   r   rK   rY   r   rV   r:   ri   r   rf   _unsubscribeidr6   r   rj   rQ   r"   handler_subscriptionsr!   r'   rI   putr   r   listr   rk   ro   allwarning)r)   rV   subscription_idqueueunsubscribedsubsrm   s          r+   ro   zSubscriptionManager.unsubscribe   s    $ m_5MSV9W--"/ $ ? ((::I9JL 
 D$6$66$+112*]=N=N<OQ  XX\\..}/?/?@@@))-8  0!''!$$	 t33IIJaO99UU   ))$B$DEEEx0=!Q&$%ABB')L &D Ac3' +C##$*:*:3*?$?@A |$$J	
 E A F %@s8   B:H<H=B%H"H#A:HH
3HHHc                 `  K   | j                   j                         D cg c]  }| j                  |       d{    }}t        |      r| j                  j                  d       yt        | j                         dkD  r&| j                  j                  d| j                          y7 nc c}w w)z
        Used to unsubscribe from all subscriptions that are being managed by the
        subscription manager.

        :return: ``True`` if unsubscribing was successful, ``False`` otherwise.
        :rtype: bool
        Nz1Successfully unsubscribed from all subscriptions.Tr   zgFailed to unsubscribe from all subscriptions. Some subscriptions are still active.
    subscriptions=%sF)rV   copyro   rx   r   rj   rQ   ry   )r)   rm   r|   s      r+   unsubscribe_allz#SubscriptionManager.unsubscribe_all	  s      ))..0
  ""3'''
 

 |KKPQ4%%&*##>&&
  (
s&   B.B)B'
B)A(B.'B))B.run_foreverc                   K   | j                   j                  s|s| j                  j                  d       y| j                  j
                  j                  }|s| j                   j                  rk	 t        t        |j                          d{         }t        t        | j                  j                  j                  |       d{         }|j                  d      }| j                   j                  |      }|rt        | j                  ||d   fi |j                   }|j"                  du s|j"                  g| j"                  r[t%        j&                  |j)                  |            }| j*                  j-                  |       |j/                  | j0                         n|j)                  |       d{    |rS| j                   j                  rk| j                  j
                  jC                          | j*                  r| j;                          d{    yy7 7 _7 p# t2        $ r" |s| j                  j5                  d       Y zY t6        $ r6 | j                  j9                  d       | j;                          d{  7    t<        $ rK}	| j                  j9                  d|	j>                         | j                  jA                          Y d}	~	d}	~	ww xY w7 ˭w)	a{  
        Used to handle all subscriptions that have handlers. The method will run until
        all subscriptions that have handler functions are unsubscribed from or, if
        ``run_forever`` is set to ``True``, it will run indefinitely.

        :param run_forever: If ``True``, the method will run indefinitely.
        :type run_forever: bool
        :return: None
        zANo handler subscriptions found. Subscription handler did not run.Nr.   rE   TzVAll handler subscriptions have been unsubscribed from. Stopping subscription handling.zUAn exception occurred in a subscription handler task. Stopping subscription handling.z"Stopping subscription handling: %s)"r"   ru   r   ry   r!   r'   rI   r	   r   getr   r   re   _process_responseget_handler_subscription_by_idr   _handler_contextr#   asynciocreate_task_handlerr&   addadd_done_callbackrN   r   rj   r   errorrT   r   rB    _handle_listener_task_exceptions!_reset_handler_subscription_queue)
r)   r   r{   responseformatted_sub_responserW   rm   sub_contextrL   rM   s
             r+   handle_subscriptionsz(SubscriptionManager.handle_subscriptions"  sm     ++AA+KKS 11MMT99OO0599;->?)-4((**<<XFF*& 033NC22QQ "8.x8# ..	#K $./D4D4D  '223<<3LM-..t/J/JK "ll;777= T99OOh 	))KKM;;//111 i .? G2 81 "KK$$:  # 4 !!6 33555! !!"F		R??A 2s   A.K,1H- H%
:H- 	H(

C0H- :H+;H- ?K,K,AK,K*K,%H- (H- +H- -&K'K,6K'JK'A K"K,"K''K,)r*   zAsyncWeb3[Any]r   N)rL   zasyncio.Task[None]r   N)r   N)F) __name__
__module____qualname____doc__logging	getLoggerr   Logger__annotations__r,   r   r   r3   r6   r@   rN   rT   propertyr   rV   r   rY   rK   r<   r
   r^   r   r   boolro   r   r   r\   r-   r+   r   r   -   se    /W..8FGNN *&Doc.B Dt DG1E G$ G/#:N SW $ 
 :tOC$89 : :> >?3+? >@# @/#*> @ _S-A f   %oc&:;	f 
W"?3#7/RUBV9W#WXW	vtF|#	$W@ s/C    v $   oc&:F&B CD 
 EC U?3/789;
E 
ENt 2H2d H2t H2r-   r   )!r   r   typingr   r   r   r   r   r   r	   r
   
eth_typingr   web3.exceptionsr   r   r   r   r   0web3.providers.persistent.subscription_containerr   
web3.typesr   r   web3.utils.subscriptionsr   r   web3r   web3.providers.persistentr   r   r   r\   r-   r+   <module>r      sQ     	 	 	 
 }2 }2r-   