
    5io                         d Z ddlZddlmZ ddlZddlmZmZ ddlm	Z	m
Z
mZ ddlmZ ddlmZ ddlZddlmZmZmZmZmZ  G d	 d
e      ZdZ	 e G d d             Ze G d d             Ze G d d             Ze G d d             Ze G d d             Ze G d d             Ze G d d             Z G d de      Z  G d de      Z!ddddddddddddd e"d!ee#   d"ed#ee	   d$ee   d%ee
   d&ee   d'e$d(ee#   d)eegdf   d*eeegdf      d+eeegdf      d,eeegdf      d-eeegdf      fd.Z%d/d0d e"d1e"d2efd3Z&y)4a  
WebSocket - `RFC 6455 <https://www.rfc-editor.org/rfc/rfc6455>`_

Use the :func:`connect()` to establish a :class:`WebSocket` client connection.

Note from the developer: This is a very low-level API, which forces the
user to deal with things like data fragmentation.
A higher-level API could easily be built on top of this.

.. _authoring-callbacks:

Authoring Callbacks
-------------------
All network operations in `awscrt.websocket` are asynchronous.
Callbacks are always invoked on the WebSocket's networking thread.
You MUST NOT perform blocking network operations from any callback, or you will cause a deadlock.
For example: do not send a frame, and then wait for that frame to complete,
within a callback. The WebSocket cannot do work until your callback returns,
so the thread will be stuck. You can send the frame from within the callback,
just don't wait for it to complete within the callback.

If you want to do blocking waits, do it from a thread you control, like the main thread.
It's fine for the main thread to send a frame, and wait until it completes.

All functions and methods in `awscrt.websocket` are thread-safe.
They can be called from any mix of threads.

.. _flow-control-reading:

Flow Control (reading)
----------------------
By default, the WebSocket will read from the network as fast as it can hand you the data.
You must prevent the WebSocket from reading data faster than you can process it,
or memory usage could balloon until your application explodes.

There are two ways to manage this.

First, and simplest, is to process incoming data synchronously within the
`on_incoming_frame` callbacks. Since callbacks are invoked on the WebSocket's
networking thread, the WebSocket cannot read more data until the callback returns.
Therefore, processing the data in a synchronous manner
(i.e. writing to disk, printing to screen, etc) will naturally
affect `TCP flow control <https://en.wikipedia.org/wiki/Transmission_Control_Protocol#Flow_control>`_,
and prevent data from arriving too fast. However, you MUST NOT perform a blocking
network operation from within the callback or you risk deadlock (see :ref:`authoring-callbacks`).

The second, more complex, way requires you to manage the size of the read window.
Do this if you are processing the data asynchronously
(i.e. sending the data along on another network connection).
Create the WebSocket with `manage_read_window` set true,
and set `initial_read_window` to the number of bytes you are ready to receive right away.
Whenever the read window reaches 0, you will stop receiving anything.
The read window shrinks as you receive the payload from "data" frames (TEXT, BINARY, CONTINUATION).
Call :meth:`WebSocket.increment_read_window()` to increase the window again keep frames flowing in.
You only need to worry about the payload from "data" frames.
The WebSocket automatically increments its window to account for any
other incoming bytes, including other parts of a frame (opcode, payload-length, etc)
and the payload of other frame types (PING, PONG, CLOSE).
You'll probably want to do it like this:
Pick the max amount of memory to buffer, and set this as the `initial_read_window`.
When data arrives, the window has shrunk by that amount.
Send this data along on the other network connection.
When that data is done sending, call `increment_read_window()`
by the amount you just finished sending.
If you don't want to receive any data at first, set the `initial_read_window` to 0,
and `increment_read_window()` when you're ready.
Maintaining a larger window is better for overall throughput.

.. _flow-control-writing:

Flow Control (writing)
----------------------
You must also ensure that you do not continually send frames faster than the other
side can read them, or memory usage could balloon until your application explodes.

The simplest approach is to only send 1 frame at a time.
Use the :meth:`WebSocket.send_frame()` `on_complete` callback to know when the send is complete.
Then you can try and send another.

