o
    :ÊÆhÂ]  ã                   @  sD  d dl mZ d dlZd dlZd dl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 ddlmZ ddlmZmZmZmZmZmZmZmZmZmZ ddlm Z m!Z! dd	l"m#Z# dd
lm$Z$m%Z%m&Z& g d¢Z'e
e e!ef Z(	 G dd„ dej)ƒZ*e*j+Z+e*j,Z,G dd„ dej)ƒZ-e-j.Z.e-j/Z/e-j0Z0e-j1Z1dZ2	 G dd„ dƒZ3dS )é    )ÚannotationsN)Ú	GeneratorÚListÚOptionalÚTypeÚUnioné   )ÚConnectionClosedÚConnectionClosedErrorÚConnectionClosedOKÚInvalidStateÚPayloadTooBigÚProtocolError)Ú	Extension)
ÚOK_CLOSE_CODESÚ	OP_BINARYÚOP_CLOSEÚOP_CONTÚOP_PINGÚOP_PONGÚOP_TEXTÚCloseÚ	CloseCodeÚFrame)ÚRequestÚResponse)ÚStreamReader)Ú
LoggerLikeÚOriginÚSubprotocol)ÚProtocolÚSideÚStateÚSEND_EOFc                   @  s   e Zd ZdZedƒ\ZZdS )r!   z6A WebSocket connection is either a server or a client.é   N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚrangeÚSERVERÚCLIENT© r,   r,   ú`/var/www/html/HyperOracle/crypto_trader/venv/lib/python3.10/site-packages/websockets/protocol.pyr!   -   s    r!   c                   @  s    e Zd ZdZedƒ\ZZZZdS )r"   z6A WebSocket connection is in one of these four states.é   N)	r%   r&   r'   r(   r)   Ú
CONNECTINGÚOPENÚCLOSINGÚCLOSEDr,   r,   r,   r-   r"   7   s    r"   ó    c                   @  s  e Zd ZdZedddœdMdd„ZedNdd„ƒZejdOdd„ƒZedPdd„ƒZ	edQdd„ƒZ
edRdd„ƒZdSdd„ZdTd d!„ZdUd$d%„ZdVdUd'd(„ZdVdUd)d*„ZdWdXd/d0„ZdSd1d2„ZdSd3d4„ZdYdZd6d7„Zd[d9d:„Zd\d<d=„Zd]d>d?„Zd^dAdB„Zd^dCdD„Zd_dGdH„Zd_dIdJ„ZdTdKdL„ZdS )`r    a6  
    Sans-I/O implementation of a WebSocket connection.

    Args:
        side: :attr:`~Side.CLIENT` or :attr:`~Side.SERVER`.
        state: initial state of the WebSocket connection.
        max_size: maximum size of incoming messages in bytes;
            :obj:`None` disables the limit.
        logger: logger for this connection; depending on ``side``,
            defaults to ``logging.getLogger("websockets.client")``
            or ``logging.getLogger("websockets.server")``;
            see the :doc:`logging guide <../../topics/logging>` for details.

    i   N)ÚstateÚmax_sizeÚloggerÚsider!   r4   r"   r5   úOptional[int]r6   úOptional[LoggerLike]ÚreturnÚNonec                C  sÂ   t  ¡ | _	 |d u rt d|j ¡ › �¡}|| _	 | tj	¡| _
|| _|| _|| _d | _d| _d | _g | _d | _d | _d | _d | _d | _	 d| _tƒ | _g | _g | _|  ¡ | _t| jƒ d | _d S )Nzwebsockets.F) ÚuuidÚuuid4ÚidÚloggingÚ	getLoggerÚnameÚlowerr6   ÚisEnabledForÚDEBUGÚdebugr7   r4   r5   Úcur_sizeÚexpect_continuation_frameÚoriginÚ
extensionsÚsubprotocolÚ
close_rcvdÚ
close_sentÚclose_rcvd_then_sentÚhandshake_excÚeof_sentr   ÚreaderÚeventsÚwritesÚparseÚparserÚnextÚ
parser_exc)Úselfr7   r4   r5   r6   r,   r,   r-   Ú__init__W   s6   
	


zProtocol.__init__c                 C  s   | j S )zm
        WebSocket connection state.

        Defined in 4.1, 4.2, 7.1.3, and 7.1.4 of :rfc:`6455`.

        )Ú_state©rW   r,   r,   r-   r4   ›   s   zProtocol.statec                 C  s    | j r| j  d|j¡ || _d S )Nz= connection is %s)rE   r6   rA   rY   )rW   r4   r,   r,   r-   r4   ¥   s   
