
    VhpT                       d Z ddlmZ ddl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 dd	lmZmZmZmZmZ dd
lmZmZmZm Z m!Z!m"Z"m#Z# ddl$m%Z% ddl&m'Z'  ed      Z(d dZ) G d de      Z* ee       G d d             Z+ ee        G d d             Z,d!dZ- e-e,        e-e+       e G d d             Z.d"dZ/dddef	 	 	 	 	 	 	 	 	 d#dZ0 e0       Z1 e/       Z2 G d de      Z3y)$z
Implementation of L{twisted.application.internet.ClientService}, particularly
its U{automat <https://automat.readthedocs.org/>} state machine.
    )annotations)	dataclassfield)random)CallableOptionalProtocolTypeVarUnion)implementer)TypeMachineBuilderpep614)Service)CancelledErrorDeferredfailmaybeDeferredsucceed)IAddressIDelayedCall	IProtocolIProtocolFactoryIReactorTimeIStreamClientEndpoint
ITransport)Logger)FailureTc                    | ddl m} |S | S )zR
    @return: the argument, or the global reactor if the argument is L{None}.
    r   )reactor)twisted.internetr    )maybeReactorr    s     S/home/dcms/DCMS/lib/python3.12/site-packages/twisted/application/_client_service.py_maybeGlobalReactorr$   )   s     ,    c                  R    e Zd Zd	dZd
dZddZddZdddZdddZ	 d	 	 	 ddZ	y)_Clientc                     y)T
        Start this L{ClientService}, initiating the connection retry loop.
        N selfs    r#   startz_Client.start6       r%   c                     y)z
        Stop trying to connect and disconnect any current connection.

        @return: a L{Deferred} that fires when all outstanding connections are
            closed and all in-progress connection attempts halted.
        Nr*   r+   s    r#   stopz_Client.stop;   r.   r%   c                     y)zg
        A connection has been made.

        @param protocol: The protocol of the connection.
        Nr*   )r,   protocols     r#   _connectionMadez_Client._connectionMadeC   r.   r%   c                     y)z
        Deliver connection failures to any L{ClientService.whenConnected}
        L{Deferred}s that have met their failAfterFailures threshold.

        @param failure: the Failure to fire the L{Deferred}s with.
        Nr*   r,   failures     r#   _connectionFailedz_Client._connectionFailedJ   r.   r%   Nc                     y)z?
        The wait between connection attempts is done.
        Nr*   r5   s     r#   
_reconnectz_Client._reconnectR   r.   r%   c                     y)z?
        The current connection has been disconnected.
        Nr*   r5   s     r#   _clientDisconnectedz_Client._clientDisconnectedW   r.   r%   c                    y)a-  
        Retrieve the currently-connected L{Protocol}, or the next one to
        connect.

        @param failAfterFailures: number of connection failures after which the
            Deferred will deliver a Failure (None means the Deferred will only
            fail if/when the service is stopped).  Set this to 1 to make the
            very first connection failure signal an error.  Use 2 to allow one
            failure but signal an error if the subsequent retry then fails.

        @return: a Deferred that fires with a protocol produced by the factory
            passed to C{__init__}.  It may:

                - fire with L{IProtocol}

                - fail with L{CancelledError} when the service is stopped

                - fail with e.g.
                  L{DNSLookupError<twisted.internet.error.DNSLookupError>} or
                  L{ConnectionRefusedError<twisted.internet.error.ConnectionRefusedError>}
                  when the number of consecutive failed connection attempts
                  equals the value of "failAfterFailures"
        Nr*   r,   failAfterFailuress     r#   whenConnectedz_Client.whenConnected\   r.   r%   returnNonerA   Deferred[None])r2   _ReconnectingProtocolProxyrA   rB   )r6   r   rA   rB   N)r6   Optional[Failure]rA   rB   r>   Optional[int]rA   Deferred[IProtocol])
__name__
__module____qualname__r-   r0   r3   r7   r9   r;   r?   r*   r%   r#   r'   r'   5   s:    

 59$1	r%   r'   c                  D    e Zd ZdZ	 	 	 	 	 	 ddZd	dZd
