
    5iI_                     4   d Z ddlZddlmZmZ ddlmZ ddlZddlm	Z	 ddl
mZmZmZ ddl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 g dZ G d de      Z G d d      Z G d de      Zd Zd Zd Z  G d de      Z! G d de      Z" G d de      Z#y)zI
event-stream RPC (remote procedure call) protocol library for `awscrt`.
    N)ABCabstractmethod)NativeResource)Header)ClientBootstrapSocketOptionsTlsConnectionOptions)Callable)Future)IntEnum)partial)OptionalSequenceUnion)MessageTypeMessageFlagClientConnectionHandlerClientConnectionClientContinuationClientContinuationHandlerc                   F    e Zd ZdZdZ	 dZ	 dZ	 dZ	 dZ	 dZ		 dZ
	 d	Z	 d
 Zy)r   a  Types of messages in the event-stream RPC protocol.

    The :attr:`~MessageType.APPLICATION_MESSAGE` and :attr:`~MessageType.APPLICATION_ERROR` types may only be sent
    on streams, and will never arrive as a protocol message (stream-id 0).

    For all other message types, they may only be sent as protocol messages
    (stream-id 0), and will never arrive as a stream message.

    Different message types expect specific headers and flags, consult documentation.r                        c                     t        |       S Nstrselfformat_specs     x/home/marpiech/ifpan-abm-pgxpred/analysis/marpiech-gwas-test/venv/lib/python3.12/site-packages/awscrt/eventstream/rpc.py
__format__zMessageType.__format__C       4y    N)__name__
__module____qualname____doc__APPLICATION_MESSAGEAPPLICATION_ERRORPINGPING_RESPONSECONNECTCONNECT_ACKPROTOCOL_ERRORINTERNAL_ERRORr'    r)   r&   r   r      sV    Y DMGKm NNr)   r   c                   (    e Zd ZdZdZ	 dZ	 dZ	 d Zy)r   zFlags for messages in the event-stream RPC protocol.

    Flags may be XORed together.
    Not all flags can be used with all message types, consult documentation.
    r   r   r   c                     t        |       S r    r!   r#   s     r&   r'   zMessageFlag.__format__a   r(   r)   N)r*   r+   r,   r-   NONECONNECTION_ACCEPTEDTERMINATE_STREAMr'   r6   r)   r&   r   r   H   s0     Dh Zr)   r   c                   n    e Zd ZdZedd       Zedee   ddfd       Zede	e
   ded	ed
eddf
d       Zy)r   a  Base class for handling connection events.

    Inherit from this class and override methods to handle connection events.
    All callbacks for this connection will be invoked on the same thread,
    and :meth:`on_connection_setup()` will always be the first callback invoked.
    returnNc                      y)a^  Invoked upon completion of the setup attempt.

        If setup was successful, the connection is provided to the user.

        Note that the network connection stays alive until it is closed,
        even if no local references to the connection object remain.
        The user should store a reference to this connection, and call
        `connection.close()` when they are done with it to avoid leaking
        resources.

        Setup will always be the first callback invoked on the handler.
        If setup failed, no further callbacks will be invoked on this handler.

        Args:
            connection: The connection, if setup was successful,
                or None if setup failed.

            error: None, if setup was successful, or an Exception
                if setup failed.

            `**kwargs`: Forward compatibility kwargs.
        Nr6   )r$   