c                 C  s&   | j turdS | jdu rtjS | jjS )zÍ
        `WebSocket close code`_.

        .. _WebSocket close code:
            https://www.rfc-editor.org/rfc/rfc6455.html#section-7.1.5

        :obj:`None` if the connection isn't closed yet.

        N)r4   r2   rK   r   ÚABNORMAL_CLOSUREÚcoderZ   r,   r,   r-   Ú
close_code«   s
   

zProtocol.close_codeúOptional[str]c                 C  s$   | j turdS | jdu rdS | jjS )zÑ
        `WebSocket close reason`_.

        .. _WebSocket close reason:
            https://www.rfc-editor.org/rfc/rfc6455.html#section-7.1.6

        :obj:`None` if the connection isn't closed yet.

        NÚ )r4   r2   rK   ÚreasonrZ   r,   r,   r-   Úclose_reason½   s
   

zProtocol.close_reasonr	   c                 C  sf   | j tu s	J dƒ‚| jdur"| jdur"| jjtv r"| jjtv r"t}nt}|| j| j| jƒ}| j	|_
|S )aè  
        Exception to raise when trying to interact with a closed connection.

        Don't raise this exception while the connection :attr:`state`
        is :attr:`~websockets.protocol.State.CLOSING`; wait until
        it's :attr:`~websockets.protocol.State.CLOSED`.

        Indeed, the exception includes the close code and reason, which are
        known only once the connection is closed.

        Raises:
            AssertionError: if the connection isn't closed yet.

        zconnection isn't closed yetN)r4   r2   rK   rL   r\   r   r   r
   rM   rV   Ú	__cause__)rW   Úexc_typeÚexcr,   r,   r-   Ú	close_excÏ   s   

ýzProtocol.close_excÚdataÚbytesc                 C  s   | j  |¡ t| jƒ dS )aH  
        Receive data from the network.

        After calling this method:

        - You must call :meth:`data_to_send` and send this data to the network.
        - You should call :meth:`events_received` and process resulting events.

        Raises:
            EOFError: if :meth:`receive_eof` was called earlier.

        N)rP   Ú	feed_datarU   rT   ©rW   rf   r,   r,   r-   Úreceive_dataõ   s   zProtocol.receive_datac                 C  s   | j  ¡  t| jƒ dS )aÇ  
        Receive the end of the data stream from the network.

        After calling this method:

        - You must call :meth:`data_to_send` and send this data to the network;
          it will return ``[b""]``, signaling the end of the stream, or ``[]``.
        - You aren't expected to call :meth:`events_received`; it won't return
          any new events.

        Raises:
            EOFError: if :meth:`receive_eof` was called earlier.

        N)rP   Úfeed_eofrU   rT   rZ   r,   r,   r-   Úreceive_eof  s   
zProtocol.receive_eofÚfinÚboolc                 C  s,   | j stdƒ‚| | _ |  tt||ƒ¡ dS )aõ  
        Send a `Continuation frame`_.

        .. _Continuation frame:
            https://datatracker.ietf.org/doc/html/rfc6455#section-5.6

        Parameters:
            data: payload containing the same kind of data
                as the initial frame.
            fin: FIN bit; set it to :obj:`True` if this is the last frame
                of a fragmented message and to :obj:`False` otherwise.

        Raises:
            ProtocolError: if a fragmented message isn't in progress.

        úunexpected continuation frameN)rG   r   Ú
send_framer   r   ©rW   rf   rm   r,   r,   r-   Úsend_continuation  s   zProtocol.send_continuationTc                 C  ó,   | j rtdƒ‚| | _ |  tt||ƒ¡ dS )a£  
        Send a `Text frame`_.

        .. _Text frame:
            https://datatracker.ietf.org/doc/html/rfc6455#section-5.6

        Parameters:
            data: payload containing text encoded with UTF-8.
            fin: FIN bit; set it to :obj:`False` if this is the first frame of
                a fragmented message.

        Raises:
            ProtocolError: if a fragmented message is in progress.

        úexpected a continuation frameN)rG   r   rp   r   r   rq   r,   r,   r-   Ú	send_text/  ó   zProtocol.send_textc                 C  rs   )a¥  
        Send a `Binary frame`_.

        .. _Binary frame:
            https://datatracker.ietf.org/doc/html/rfc6455#section-5.6

        Parameters:
            data: payload containing arbitrary binary data.
            fin: FIN bit; set it to :obj:`False` if this is the first frame of
                a fragmented message.

        Raises:
            ProtocolError: if a fragmented message is in progress.

        rt   N)rG   r   rp   r   r   rq   r,   r,   r-   Úsend_binaryD  rv   zProtocol.send_binaryr_   r\   r`   Ústrc                 C  sj   | j rtdƒ‚|du r|dkrtdƒ‚ttjdƒ}d}n	t||ƒ}| ¡ }|  tt|ƒ¡ || _	t
| _dS )a†  
        Send a `Close frame`_.

        .. _Close frame:
            https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.1

        Parameters:
            code: close code.
            reason: close reason.

        Raises:
            ProtocolError: if a fragmented message is being sent, if the code
                isn't valid, or if a reason is provided without a code

        rt   Nr_   z#cannot send a reason without a coder3   )rG   r   r   r   ÚNO_STATUS_RCVDÚ	serializerp   r   r   rL   r1   r4   ©rW   r\   r`   Úcloserf   r,   r,   r-   Ú