dZddZddZy)rE   z
    A proxy for a Protocol to provide connectionLost notification to a client
    connection service, in support of reconnecting when connections are lost.
    c                     || _         || _        y)a  
        Create a L{_ReconnectingProtocolProxy}.

        @param protocol: the application-provided L{interfaces.IProtocol}
            provider.
        @type protocol: provider of L{interfaces.IProtocol} which may
            additionally provide L{interfaces.IHalfCloseableProtocol} and
            L{interfaces.IFileDescriptorReceiver}.

        @param lostNotification: a 1-argument callable to invoke with the
            C{reason} when the connection is lost.
        N)	_protocol_lostNotification)r,   r2   lostNotifications      r#   __init__z#_ReconnectingProtocolProxy.__init__   s     "!1r%   c                H    || _         | j                  j                  |       y rF   )
_transportrP   makeConnection)r,   	transports     r#   rV   z)_ReconnectingProtocolProxy.makeConnection   s    #%%i0r%   c                    	 | j                   j                  |      | j                  |       S # | j                  |       w xY w)z
        The connection was lost.  Relay this information.

        @param reason: The reason the connection was lost.

        @return: the underlying protocol's result
        )rP   connectionLostrQ   )r,   reasons     r#   rY   z)_ReconnectingProtocolProxy.connectionLost   s6    	+>>008""6*D""6*s	   . Ac                .    t        | j                  |      S rF   )getattrrP   r,   items     r#   __getattr__z&_ReconnectingProtocolProxy.__getattr__   s    t~~t,,r%   c                P    d| j                   j                   d| j                  dS )N<z
 wrapping >)	__class__rK   rP   r+   s    r#   __repr__z#_ReconnectingProtocolProxy.__repr__   s'    4>>**+:dnn5GqIIr%   N)r2   r   rR   Callable[[Failure], None]rA   rB   )rW   r   rA   rB   )rZ   r   rA   rB   r^   strrA   objectrA   rg   )	rK   rL   rM   __doc__rS   rV   rY   r_   rd   r*   r%   r#   rE   rE   x   s9    
2!25N2	2$1+-Jr%   rE   c                  <    e Zd ZdZ	 	 	 	 	 	 ddZddZd	dZd
dZy)_DisconnectFactoryz
    A L{_DisconnectFactory} is a proxy for L{IProtocolFactory} that catches
    C{connectionLost} notifications and relays them.
    c                     || _         || _        y rF   )_protocolFactory_protocolDisconnected)r,   protocolFactoryprotocolDisconnecteds      r#   rS   z_DisconnectFactory.__init__   s    
 !0%9"r%   c                j    | j                   j                  |      }|yt        || j                        S )a2  
        Create a L{_ReconnectingProtocolProxy} with the disconnect-notification
        callback we were called with.

        @param addr: The address the connection is coming from.

        @return: a L{_ReconnectingProtocolProxy} for a protocol produced by
            C{self._protocolFactory}
        N)rn   buildProtocolrE   ro   )r,   addrbuilts      r#   rs   z _DisconnectFactory.buildProtocol   s5     %%33D9=)%1K1KLLr%   c                .    t        | j                  |      S rF   )r\   rn   r]   s     r#   r_   z_DisconnectFactory.__getattr__   s    t,,d33r%   c                b    dj                  | j                  j                  | j                        S )Nz<{} wrapping {!r}>)formatrc   rK   rn   r+   s    r#   rd   z_DisconnectFactory.__repr__   s*    #**NN##T%:%:
 	
r%   N)rp   r   rq   re   rA   rB   )rt   r   rA   zOptional[IProtocol]rf   ri   )rK   rL   rM   rj   rS   rs   r_   rd   r*   r%   r#   rl   rl      s8    
:): 8: 
	:M4
r%   rl   c                *    dD ]  }t        | |        y)z
    Remove the special runtime attributes set by L{implementer} so that a class
    can proxy through those attributes with C{__getattr__} and thereby forward
    optionally-provided interfaces by the delegated class.
    )__providedBy____provides____implemented__N)delattr)ozopeSpecials     r#   _deinterfacer      s     M  ; r%   c                      e Zd ZU dZded<   ded<   ded<   ded	<   d