connectionerrorkwargss       r&   on_connection_setupz+ClientConnectionHandler.on_connection_setupn       0 	r)   reasonc                      y)aK  Invoked when the connection finishes shutting down.

        This event will not be invoked if connection setup failed.

        Args:
            reason: Reason will be None if the user initiated the shutdown,
                otherwise the reason will be an Exception.

            **kwargs: Forward compatibility kwargs.
        Nr6   )r$   rD   rA   s      r&   on_connection_shutdownz.ClientConnectionHandler.on_connection_shutdown   s     	r)   headerspayloadmessage_typeflagsc                      y)a  Invoked when a message for the connection (stream-id 0) is received.

        Args:
            headers: Message headers.

            payload: Binary message payload.

            message_type: Message type.

            flags: Message flags. Values from :class:`MessageFlag` may be
                XORed together. Not all flags can be used with all message
                types, consult documentation.

            **kwargs: Forward compatibility kwargs.
        Nr6   r$   rG   rH   rI   rJ   rA   s         r&   on_protocol_messagez+ClientConnectionHandler.on_protocol_message   rC   r)   r=   N)r*   r+   r,   r-   r   rB   r   	ExceptionrF   r   r   bytesr   intrM   r6   r)   r&   r   r   f   s      2 Xi-@ t   f%  &	
   r)   r   c                     | g } n| D cg c]  }|j                          } }|d}|t        j                  }| |||fS c c}w )z~
    Transform args that a python send-msg function would take,
    into args that a native send-msg function would take.
    r)   )_as_binding_tupler   r9   rG   rH   rI   rJ   is        r&   _to_binding_msg_argsrV      sX     29:Q1&&(::}  WlE22 ;s   ?c                 z    | D cg c]  }t        j                  |       } }|d}t        |      }| |||fS c c}w )zr
    Transform msg-received args that came from native,
    into msg-received args presented to python users.
    r)   )r   _from_binding_tupler   rT   s        r&   _from_binding_msg_argsrY      sJ    
 7>>v))!,>G>|,LWlE22	 ?s   8c                     |rt         j                  j                  |      nd }	 |r	 ||       |r| j                  |       y | j	                  d        y # |r| j                  |       w | j	                  d        w xY w)N)r@   )awscrt