send_closeY  s   

zProtocol.send_closec                 C  ó   |   tt|ƒ¡ dS )zÚ
        Send a `Ping frame`_.

        .. _Ping frame:
            https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2

        Parameters:
            data: payload containing arbitrary binary data.

        N)rp   r   r   ri   r,   r,   r-   Ú	send_pingy  ó   zProtocol.send_pingc                 C  r~   )zÚ
        Send a `Pong frame`_.

        .. _Pong frame:
            https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3

        Parameters:
            data: payload containing arbitrary binary data.

        N)rp   r   r   ri   r,   r,   r-   Ú	send_pong†  r€   zProtocol.send_pongÚintc                 C  sr   | j tu r!|tjkr!t||ƒ}| ¡ }|  tt|ƒ¡ || _	t
| _ | jtu r-| js-|  ¡  |  ¡ | _t| jƒ dS )a?  
        `Fail the WebSocket connection`_.

        .. _Fail the WebSocket connection:
            https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.7

        Parameters:
            code: close code
            reason: close reason

        Raises:
            ProtocolError: if the code isn't valid.
        N)r4   r0   r   r[   r   rz   rp   r   r   rL   r1   r7   r*   rO   Úsend_eofÚdiscardrT   rU   r{   r,   r,   r-   Úfail“  s   



zProtocol.failúList[Event]c                 C  ó   | j g }| _ |S )a7  
        Fetch events generated from data received from the network.

        Call this method immediately after any of the ``receive_*()`` methods.

        Process resulting events, likely by passing them to the application.

        Returns:
            List[Event]: Events read from the connection.
        )rQ   )rW   rQ   r,   r,   r-   Úevents_received¾  s   zProtocol.events_receivedúList[bytes]c                 C  r‡   )aÖ  
        Obtain data to send to the network.

        Call this method immediately after any of the ``receive_*()``,
        ``send_*()``, or :meth:`fail` methods.

        Write resulting data to the connection.

        The empty bytestring :data:`~websockets.protocol.SEND_EOF` signals
        the end of the data stream. When you receive it, half-close the TCP
        connection.

        Returns:
            List[bytes]: Data to write to the connection.

        )rR   )rW   rR   r,   r,   r-   Údata_to_sendÎ  s   zProtocol.data_to_sendc                 C  s   | j tu p	| jduS )a¯  
        Tell if the TCP connection is expected to close soon.

        Call this method immediately after any of the ``receive_*()``,
        ``send_close()``, or :meth:`fail` methods.

        If it returns :obj:`True`, schedule closing the TCP connection after a
        short timeout if the other side hasn't already closed it.

        Returns:
            bool: Whether the TCP connection is expected to close soon.

        N)r4   r1   rN   rZ   r,   r,   r-   Úclose_expectedâ  s   zProtocol.close_expectedúGenerator[None, None, None]c              
   c  sè  � zO	 | j  ¡ E dH r| jr| j d¡ tdƒ‚| jdu r d}n| jdu r)| j}n| j| j }tj| j j	| j
tu || jd�E dH }| jrK| j d|¡ |  |¡ q tyn } z|  tjt|ƒ¡ || _W Y d}~nƒd}~w ty‹ } z|  tjt|ƒ¡ || _W Y d}~nfd}~w ty­ } z|  tj|j› d|j› �¡ || _W Y d}~nDd}~w tyÊ } z|  tjt|ƒ¡ || _W Y d}~n'd}~w tyì } z| jjddd	� |  tj¡ || _W Y d}~nd}~ww dV  td
ƒ‚)a-  
        Parse incoming data into frames.

        :meth:`receive_data` and :meth:`receive_eof` run this generator
        coroutine until it needs more data or reaches EOF.

        :meth:`parse` never raises an exception. Instead, it sets the
        :attr:`parser_exc` and yields control.

        TNú< EOFzunexpected end of stream)Úmaskr5   rI   z< %sz at position zparser failed)Úexc_infoz"parse() shouldn't step after error)rP   Úat_eofrE   r6   ÚEOFErrorr5   rF   r   rS   Ú