A more complex, but higher throughput, way is to let multiple frames be in flight
but have a cap. If the number of frames in flight, or bytes in flight, reaches
your cap then wait until some frames complete before trying to send more.

.. _api:

API
---
    N)NativeResource)HttpProxyOptionsHttpRequest)ClientBootstrapTlsConnectionOptionsSocketOptions)	dataclass)IntEnum)CallableOptionalSequenceTupleUnionc                   :    e Zd ZdZdZ	 dZ	 dZ	 dZ	 dZ	 dZ		 d Z
y	)
Opcodea>  An opcode defines a frame's type.

    RFC 6455 classifies TEXT and BINARY as `data frames <https://www.rfc-editor.org/rfc/rfc6455#section-5.6>`_.
    A CONTINUATION frame "continues" the most recent data frame.
    All other opcodes are for `control frames <https://www.rfc-editor.org/rfc/rfc6455#section-5.5>`_.
    )r            	   
   c                 x    | j                   t        j                  t        j                  t        j                  fv S )aR  True if this is a "data frame" opcode.

        TEXT, BINARY, and CONTINUATION are "data frames". The rest are "control" frames.

        If the WebSocket was created with `manage_read_window`,
        then the read window shrinks as "data frames" are received.
        See :ref:`flow-control-reading` for a thorough explanation.
        )valuer   TEXTBINARYCONTINUATIONselfs    r/home/marpiech/ifpan-abm-pgxpred/analysis/marpiech-gwas-test/venv/lib/python3.12/site-packages/awscrt/websocket.pyis_data_framezOpcode.is_data_frame   s(     zzfkk6==&:M:MNNN    N)__name__