exceptions	from_codeset_exception
set_result)bound_futurebound_callback
error_codees       r&   _on_message_flushrd      sp    3=##J/4A*# &&q)##D) &&q)##D)s   A 'A=c                        e Zd ZdZg dZ fdZedddddedede	d	e
d
ee   dee   ddfd       Zd Zd Zd Zd Zd Zddddddeee      deeeef      dedee	   deddfdZddZ xZS )r   a  A client connection for the event-stream RPC protocol.

    Use :meth:`ClientConnection.connect()` to establish a new
    connection.

    Note that the network connection stays alive until it is closed,
    even if no local references to the connection object remain.
    The user should store a reference to any connections, and call
    :meth:`close()` when they are done with them to avoid leaking resources.

    Attributes:
        host_name (str): Remote host name.

        port (int): Remote port.

        shutdown_future (concurrent.futures.Future[None]): Completes when this
            connection has finished shutting down. Future will contain a
            result of None, or an exception indicating why shutdown occurred.
    )	host_nameportshutdown_future_connect_future_handlerc                     t         |           || _        || _        t	               | _        | j
                  j                          t	               | _        | j                  j                          || _        y r    )	super__init__rf   rg   r   rh   set_running_or_notify_cancelri   rj   )r$   rf   rg   handler	__class__s       r&   rm   zClientConnection.__init__   s[    "	%x99;%x99;r)   N)	bootstrapsocket_optionstls_connection_optionsro   rf   rg   rq   rr   rs   r=   concurrent.futures.Futurec                    |s
t               } | |||      }|st        j                         }t        j                  ||||||       |j
                  S )a,  Asynchronously establish a new ClientConnection.

        Args:
            handler: Handler for connection events.

            host_name: Connect to host.

            port: Connect to port.

            bootstrap: Client bootstrap to use when initiating socket connection.
                If None is provided, the default singleton is used.

            socket_options: Optional socket options.
                If None is provided, then default options are used.

            tls_connection_options: Optional TLS
                connection options. If None is provided, then the connection will
                be attempted over plain-text.

        Returns:
            concurrent.futures.Future: A Future which completes when the connection succeeds or fails.
            If successful, the Future will contain None.
            Otherwise it will contain an exception.
            If the connection is successful, it will be made available via
            the handler's on_connection_setup callback.
            Note that this network connection stays alive until it is closed,
            even if no local references to the connection object remain.
            The user should store a reference to any connections, and call
            :meth:`close()` when they are done with them to avoid leaking resources.
        )r   r   get_or_create_static_default_awscrt*event_stream_rpc_client_connection_connectri   )clsro   rf   rg   rq   rr   rs   r?   s           r&   connectzClientConnection.connect   s`    R *_N D'2
'DDFI 	::"	 )))r)   c                 ~   |r"d }t         j                  j                  |      }n| }d }	 | j                  j	                  ||       |r| j
                  j                  |       y | j
                  j                  d        y # |r| j
                  j                  |       w | j
                  j                  d        w xY w)N)r?   r@   )r[   r\   r]   rj   rB   ri   r^   r_   )r$   rb   r?   r@   s       r&   _on_connection_setupz%ClientConnection._on_connection_setup;  s    J%%//
;EJE	6MM--5-Q $$2259$$//5 $$2259$$//5s   B ;B<c                 r   |rt         j                  j                  |      nd }	 | j                  j	                  |       |r| j
                  j                  |       y | j
                  j                  d        y # |r| j
                  j                  |       w | j
                  j                  d        w xY w)N)rD   )r[   r\   r]   rj   rF   rh   r^   r_   )r$   rb   rD   s      r&   _on_connection_shutdownz(ClientConnection._on_connection_shutdownL  s    <F"",,Z8D	6MM000? $$226:$$//5 $$226:$$//5s   A; ;;B6c                 h    t        ||||      \  }}}}| j                  j                  ||||       y N)rG   rH   rI   rJ   )rY   rj   rM   r$   rG   rH   rI   rJ   s        r&   _on_protocol_messagez%ClientConnection._on_protocol_messageW  sA    0FwPWYegl0m-,))%	 	* 	r)   c                 X    t        j                  | j                         | j                  S )a)  Close the connection.

        Shutdown is asynchronous. This call has no effect if the connection is
        already closed or closing.

        Note that, if the network connection hasn't already ended,
        `close()` MUST be called to avoid leaking resources. The network
        connection will not terminate simply because there are no references
        to the connection object.

        Returns:
            concurrent.futures.Future: This connection's :attr:`shutdown_future`,
            which completes when shutdown has finished.
        )rw   (event_stream_rpc_client_connection_close_bindingrh   r$   s    r&   closezClientConnection.close`  s"      	88G###r)   c                 @    t        j                  | j                        S )z
        Returns:
            bool: True if this connection is open and usable, False otherwise.
            Check :attr:`shutdown_future` to know when the connection is completely
            finished shutting down.
        )rw   *event_stream_rpc_client_connection_is_openr   r   s    r&   is_openzClientConnection.is_opens  s     AA$--PPr)   rG   rH   rJ   on_flushrG   rH   rI   rJ   r   c                    t               }|j                          t        ||||      \  }}}}t        j                  | j
                  ||||t        t        ||             |S )aX  Send a protocol message.

        Protocol messages use stream-id 0.

        Use the returned future, or the `on_flush` callback, to be informed
        when the message is successfully written to the wire, or fails to send.

        Keyword Args:
            headers: Message headers.

            payload: Binary message payload.

            message_type: Message type.

            flags: Message flags. Values from :class:`MessageFlag` may be
                XORed together. Not all flags can be used with all message
                types, consult documentation.

            on_flush: Callback invoked when the message is successfully written
                to the wire, or fails to send. The function should take the
                following arguments and return nothing:

                    *   `error` (Optional[Exception]): None if the message was
                        successfully written to the wire, or an Exception
                        if it failed to send.

                    *   `**kwargs` (dict): Forward compatibility kwargs.

                This callback is always invoked on the connection's event-loop
                thread.

        Returns:
            A future which completes with a result of None if the
            message is successfully written to the wire,
            or an exception if the message fails to send.
        )r   rn   rV   rw   8event_stream_rpc_client_connection_send_protocol_messager   r   rd   r$   rG   rH   rI   rJ   r   futures          r&   send_protocol_messagez&ClientConnection.send_protocol_message|  sk    X ++- 1EWgWcej0k-,HHMM%vx8	: r)   c                 R    t        ||       }t        j                  |       |_        |S )aj  
        Create a new stream.

        The stream will send no data until :meth:`ClientContinuation.activate()`
        is called. Call activate() when you're ready for callbacks and events to fire.

        Args:
            handler: Handler to process continuation messages and state changes.

        Returns:
            The new continuation object.
        )r   rw   -event_stream_rpc_client_connection_new_streamr   )r$   ro   continuations      r&   