read_exactr7   r*   rI   Ú
recv_framer   r…   r   ÚPROTOCOL_ERRORrx   rV   r[   ÚUnicodeDecodeErrorÚINVALID_DATAr`   Ústartr   ÚMESSAGE_TOO_BIGÚ	ExceptionÚerrorÚINTERNAL_ERRORÚAssertionError)rW   r5   Úframerd   r,   r,   r-   rS   ü  s\   €

ü
â €€€€€üzProtocol.parsec                 c  sx   � | j tu | jksJ ‚| j ¡ E dH s | j ¡  | j ¡ E dH r| jr)| j d¡ | j tu r2|  	¡  t
| _dV  tdƒ‚)zí
        Discard incoming data.

        This coroutine replaces :meth:`parse`:

        - after receiving a close frame, during a normal closure (1.4);
        - after sending a close frame, during an abnormal closure (7.1.7).

        Nr�   z"discard() shouldn't step after EOF)r7   r*   rO   rP   r�   r„   rE   r6   r+   rƒ   r2   r4   rœ   rZ   r,   r,   r-   r„   C  s   €
ÿ
zProtocol.discardr�   r   c                 C  sr  |j tu s
|j tu r!| jdurtdƒ‚|jrd| _n—t|jƒ| _n�|j tu rA| jdu r/tdƒ‚|jr6d| _n{|  jt|jƒ7  _np|j t	u rRt
t|jƒ}|  |¡ n_|j tu rXnY|j tu r¨t |j¡| _| jtu rs| jduspJ ‚d| _| jdur|tdƒ‚| jtu r”|  t
t|jƒ¡ | j| _d| _t| _| jtu r�|  ¡  |  ¡ | _t| jƒ n	td|j d›�ƒ‚| j |¡ dS )	z-
        Process an incoming frame.

        Nrt   ro   Fzincomplete fragmented messageTzunexpected opcode: Ú02x)Úopcoder   r   rF   r   rm   Úlenrf   r   r   r   r   rp   r   r   rS   rK   r4   r1   rL   rM   r0   r7   r*   rƒ   r„   rT   rU   rœ   rQ   Úappend)rW   r�   Ú
pong_framer,   r,   r-   r“   a  sF   










zProtocol.recv_framec                 C  sT   | j turtd| j j› d�ƒ‚| jr| j d|¡ | j |j| j	t
u | jd�¡ d S )Nz#cannot write to a WebSocket in the z statez> %s)rŽ   rI   )r4   r0   r   rA   rE   r6   rR   r¡   rz   r7   r+   rI   )rW   r�   r,   r,   r-   rp   ³  s   
ÿÿzProtocol.send_framec                 C  s2   | j rJ ‚d| _ | jr| j d¡ | j t¡ d S )NTz> EOF)rO   rE   r6   rR   r¡   r#   rZ   r,   r,   r-   rƒ   ¿  s
   
zProtocol.send_eof)
r7   r!   r4   r"   r5   r8   r6   r9   r:   r;   )r:   r"   )r4   r"   r:   r;   )r:   r8   )r:   r^   )r:   r	   )rf   rg   r:   r;   )r:   r;   )rf   rg   rm   rn   r:   r;   )T)Nr_   )r\   r8   r`   rx   r:   r;   )r_   )r\   r‚   r`   rx   r:   r;   )r:   r†   )r:   r‰   )r:   rn   )r:   rŒ   )r�   r   r:   r;   )r%   r&   r'   r(   r0   rX   Úpropertyr4   Úsetterr]   ra   re   rj   rl   rr   ru   rw   r}   r   r�   r…   rˆ   rŠ   r‹   rS   r„   r“   rp   rƒ   r,   r,   r,   r-   r    G   sB    úD	
%


 

+



G

Rr    )4Ú
__future__r   Úenumr?   r<   Útypingr   r   r   r   r   Ú
exceptionsr	   r
   r   r   r   r   rI   r   Úframesr   r   r   r   r   r   r   r   r   r   Úhttp11r   r   Ústreamsr   r   r   r   Ú__all__ÚEventÚIntEnumr!   r*   r+   r"   r/   r0   r1   r2   r#   r    r,   r,   r,   r-   Ú<module>   s2     0