ed<    ee      Zded<    ee      Zded<   dZ	ded<    e
       Zded<   ddZddZddZddZy)_Corez6
    Shared core for ClientService state machine.
    r   endpointr   factoryCallable[[int], float]timeoutForAttemptr   clock'Optional[Callable[[IProtocol], object]]prepareConnection)default_factoryzlist[Deferred[None]]stopWaitersz/list[tuple[Deferred[IProtocol], Optional[int]]]awaitingConnectedr   intfailedAttemptsr   logc                f    | j                   j                  t                      | j                   d   S )N)r   appendr   r+   s    r#   waitForStopz_Core.waitForStop   s)    
+##r%   c                b    g | j                   c| _         }|D ]  \  }}|j                  |        y rF   )r   callback)r,   valuewaitingw	remainings        r#   unawaitz_Core.unawait   s6    *,d.D.D'# 	LAyJJu	r%   c                H    | j                  t        t                            y rF   )r   r   r   r+   s    r#   cancelConnectWaitersz_Core.cancelConnectWaiters   s    W^-./r%   c                \    g | j                   c| _         }|D ]  }|j                  d         y rF   )r   r   )r,   r   r   s      r#   finishStoppingz_Core.finishStopping   s2    $&(8(8!' 	AJJt	r%   NrC   )r   zUnion[IProtocol, Failure]rA   rB   r@   )rK   rL   rM   rj   __annotations__r   listr   r   r   r   r   r   r   r   r   r*   r%   r#   r   r      s|    
 $#-->> ).d(CK%CINJF  NC(C$
0r%   r   c            	        t        t        t              } 	 d	 	 	 	 	 	 	 dd}	 	 	 	 	 	 	 	 dd}	 d	 	 	 	 	 	 	 dd}| j                  d      }| j                  d|      }| j                  d      }| j                  d|      }| j                  d|      }| j                  d	      }	| j                  d
      }
| j                  d      }|j	                  t        j
                        j                  |      j                  d        |j	                  t        j
                        j                         j                  d        |j	                  t        j                        j                  |      j                  d        |j	                  t        j
                        j                         j                  d        |j	                  t        j                        j                  |      j                  d        |j	                  t        j                        j                  |      j                  d        |j	                  t        j
                        j                         j                  d        |j	                  t        j                        j                  |      j                  d        |	j	                  t        j
                        j                  |
      j                  d        |
j	                  t        j
                        j                  |
      j                  d        |j	                  t        j
                        j                  |      j                  d        t        |j	                  t        j                        j                  |            t        |j	                  t        j                        j                  |            dd              }t        |j	                  t        j                        j                  |	            	 	 	 	 	 	 	 	 dd       }t        |j	                  t        j                  d      j                  |            dd       }t        |j	                  t        j                        j                  |            dd       }t        |j	                  t        j                        j                  |	            	 	 	 	 	 	 	 	 d d       }t        |j	                  t        j                        j                               	 d	 	 	 	 	 	 	 	 	 d!d       }t        |	j	                  t        j                        j                               t        |
j	                  t        j                        j                  |	            dd              }t        |	j	                  t        j                        j                  |            t        |	j	                  t        j                        j                  |            	 d	 	 	 	 	 	 	 d"d              }t        |j	                  t        j                  d      j                               t        |j	                  t        j                  d      j                               t        |j	                  t        j                        j                  |            t        |
j	                  t        j                        j                  |
            t        |	j	                  t        j                        j                  |	            	 d	 	 	 	 	 	 	 d#d                                   }t        |
j	                  t        j                        j                  |            dd"d       }t        |j	                  t        j                        j                  |            	 d	 	 	 	 	 	 	 d#d       }| j!                         S )$Nc                   |xj                   dz  c_         |j                  |j                         }|j                  j                  d|j                   |j                  |       |j
                  j                  || j                        S )N   zDScheduling retry {attempt} to connect {endpoint} in {delay} seconds.)attemptr   delay)r   r   r   infor   r   	callLaterr9   )csr6   r   s       r#   waitForRetryz!makeMachine.<locals>.waitForRetry  ss     	