new_streamzClientConnection.new_stream  s*     *'48 ' U UVZ [r)   )ro   r   r=   r   )r*   r+   r,   r-   	__slots__rm   classmethodr   r"   rQ   r   r   r   r	   rz   r|   r~   r   r   r   r   r   r   rP   	bytearrayr   r
   r   r   __classcell__rp   s   @r&   r   r      s   ( XI	   *.6:EI:* -:* 	:*
 :* ':* %]3:* %--A$B:* Oj:* :*x6"	6$&Q 379=#'!%9 hv./9 eE9$456	9
 &9 C=9 9 +F9vr)   r   c                        e Zd ZdZ fdZddddddedee   dee	e
f   ded	ed
efdZddddddee   dee	e
f   ded	ed
eddfdZd Zd Zd Z xZS )r   a  
    A continuation of messages on a given stream-id.

    Create with :meth:`ClientConnection.new_stream()`.

    The stream will send no data until :meth:`ClientContinuation.activate()`
    is called. Call activate() when you're ready for callbacks and events to fire.

    Attributes:
        connection (ClientConnection): This stream's connection.

        closed_future (concurrent.futures.Future) : Future which completes with a result of None
            when the continuation has closed.
    c                     t         |           || _        || _        t	               | _        | j
                  j                          y r    )rl   rm   rj   r?   r   closed_futurern   )r$   ro   r?   rp   s      r&   rm   zClientContinuation.__init__  s8    $#X779r)   Nr   	operationrG   rH   rI   rJ   r   c                    t               }|j                          t        ||||      \  }}}}t        j                  | j
                  | |||||t        t        ||             |S )a  
        Activate the stream by sending its first message.

        Use the returned future, or the `on_flush` callback, to be informed
        when the message is successfully written to the wire, or fails to send.

        activate() may only be called once, use send_message() to write further
        messages on this stream-id.

        Keyword Args:
            operation: Operation name for this stream.

            headers: Message headers.

            payload: Binary message payload.

            message_type: Message type.

            flags: Message flags. Values from :class:`MessageFlag` may be
                XORed together. Not all flags can be used with all message
                types, consult documentation.

            on_flush: Callback invoked when the message is successfully written
                to the wire, or fails to send. The function should take the
                following arguments and return nothing:

                    *   `error` (Optional[Exception]): None if the message was
                        successfully written to the wire, or an Exception
                        if it failed to send.

                    *   `**kwargs` (dict): Forward compatibility kwargs.

                This callback is always invoked on the connection's event-loop
                thread.

        Returns:
            A future which completes with a result of None if the
            message is successfully written to the wire,
            or an exception if the message fails to send.
        )r   rn   rV   rw   -event_stream_rpc_client_continuation_activater   r   rd   )r$   r   rG   rH   rI   rJ   r   flush_futures           r&   activatezClientContinuation.activate  su    d x113 1EWgWcej0k-,==MM %|X>	@ r)   r=   rt   c                    t               }|j                          t        ||||      \  }}}}t        j                  | j
                  ||||t        t        ||             |S )a  
        Send a continuation message.

        Use the returned future, or the `on_flush` callback, to be informed
        when the message is successfully written to the wire, or fails to send.

        Note that the the first message on a stream-id must be sent with activate(),
        send_message() is for all messages that follow.

        Keyword Args:
            operation: Operation name for this stream.

            headers: Message headers.

            payload: Binary message payload.

            message_type: Message type.

            flags: Message flags. Values from :class:`MessageFlag` may be
                XORed together. Not all flags can be used with all message
                types, consult documentation.

            on_flush: Callback invoked when the message is successfully written
                to the wire, or fails to send. The function should take the
                following arguments and return nothing:

                    *   `error` (Optional[Exception]): None if the message was
                        successfully written to the wire, or an Exception
                        if it failed to send.

                    *   `**kwargs` (dict): Forward compatibility kwargs.

                This callback is always invoked on the connection's event-loop
                thread.

        Returns:
            A future which completes with a result of None if the
            message is successfully written to the wire,
            or an exception if the message fails to send.
        )r   rn   rV   rw   1event_stream_rpc_client_continuation_send_messager   r   rd   r   s          r&   send_messagezClientContinuation.send_message(  sh    ` ++-0DWgWcej0k-,AAMM%vx8	: r)   c                 @    t        j                  | j                        S r    )rw   .event_stream_rpc_client_continuation_is_closedr   r   s    r&   	is_closedzClientContinuation.is_closedf  s    EEdmmTTr)   c                     	 | j                   j                          | j                  j                  d        y # | j                  j                  d        w xY wr    )rj   on_continuation_closedr   r_   r   s    r&   _on_continuation_closedz*ClientContinuation._on_continuation_closedi  sB    	0MM002 ))$/D))$/s	   8 Ac                 h    t        ||||      \  }}}}| j                  j                  ||||       y r   )rY   rj   on_continuation_messager   s        r&   _on_continuation_messagez+ClientContinuation._on_continuation_messagep  sA    0FwPWYegl0m-,--%	 	. 	r)   )r*   r+   r,   r-   rm   r"   r   r   r   rP   r   r   rQ   r
   r   r   r   r   r   r   r   s   @r&   r   r     s    : )-/3!%E E f%	E
 5)+,E &E E ET )-/3!%< f%< 5)+,	<
 &< < < +F<|U0r)   r   c                   N    e Zd ZdZedee   dedede	ddf
d       Z
ed
d	       Zy)r   a  Base class for handling stream continuation events.

    Inherit from this class and override methods to handle events.
    All callbacks will be invoked on the same thread (the same thread used by
    the connection).

    A common pattern is to store the continuation within its handler.
    Example::

        continuation_handler.continuation = connection.new_stream(continuation_handler)
    rG   rH   rI   rJ   r=   Nc                      y)a  Invoked when a message is received on this continuation.

        Args:
            headers: Message headers.

            payload: Binary message payload.

            message_type: Message type.

            flags: Message flags. Values from :class:`MessageFlag` may be
                XORed together. Not all flags can be used with all message
                types, consult documentation.

            **kwargs: Forward compatibility kwargs.
        Nr6   rL   s         r&   r   z1ClientContinuationHandler.on_continuation_message  s    . 	r)   c                      y)aY  Invoked when the continuation is closed.

        Once the continuation is closed, no more messages may be sent or received.
        The continuation is closed when a message is sent or received with
        the TERMINATE_STREAM flag, or when the connection shuts down.

        Args:
            **kwargs: Forward compatibility kwargs.
        Nr6   )r$   rA   s     r&   r   z0ClientContinuationHandler.on_continuation_closed  s     	r)   rN   )r*   r+   r,   r-   r   r   r   rP   r   rQ   r   r   r6   r)   r&   r   r   z  sd    
 f%  &	
   0 
 
r)   r   )$r-   rw   abcr   r   r[   r   awscrt.exceptionsawscrt.eventstreamr   	awscrt.ior   r   r	   collections.abcr
   concurrent.futuresr   enumr   	functoolsr   typingr   r   r   __all__r   r   r   rV   rY   rd   r   r   r   r6   r)   r&   <module>r      s     # !  % J J $ %   , ,'' 'T <Hc HV3"	3*j~ jZn nb1 1r)   