__module____qualname____doc__r   r   r   CLOSEPINGPONGr    r    r   r   r   g   sQ     L
 D' F,E D D	Or    r   l    c                       e Zd ZU dZdZee   ed<   	 dZed   ed<   	 dZ	ee
   ed<   	 dZeeeeef         ed<   	 dZeed<   y)	OnConnectionSetupDataz1Data passed to the `on_connection_setup` callbackN	exception	WebSocket	websockethandshake_response_statushandshake_response_headershandshake_response_body)r!   r"   r#   r$   r+   r   	Exception__annotations__r-   r.   intr/   r   r   strr0   bytesr(   r    r   r*   r*      s}    ;%)Ix	")1 (,Ix$+ 04x}3 GK%S/)B CJ &*U)r    r*   c                   &    e Zd ZU dZdZee   ed<   y)OnConnectionShutdownDataz4Data passed to the `on_connection_shutdown` callbackNr+   r!   r"   r#   r$   r+   r   r1   r2   r(   r    r   r7   r7      s    >%)Ix	")3r    r7   c                   <    e Zd ZU dZeed<   	 eed<   	 eed<   	 d Zy)IncomingFramezRDescribes the frame you are receiving.

    Used in `on_incoming_frame` callbacks opcodepayload_lengthfinc                 6    | j                   j                         S )aK  True if this is a "data frame".

        TEXT, BINARY, and CONTINUATION are "data frames". The rest are "control frames".

        If the WebSocket was created with `manage_read_window`,
        then the read window shrinks as "data frames" are received.
        See :ref:`flow-control-reading` for a thorough explanation.
        )r;   r   r   s    r   r   zIncomingFrame.is_data_frame   s     {{((**r    N)	r!   r"   r#   r$   r   r2   r3   boolr   r(   r    r   r:   r:      s*    . N1	Ih	+r    r:   c                       e Zd ZU dZeed<   y)OnIncomingFrameBeginDatazData passed to the `on_incoming_frame_begin` callback.

    Each `on_incoming_frame_begin` call will be followed by
    0+ `on_incoming_frame_payload` calls,
    followed by one `on_incoming_frame_complete` call.frameN)r!   r"   r#   r$   r:   r2   r(   r    r   rA   rA      s    : :r    rA   c                   (    e Zd ZU dZeed<   	 eed<   y)OnIncomingFramePayloadDataa8  Data passed to the `on_incoming_frame_payload` callback.

    This callback will be invoked 0+ times.
    Each time, `data` will contain a bit more of the payload.
    Once all `frame.payload_length` bytes have been received
    (or the network connection is lost), the `on_incoming_frame_complete`
    callback will be invoked.

    If the WebSocket was created with `manage_read_window`,
    and this is a "data frame" (TEXT, BINARY, CONTINUATION),
    then the read window shrinks by `len(data)`.
    See :ref:`flow-control-reading` for a thorough explanation.
    rB   dataN)r!   r"   r#   r$   r:   r2   r5   r(   r    r   rD   rD   
  s     >
K1r    rD   c                   2    e Zd ZU dZeed<   	 dZee   ed<   y)OnIncomingFrameCompleteDataz9Data passed to the `on_incoming_frame_complete` callback.rB   Nr+   )	r!   r"   r#   r$   r:   r2   r+   r   r1   r(   r    r   rG   rG   !  s#    C5%)Ix	")Gr    rG   c                   &    e Zd ZU dZdZee   ed<   y)OnSendFrameCompleteDatazIData passed to the :meth:`WebSocket.send_frame()` `on_complete` callback.Nr+   r8   r(   r    r   rI   rI   -  s    S%)Ix	")Lr    rI   c                   ~     e Zd ZdZ fdZd Z	 dddddedeee	e
eef      d	ed
eeegdf      fdZdefdZ xZS )r,   z]A WebSocket connection.

    Use :meth:`connect()` to establish a new client connection.
    c                 0    t         |           || _        y N)super__init___binding)r   binding	__class__s     r   rN   zWebSocket.__init__?  s    r    c                 B    t        j                  | j                         y)a  Close the WebSocket asynchronously.

        You should call this when you are done with a healthy WebSocket,
        to ensure that it shuts down and cleans up.
        You don't need to call this on a WebSocket that has already shut
        down, or is in the middle of shutting down, but it is safe to do so.
        This function is idempotent.

        To determine when shutdown has completed, you can use the
        `on_shutdown_complete` callback (passed into :meth:`connect()`).
        N)_awscrtwebsocket_closerO   r   s    r   closezWebSocket.closeD  s     	.r    NT)r=   on_completer;   payloadr=   rV   c                l      fd}t        j                   j                  t        |      |||       y)aC  Send a WebSocket frame asynchronously.

        See `RFC 6455 section 5 - Data Framing <https://www.rfc-editor.org/rfc/rfc6455#section-5>`_
        for details on all frame types.

        This is a low-level API, which requires you to send the appropriate payload for each type of opcode.
        If you are not an expert, stick to sending :attr:`Opcode.TEXT` or :attr:`Opcode.BINARY` frames,
        and don't touch the FIN bit.

        See :ref:`flow-control-writing` to learn about limiting the amount of
        unsent data buffered in memory.

        Args:
            opcode: :class:`Opcode` for this frame.

            payload: Any `bytes-like object <https://docs.python.org/3/glossary.html#term-bytes-like-object>`_.
                `str` will always be encoded as UTF-8. It is fine to pass a `str` for a BINARY frame.
                None will result in an empty payload, the same as passing empty `bytes()`

            fin: The FIN bit indicates that this is the final fragment in a message.
                Do not set this False unless you understand
                `WebSocket fragmentation <https://www.rfc-editor.org/rfc/rfc6455#section-5.4>`_

            on_complete: Optional callback, invoked when the frame has finished sending.
                Takes a single :class:`OnSendFrameCompleteData` argument.

                If :attr:`OnSendFrameCompleteData.exception` is set, the connection
                was lost before this frame could be completely sent.

                But if `exception` is None, the frame was successfully written to the OS socket.
                (This doesn't mean the other endpoint has received the data yet,
                or even guarantee that the data has left the machine yet,
                but it's on track to get there).

                Be sure to read about :ref:`authoring-callbacks`.
        c                 :   t               }| r$t        j                  j                  |       |_        	 	 |       y y # t
        $ rR t        dt        j                         t        j                  t        j                           j                          Y y w xY w)Nz6Exception in WebSocket.send_frame on_complete callbackfile)rI   awscrt