A##A$4$45	

R$$ZZ	 	 	
 ww  55r%   c                J    d|_         |j                  |j                         |S )Nr   )r   r   rP   )r   r   r2   s      r#   rememberConnectionz'makeMachine.<locals>.rememberConnection  s#     			($$%r%   c                   t        j                  | j                        }j                  j	                  |      }	 	 	 	 dfd}|}|j                  |      j                  | j                        j                  | j                         |S )Nc                     j                   (t        j                          j                   fd      S t               S )Nc                    S rF   r*   )_r2   s    r#   <lambda>zImakeMachine.<locals>.attemptConnection.<locals>.prepare.<locals>.<lambda>'  s    h r%   )r   r   addCallbackr   )r2   r   s   `r#   preparez7makeMachine.<locals>.attemptConnection.<locals>.prepare"  sA     "".$Q%8%8(COO&  8$$r%   )r2   rE   rA   $Deferred[_ReconnectingProtocolProxy])	rl   r   r;   r   connectr   r3   
addErrbackr7   )r   r   r6   factoryProxy
connectingr   connectingProxys    `     r#   attemptConnectionz&makeMachine.<locals>.attemptConnection  s     *!))Q5J5JK*+***<*<\*J
	%0	%1	% %''0[**+Z++,r%   Init
ConnectingStoppedWaiting	ConnectedDisconnecting
Restartingc                    t        d       S rF   )r   r   r   s     r#   immediateStopz"makeMachine.<locals>.immediateStopO  s     t}r%   c                F    |j                         }|j                          |S rF   )r   cancel)r   r   r   waiteds       r#   connectingStopz#makeMachine.<locals>.connectingStopT  s     r%   T)nodatac                    g }g }|j                   D ]H  \  }}||j                  ||f       |dk  r|j                  |       3|j                  ||dz
  f       J ||_         |D ]  }|j                  |        y )Nr   )r   r   r   )r   r   r6   readynotReadyr   r   s          r#   failedWhenConnectingz)makeMachine.<locals>.failedWhenConnecting\  s    DF// 	4LAy I/aQIM 23	4 ' 	 AJJw	 r%   c                    |j                         }|j                          |j                          |j                          |S rF   )r   r   r   r   )r   r   futureRetryr   s       r#   r0   zmakeMachine.<locals>.stopk  s6    	 	r%   c                Z    |j                         }|j                  j                          |S rF   )r   rU   loseConnection)r   r   r2   r   s       r#   stopWhileConnectedz'makeMachine.<locals>.stopWhileConnecteds  s&     **,r%   c                ,    t        |j                        S rF   )r   rP   )r   r   r2   r>   s       r#   whenConnectedWhenConnectedz/makeMachine.<locals>.whenConnectedWhenConnected{  s     x))**r%   c                "    |j                         S rF   )r   r   s     r#   	discoStopzmakeMachine.<locals>.discoStop  s     }}r%   c                D    |j                          |j                          y rF   )r   r   r   r   r6   s      r#   disconnectingFinishedz*makeMachine.<locals>.disconnectingFinished  s    
 	
 	r%   c                T    t               }|j                  j                  ||f       |S rF   )r   r   r   )r   r   r>   results       r#   awaitingConnectionz'makeMachine.<locals>.awaitingConnection  s*     '/j	""F,=#>?r%   c                $    |j                          y rF   )r   r   s      r#   restartDonez makeMachine.<locals>.restartDone  s    	r%   c                (    t        t                     S rF   )r   r   )r   r   r>   s      r#   notGoingToConnectz&makeMachine.<locals>.notGoingToConnect  s     N$%%r%   rF   )r   r'   r   r   r6   rG   rA   r   )r   r'   r   r   r2   rE   rA   rE   )r   r'   r   r   r6   rG   rA   r   )r   r'   r   r   rA   rD   )r   r'   r   r   r   r   rA   rD   )r   r'   r   r   r6   r   rA   rB   )r   r'   r   r   r   r   rA   rD   )r   r'   r   r   r2   rE   rA   rD   )
r   r'   r   r   r2   rE   r>   rI   rA   rJ   )r   r'   r   r   r6   rG   rA   rB   )r   r'   r   r   r>   rI   rA   rJ   )r   r'   r   stateuponr-   toreturnsloopr3   r9   r7   r;   r   r0   r?   build)machiner   r   r   r   r   r   r   r   r   r   r   r   r   r0   r   r   r   r   r   r   r   s                         r#   makeMachiner     s    %0G <@666'86	6(B	# <@'8	-8 == D|->?JmmI&GmmI|4Gk+=>IMM/2M|,JmmI&G 	IIgmm
+33D9OOGMM"'')11$7OOG++,//	:BB4HLL$$&..t4LL##$''
3;;DANN7,,-009AA$GNN7==!&&(006NN7../227;CCDIw}}%((4<<TBOOGMM"%%j199$?LL"":.66t< DIIgll#&&w/0GLL&))'23 4 1 JOOGLL),,];<'K	 = JOOG55dOCFFwOP  Q  GLL&))'23 4 INN7<<(++M:;(B	 < INN70016689
 ,0	+++ -+ )	+
 
+ :+ Mw||,1134JOOGLL),,];< = 5 Mw889<<WEFMw::;>>wGH;?'8	 I G JOOG11$O?DDFGGLL..tL<AACDDIIg++,//56JOOG11255jABMw44588GHAE1>	 I C 7 E H
 JOOG778;;JGH I GLL../227;<AE&&&1>&	& =&
 ==?r%   g      ?g      N@g      ?c                      d fd}|S )a  
    A timeout policy for L{ClientService} which computes an exponential backoff
    interval with configurable parameters.

    @since: 16.1.0

    @param initialDelay: Delay for the first reconnection attempt (default
        1.0s).
    @type initialDelay: L{float}

    @param maxDelay: Maximum number of seconds between connection attempts
        (default 60 seconds, or one minute).  Note that this value is before
        jitter is applied, so the actual maximum possible delay is this value
        plus the maximum possible result of C{jitter()}.
    @type maxDelay: L{float}

    @param factor: A multiplicative factor by which the delay grows on each
        failed reattempt.  Default: 1.5.
    @type factor: L{float}

    @param jitter: A 0-argument callable that introduces noise into the delay.
        By default, C{random.random}, i.e. a pseudorandom floating-point value
        between zero and one.
    @type jitter: 0-argument callable returning L{float}

    @return: a 1-argument callable that, given an attempt count, returns a
        floating point number; the number of seconds to delay.
    @rtype: see L{ClientService.__init__}'s C{retryPolicy} argument.
    c                t    	 t        t        d|       z  z        }|        z   S # t        $ r }Y w xY w)Nd   )minOverflowError)r   r   factorinitialDelayjittermaxDelays     r#   policyzbackoffPolicy.<locals>.policy  sJ    	#c72C(CDhOE vx  	E	s   ) 77)r   r   rA   floatr*   )r   r   r   r   r   s   ```` r#   backoffPolicyr     s    H    Mr%   c                  r     e Zd ZdZ e       Z	 	 	 d	 	 	 	 	 	 	 	 	 ddZ	 d	 	 	 d	dZd
 fdZd fdZ	 xZ
S )ClientServicez
    A L{ClientService} maintains a single outgoing connection to a client
    endpoint, reconnecting after a configurable timeout when a connection
    fails, either before or after connecting.

    @since: 16.1.0
    c           
         t        |      }|t        n|}t        t        |||||| j                              | _        y)a  
        @param endpoint: A L{stream client endpoint
            <interfaces.IStreamClientEndpoint>} provider which will be used to
            connect when the service starts.

        @param factory: A L{protocol factory <interfaces.IProtocolFactory>}
            which will be used to create clients for the endpoint.

        @param retryPolicy: A policy configuring how long L{ClientService} will
            wait between attempts to connect to C{endpoint}; a callable taking
            (the number of failed connection attempts made in a row (L{int}))
            and returning the number of seconds to wait before making another
            attempt.

        @param clock: The clock used to schedule reconnection.  It's mainly
            useful to be parametrized in tests.  If the factory is serialized,
            this attribute will not be serialized, and the default value (the
            reactor) will be restored when deserialized.

        @param prepareConnection: A single argument L{callable} that may return
            a L{Deferred}.  It will be called once with the L{protocol
            <interfaces.IProtocol>} each time a new connection is made.  It may
            call methods on the protocol to prepare it for use (e.g.
            authenticate) or validate it (check its health).

            The C{prepareConnection} callable may raise an exception or return
            a L{Deferred} which fails to reject the connection.  A rejected
            connection is not used to fire an L{Deferred} returned by
            L{whenConnected}.  Instead, L{ClientService} handles the failure
            and continues as if the connection attempt were a failure
            (incrementing the counter passed to C{retryPolicy}).

            L{Deferred}s returned by L{whenConnected} will not fire until any
            L{Deferred} returned by the C{prepareConnection} callable fire.
            Otherwise its successful return value is consumed, but ignored.

            Present Since Twisted 18.7.0
        N)r   r   )r$   _defaultPolicyClientMachiner   _log_machine)r,   r   r   retryPolicyr   r   s         r#   rS   zClientService.__init__  sE    \ $E*(3(;n!."3II	"
r%   c                8    | j                   j                  |      S )ai  
        Retrieve the currently-connected L{Protocol}, or the next one to
        connect.

        @param failAfterFailures: number of connection failures after which
            the Deferred will deliver a Failure (None means the Deferred will
            only fail if/when the service is stopped).  Set this to 1 to make
            the very first connection failure signal an error.  Use 2 to
            allow one failure but signal an error if the subsequent retry
            then fails.
        @type failAfterFailures: L{int} or None

        @return: a Deferred that fires with a protocol produced by the
            factory passed to C{__init__}
        @rtype: L{Deferred} that may:

            - fire with L{IProtocol}

            - fail with L{CancelledError} when the service is stopped

            - fail with e.g.
              L{DNSLookupError<twisted.internet.error.DNSLookupError>} or
              L{ConnectionRefusedError<twisted.internet.error.ConnectionRefusedError>}
              when the number of consecutive failed connection attempts
              equals the value of "failAfterFailures"
        )r   r?   r=   s     r#   r?   zClientService.whenConnected#  s    : }}**+<==r%   c                    | j                   r| j                  j                  d       yt        |           | j
                  j                          y)r)   z1Duplicate ClientService.startService {log_source}N)runningr   warnsuperstartServicer   r-   r,   rc   s    r#   r  zClientService.startServiceB  s;     <<IINNNOr%   c                T    t         |           | j                  j                         S )z
        Stop attempting to reconnect and close any existing connections.

        @return: a L{Deferred} that fires when all outstanding connections are
            closed and all in-progress connection attempts halted.
        )r  stopServicer   r0   r  s    r#   r  zClientService.stopServiceL  s#     	}}!!##r%   )NNN)
r   r   r   r   r   z Optional[Callable[[int], float]]r   zOptional[IReactorTime]r   r   rF   rH   r@   rC   )rK   rL   rM   rj   r   r   rS   r?   r  r  __classcell__)rc   s   @r#   r   r     s|     8D 9=(,EI:
':
 ":
 6	:

 &:
 C:
z 26>!.>	>>$ $r%   r   N)r"   zOptional[T]rA   r   )r~   rh   rA   rB   )rA   zCallable[[_Core], _Client])
r   r   r   r   r   r   r   zCallable[[], float]rA   r   )4rj   
__future__r   dataclassesr   r   r   _goodEnoughRandomtypingr   r   r	   TypingProtocolr
   r   zope.interfacer   automatr   r   twisted.application.servicer   twisted.internet.deferr   r   r   r   r   twisted.internet.interfacesr   r   r   r   r   r   r   twisted.loggerr   twisted.python.failurer   r   r$   r'   rE   rl   r   r   r   r   r   r   r   r*   r%   r#   <module>r     s>  
 # ( . Q Q & . /    " *CL	@n @F Y-J -J -J` #
 #
 #
L     ' ( # # #LbL "3	+++ +  	+
 +\ x$G x$r%   