exceptions	from_coder+   BaseExceptionprintsysstderr
excepthookexc_inforU   )
error_codecbdatarV   r   s     r   _on_completez*WebSocket.send_frame.<locals>._on_complete~  s{    ,.F#)#4#4#>#>z#J *' +  NUXU_U_`/

s   
? ABBN)rS   websocket_send_framerO   r   )r   r;   rW   r=   rV   rg   s   `   ` r   
send_framezWebSocket.send_frameR  s0    X	 	$$MM6N	r    sizec                 d    |dk  rt        d      t        j                  | j                  |       y)a`  Manually increment the read window by this many bytes, to continue receiving frames.

        See :ref:`flow-control-reading` for a thorough explanation.
        If the WebSocket was created without `manage_read_window`, this function does nothing.
        This function may be called from any thread.

        Args:
            size: in bytes
        r   z!Increment size cannot be negativeN)
ValueErrorrS   websocket_increment_read_windowrO   )r   rj   s     r   increment_read_windowzWebSocket.increment_read_window  s+     !8@AA//tDr    rL   )r!   r"   r#   r$   rN   rU   r   r   r   r4   r5   	bytearray
memoryviewr?   r   rI   ri   r3   rn   __classcell__rQ   s   @r   r,   r,   9  s    
 
/" GK?
 KO?? %UIz ABC?
 ? h(?'@$'FGH?BE# Er    r,   c                   <     e Zd Z fdZd Zd Zd Zd Zd Z xZ	S )_WebSocketCorec                 h    t         |           || _        || _        || _        || _        || _        y rL   )rM   rN   _on_connection_setup_cb_on_connection_shutdown_cb_on_incoming_frame_begin_cb_on_incoming_frame_payload_cb_on_incoming_frame_complete_cb)r   on_connection_setupon_connection_shutdownon_incoming_frame_beginon_incoming_frame_payloadon_incoming_frame_completerQ   s         r   rN   z_WebSocketCore.__init__  s8     	':$*@'+B(-F*.H+r    c                    t               }|r%t        j                  j                  |      |_        nt        |      |_        ||_        ||_        ||_	        	 | j                  |       y # t        $ rj t        dt        j                         t        j                  t        j                            |j                  |j                  j#                          Y y Y y w xY w)Nz3Exception in WebSocket on_connection_setup callbackrZ   )r*   r\   r]   r^   r+   r,   r-   r.   r/   r0   rv   r_   r`   ra   rb   rc   rd   rU   )r   re   websocket_bindingr.   r/   r0   rf   s          r   _on_connection_setupz#_WebSocketCore._on_connection_setup  s     '(%00:::FF():;F+D(,F))@&	)((0 	)GcjjYNNCLLN++  &&( ,	)s   A* *A.CCc                 >   t               }|r$t        j                  j                  |      |_        	 | j
                  | j                  |       y y # t        $ rB t        dt        j                         t        j                  t        j                           Y y w xY w)Nz6Exception in WebSocket on_connection_shutdown callbackrZ   )r7   r\   r]   r^   r+   rw   r_   r`   ra   rb   rc   rd   r   re   rf   s      r   _on_connection_shutdownz&_WebSocketCore._on_connection_shutdown  s}    )+%00:::FF	,..://7 ; 	,JQTQ[Q[\NNCLLN+	,s   A ABBc                 <   t        t        |      ||      | _        t        | j                        }	 | j                  | j	                  |       y# t
        $ rB t        dt        j                         t        j                  t        j                           Y yw xY w)Nz7Exception in WebSocket on_incoming_frame_begin callbackrZ   FT)r:   r   _current_incoming_framerA   rx   r_   r`   ra   rb   rc   rd   )r   
opcode_intr<   r=   rf   s        r   _on_incoming_frame_beginz'_WebSocketCore._on_incoming_frame_begin  s    '4VJ5GY\']$)$*F*FG	//;008   	KRUR\R\]NNCLLN+	s   A ABBc                    t        | j                  |      }	 | j                  | j                  |       y# t        $ rB t	        dt
        j                         t        j                  t        j                           Y yw xY w)Nz9Exception in WebSocket on_incoming_frame_payload callbackrZ   FT)	rD   r   ry   r_   r`   ra   rb   rc   rd   )r   rE   rf   s      r   _on_incoming_frame_payloadz)_WebSocketCore._on_incoming_frame_payload  sp    +D,H,H$O	11=226:   	MTWT^T^_NNCLLN+	s   6 AB Bc                 V   t        | j                        }|r$t        j                  j	                  |      |_        | `	 | j                  | j                  |       y# t        $ rB t        dt        j                         t        j                  t        j                           Y yw xY w)Nz:Exception in WebSocket on_incoming_frame_complete callbackrZ   FT)rG   r   r\   r]   r^   r+   rz   r_   r`   ra   rb   rc   rd   r   s      r   _on_incoming_frame_completez*_WebSocketCore._on_incoming_frame_complete  s    ,T-I-IJ%00:::FF(	22>33F;   	NUXU_U_`NNCLLN+	s   A AB('B()
r!   r"   r#   rN   r   r   r   r   r   rq   rr   s   @r   rt   rt     s"    I)6, r    rt   F)port	bootstrapsocket_optionstls_connection_optionsproxy_optionsmanage_read_windowinitial_read_windowr|   r}   r~   r   hostr   handshake_requestr   r   r   r   r   r   r{   r|   r}   r~   r   c                     |r|t        d      d}|dk  rt        d      |d}|t        j                         }|
t               }t	        |	|
|||      }t        j                  | |||||||||
       y)a  Asynchronously establish a client WebSocket connection.

    The `on_connection_setup` callback is invoked once the connection
    has succeeded or failed.

    If successful, a :class:`WebSocket` will be provided in the
    :class:`OnConnectionSetupData`. You should store this WebSocket somewhere,
    so that you can continue using it (the connection will shut down
    if the class is garbage collected).

    The WebSocket will shut down after one of these things occur:
        * You call :meth:`WebSocket.close()`
        * You, or the server, sends a CLOSE frame.
        * The underlying socket shuts down.
        * All references to the WebSocket are dropped,
          causing it to be garbage collected. However, you should NOT
          rely on this behavior. You should call :meth:`~WebSocket.close()` when you are
          done with a healthy WebSocket, to ensure that it shuts down and cleans up.
          It is very easy to accidentally keep a reference around without realizing it.

    Be sure to read about :ref:`authoring-callbacks`.

    Args:
        host: Hostname to connect to.

        port: Port to connect to. If not specified, it defaults to port 443
            when `tls_connection_options` is present, and port 80 otherwise.

        handshake_request: HTTP request for the initial WebSocket handshake.

            The request's method MUST be "GET", and the following headers are
            required::

                Host: <host>
                Upgrade: websocket
                Connection: Upgrade
                Sec-WebSocket-Key: <base64-encoding of 16 random bytes>
                Sec-WebSocket-Version: 13

            You can use :meth:`create_handshake_request()` to make a valid WebSocket
            handshake request, modifying the path and headers to fit your needs,
            and then passing it here.

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

        socket_options: Socket options.
            If not specified, default options are used.

        proxy_options: HTTP Proxy options.
            If not specified, no proxy is used.

        manage_read_window: Set true to manually manage the flow-control read window.
            If false (the default), data arrives as fast as possible.
            See :ref:`flow-control-reading` for a thorough explanation.

        initial_read_window: The initial size of the read window, in bytes.
            This must be set if `manage_read_window` is true,
            otherwise it is ignored.
            See :ref:`flow-control-reading` for a thorough explanation.
            An initial size of 0 will prevent any frames from arriving
            until :meth:`WebSocket.increment_read_window()` is called.

        on_connection_setup: Callback invoked when the connect completes.
            Takes a single :class:`OnConnectionSetupData` argument.

            If successful, :attr:`OnConnectionSetupData.websocket` will be set.
            You should store the :class:`WebSocket` somewhere, so you can
            use it to send data when you're ready.
            The other callbacks will be invoked as events occur,
            until the final `on_connection_shutdown` callback.

            If unsuccessful, :attr:`OnConnectionSetupData.exception` will be set,
            and no further callbacks will be invoked.

            If this callback raises an exception, the connection will shut down.

        on_connection_shutdown: Optional callback, invoked when a connection shuts down.
            Takes a single :class:`OnConnectionShutdownData` argument.

            This callback is never invoked if `on_connection_setup` reported an exception.

        on_incoming_frame_begin: Optional callback, invoked once at the start of each incoming frame.
            Takes a single :class:`OnIncomingFrameBeginData` argument.

            Each `on_incoming_frame_begin` call will be followed by 0+
            `on_incoming_frame_payload` calls, followed by one
            `on_incoming_frame_complete` call.

            The "frame complete" callback is guaranteed to be invoked
            once for each "frame begin" callback, even if the connection
            is lost before the whole frame has been received.

            If this callback raises an exception, the connection will shut down.

        on_incoming_frame_payload: Optional callback, invoked 0+ times as payload data arrives.
            Takes a single :class:`OnIncomingFramePayloadData` argument.

            If `manage_read_window` is on, and this is a "data frame",
            then the read window shrinks accordingly.
            See :ref:`flow-control-reading` for a thorough explanation.

            If this callback raises an exception, the connection will shut down.

        on_incoming_frame_complete: Optional callback, invoked when the WebSocket
            is done processing an incoming frame.
            Takes a single :class:`OnIncomingFrameCompleteData` argument.

            If :attr:`OnIncomingFrameCompleteData.exception` is set,
            then something went wrong processing the frame
            or the connection was lost before the frame could be completed.

            If this callback raises an exception, the connection will shut down.
    NzD'initial_read_window' must be set if 'manage_read_window' is enabledr   z('initial_read_window' cannot be negative)rl   r   get_or_create_static_defaultr   rt   rS   websocket_client_connect)r   r   r   r   r   r   r   r   r   r{   r|   r}   r~   r   cores                  r   connectr     s    F &cddQCDD|#@@B	&!"$D $$
r    /)pathr   returnc                 `    t        j                  | |      \  }}t        j                  ||      S )a  Create an HTTP request with all the required fields for a WebSocket handshake.

    The method will be "GET", and the following headers are added::

        Host: <host>
        Upgrade: websocket
        Connection: Upgrade
        Sec-WebSocket-Key: <base64-encoding of 16 random bytes>
        Sec-WebSocket-Version: 13

    You may can add headers, or modify the path, before using this request.

    Args:
        host: Value for "Host" header
        path: Path (and query) string. Defaults to "/".
    )rS   "websocket_create_handshake_requestr   _from_bindings)r   r   http_request_bindinghttp_headers_bindings       r   create_handshake_requestr     s4    " 291[1[\`bf1g..%%&:<PQQr    )'r$   rS   r\   r   awscrt.exceptionsawscrt.httpr   r   	awscrt.ior   r   r   dataclassesr	   enumr
   ra   typingr   r   r   r   r   r   MAX_PAYLOAD_LENGTHr*   r7   r:   rA   rD   rG   rI   r,   rt   r4   r3   r?   r   r   r(   r    r   <module>r      s}  Wv  !  5 J J !  
 = =:OW :Oz (  : * * *Z 3 3 3 + + +8 ; ; ; 2 2 2, G G G L L LgE gETj^ j` +/.2=A04$)-SWTXX\Z^f
f 3-f #	f
 (f ]+f %%9:f ,-f f "#f "#8"94"?@f %X/G.H$.N%OPf &h0H/I4/O&PQf  (2L1Mt1S(TUf !)3N2OQU2U)V WfR 8; Rc R R{ Rr    