o
    ïÅ[hÂð  ã                   @  sP  d dl mZ d dlZd dlZd dlZd dlZd dl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mZmZmZmZmZmZmZ ddlmZ ddl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.m/Z/ dd
l
m0Z0m1Z1m2Z2 ddl3m4Z4 ddl5m6Z6 ddgZ7G dd„ dej8ƒZ9ddd„Z:dS )é    )ÚannotationsN)ÚAnyÚAsyncIterableÚAsyncIteratorÚ	AwaitableÚDequeÚDictÚIterableÚListÚMappingÚOptionalÚUnionÚcasté   )ÚState)ÚHeaders)ÚConnectionClosedÚConnectionClosedErrorÚConnectionClosedOKÚInvalidStateÚPayloadTooBigÚProtocolError)Ú	Extension)ÚOK_CLOSE_CODESÚ	OP_BINARYÚOP_CLOSEÚOP_CONTÚOP_PINGÚOP_PONGÚOP_TEXTÚCloseÚOpcodeÚprepare_ctrlÚprepare_data)ÚDataÚ
LoggerLikeÚSubprotocolé   )Úloop_if_py_lt_38)ÚFrameÚWebSocketCommonProtocolÚ	broadcastc                   @  s"  e Zd ZU dZded< dZded< ddddd	d
dddddddddœd–d%d&„Zd—d'd(„Zd—d)d*„Zd—d+d,„Z	e
d˜d-d.„ƒZe
d™d/d0„ƒZe
dšd1d2„ƒZe
d›d4d5„ƒZe
d›d6d7„ƒZe
dœd8d9„ƒZe
dœd:d;„ƒZe
d™d<d=„ƒZe
d˜d>d?„ƒZddAdB„ZdždDdE„ZdŸdHdI„Zd d¡dNdO„Zd—dPdQ„Zd¢d£dUdV„Zd¤d¥dXdY„Zd¦d[d\„Zd—d]d^„Zd—d_d`„Zd§dadb„Zd¨ddde„Zd©dgdh„Z dªdldm„Z!d—dndo„Z"e#j$dpœd«drds„Z%	d¢d¬dwdx„Z&d—dydz„Z'd—d{d|„Z(d—d}d~„Z)dœdd€„Z*d­d¡d‚dƒ„Z+d—d„d…„Z,d®dˆd‰„Z-d¯dŒd„Z.d—dŽd„Z/d—dd‘„Z0d°d’d“„Z1d—d”d•„Z2dS )±r*   u"  
    WebSocket connection.

    :class:`WebSocketCommonProtocol` provides APIs shared between WebSocket
    servers and clients. You shouldn't use it directly. Instead, use
    :class:`~websockets.client.WebSocketClientProtocol` or
    :class:`~websockets.server.WebSocketServerProtocol`.

    This documentation focuses on low-level details that aren't covered in the
    documentation of :class:`~websockets.client.WebSocketClientProtocol` and
    :class:`~websockets.server.WebSocketServerProtocol` for the sake of
    simplicity.

    Once the connection is open, a Ping_ frame is sent every ``ping_interval``
    seconds. This serves as a keepalive. It helps keeping the connection
    open, especially in the presence of proxies with short timeouts on
    inactive connections. Set ``ping_interval`` to :obj:`None` to disable
    this behavior.

    .. _Ping: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.5.2

    If the corresponding Pong_ frame isn't received within ``ping_timeout``
    seconds, the connection is considered unusable and is closed with code
    1011. This ensures that the remote endpoint remains responsive. Set
    ``ping_timeout`` to :obj:`None` to disable this behavior.

    .. _Pong: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.5.3

    The ``close_timeout`` parameter defines a maximum wait time for completing
    the closing handshake and terminating the TCP connection. For legacy
    reasons, :meth:`close` completes in at most ``5 * close_timeout`` seconds
    for clients and ``4 * close_timeout`` for servers.

    See the discussion of :doc:`timeouts <../topics/timeouts>` for details.

    ``close_timeout`` needs to be a parameter of the protocol because
    websockets usually calls :meth:`close` implicitly upon exit:

    * on the client side, when :func:`~websockets.client.connect` is used as a
      context manager;
    * on the server side, when the connection handler terminates;

    To apply a timeout to any other API, wrap it in :func:`~asyncio.wait_for`.

    The ``max_size`` parameter enforces the maximum size for incoming messages
    in bytes. The default value is 1Â MiB. If a larger message is received,
    :meth:`recv` will raise :exc:`~websockets.exceptions.ConnectionClosedError`
    and the connection will be closed with code 1009.

    The ``max_queue`` parameter sets the maximum length of the queue that
    holds incoming messages. The default value is ``32``. Messages are added
    to an in-memory queue when they're received; then :meth:`recv` pops from
    that queue. In order to prevent excessive memory consumption when
    messages are received faster than they can be processed, the queue must
    be bounded. If the queue fills up, the protocol stops processing incoming
    data until :meth:`recv` is called. In this situation, various receive
    buffers (at least in :mod:`asyncio` and in the OS) will fill up, then the
    TCP receive window will shrink, slowing down transmission to avoid packet
    loss.

    Since Python can use up to 4 bytes of memory to represent a single
    character, each connection may use up to ``4 * max_size * max_queue``
    bytes of memory to store incoming messages. By default, this is 128Â MiB.
    You may want to lower the limits, depending on your application's
    requirements.

    The ``read_limit`` argument sets the high-water limit of the buffer for
    incoming bytes. The low-water limit is half the high-water limit. The
    default value is 64Â KiB, half of asyncio's default (based on the current
    implementation of :class:`~asyncio.StreamReader`).

    The ``write_limit`` argument sets the high-water limit of the buffer for
    outgoing bytes. The low-water limit is a quarter of the high-water limit.
    The default value is 64Â KiB, equal to asyncio's default (based on the
    current implementation of ``FlowControlMixin``).

    See the discussion of :doc:`memory usage <../topics/memory>` for details.

    Args:
        logger: logger for this connection;
            defaults to ``logging.getLogger("websockets.protocol")``;
            see the :doc:`logging guide <../topics/logging>` for details.
        ping_interval: delay between keepalive pings in seconds;
            :obj:`None` to disable keepalive pings.
        ping_timeout: timeout for keepalive pings in seconds;
            :obj:`None` to disable timeouts.
        close_timeout: timeout for closing the connection in seconds;
            for legacy reasons, the actual timeout is 4 or 5 times larger.
        max_size: maximum size of incoming messages in bytes;
            :obj:`None` to disable the limit.
        max_queue: maximum number of incoming messages in receive buffer;
            :obj:`None` to disable the limit.
        read_limit: high-water mark of read buffer in bytes.
        write_limit: high-water mark of write buffer in bytes.

    ÚboolÚ	is_clientZ	undefinedÚstrÚsideNé   i   é    i   F)ÚloggerÚping_intervalÚping_timeoutÚclose_timeoutÚmax_sizeÚ	max_queueÚ
read_limitÚwrite_limitÚhostÚportÚsecureÚlegacy_recvÚloopÚtimeoutr2   úOptional[LoggerLike]r3   úOptional[float]r4   r5   r6   úOptional[int]r7   r8   Úintr9   r:   úOptional[str]r;   r<   úOptional[bool]r=   r>   ú#Optional[asyncio.AbstractEventLoop]r?   ÚreturnÚNonec                C  s¬  |rt  dt¡ |d u rd}nt  dt¡ |d u r|}|d u r$t ¡ }nt  dt¡ || _|| _|| _|| _|| _	|| _
|| _t ¡ | _	 |d u rNt d¡}ttj|ƒ}t |d| i¡| _	 | tj¡| _|| _|	| _|
| _|| _|| _tj|d |d| _d	| _d | _ tj!di t"|ƒ¤Ž| _#t$j%| _&| jrœ| j d
¡ |  	 |  	 |  	 g | _'d | _(	 d | _)d | _*d | _+| ,¡ | _-t. /¡ | _0d | _1d | _2d | _3i | _4|  d | _5|  |  d S )Nzlegacy_recv is deprecatedé
   zrename timeout to close_timeoutzremove loop argumentzwebsockets.protocolÚ	websocketr   )Úlimitr>   Fz= connection is CONNECTING© )6ÚwarningsÚwarnÚDeprecationWarningÚasyncioZget_event_loopr3   r4   r5   r6   r7   r8   r9   ÚuuidÚuuid4ÚidÚloggingÚ	getLoggerr   ÚLoggerÚLoggerAdapterr2   ÚisEnabledForÚDEBUGÚdebugr>   Ú_hostÚ_portÚ_securer=   ÚStreamReaderÚreaderÚ_pausedÚ_drain_waiterÚLockr(   Ú_drain_lockr   Ú
CONNECTINGÚstateÚ
extensionsZsubprotocolÚ
close_rcvdÚ
close_sentÚclose_rcvd_then_sentÚcreate_futureÚconnection_lost_waiterÚcollectionsÚdequeÚmessagesÚ_pop_message_waiterÚ_put_message_waiterÚ_fragmented_message_waiterÚpingsÚtransfer_data_exc)Úselfr2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   rL   rL   ú/home/ubuntu/experiments/live_experiments/Pythonexperiments/Otree/venv/lib/python3.10/site-packages/websockets/legacy/protocol.pyÚ__init__§   sv   




z WebSocketCommonProtocol.__init__c                 Ã  sV   | j  ¡ r
tdƒ‚| jsd S | j}|d u s| ¡ sJ ‚| j ¡ }|| _|I d H  d S )NzConnection lost)rk   ÚdoneÚConnectionResetErrorr`   ra   Z	cancelledr>   rj   ©rt   ÚwaiterrL   rL   ru   Ú_drain_helper.  s   €

z%WebSocketCommonProtocol._drain_helperc                 Ã  sd   | j d ur| j  ¡ }|d ur|‚| jd ur)| j ¡ r)tjdi t| jƒ¤ŽI d H  |  ¡ I d H  d S )Nr   )r   )	r_   Ú	exceptionÚ	transportÚ
is_closingrP   Úsleepr(   r>   r{   ©rt   ÚexcrL   rL   ru   Ú_drain:  s   €



zWebSocketCommonProtocol._drainc                 C  sd   | j tju sJ ‚tj| _ | jr| j d¡ | j |  ¡ ¡| _	| j |  
¡ ¡| _| j |  ¡ ¡| _dS )zŒ
        Callback when the WebSocket opening handshake completes.

        Enter the OPEN state and start the data transfer phase.

        z= connection is OPENN)re   r   rd   ÚOPENrZ   r2   r>   Úcreate_taskÚtransfer_dataÚtransfer_data_taskÚkeepalive_pingÚkeepalive_ping_taskÚclose_connectionÚclose_connection_task©rt   rL   rL   ru   Úconnection_openJ  s   z'WebSocketCommonProtocol.connection_openc                 C  ó(   | j rdnd}t d|› dt¡ | jS )NÚremote_addressÚlocal_addressúuse z[0] instead of host)r-   rM   rN   rO   r[   ©rt   ÚalternativerL   rL   ru   r:   ]  ó   zWebSocketCommonProtocol.hostc                 C  r   )NrŽ   r   r   z[1] instead of port)r-   rM   rN   rO   r\   r‘   rL   rL   ru   r;   c  r“   zWebSocketCommonProtocol.portc                 C  s   t  dt¡ | jS )Nzdon't use secure)rM   rN   rO   r]   r‹   rL   rL   ru   r<   i  s   zWebSocketCommonProtocol.securer   c                 C  ó*   z| j }W n
 ty   Y dS w | d¡S )a(  
        Local address of the connection.

        For IPv4 connections, this is a ``(host, port)`` tuple.

        The format of the address depends on the address family;
        see :meth:`~socket.socket.getsockname`.

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

        NZsockname©r}   ÚAttributeErrorZget_extra_info©rt   r}   rL   rL   ru   r   p  ó   
ÿ
z%WebSocketCommonProtocol.local_addressc                 C  r”   )a)  
        Remote address of the connection.

        For IPv4 connections, this is a ``(host, port)`` tuple.

        The format of the address depends on the address family;
        see :meth:`~socket.socket.getpeername`.

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

        NZpeernamer•   r—   rL   rL   ru   rŽ   „  r˜   z&WebSocketCommonProtocol.remote_addressc                 C  s   | j tju o| j ¡  S )a{  
        :obj:`True` when the connection is open; :obj:`False` otherwise.

        This attribute may be used to detect disconnections. However, this
        approach is discouraged per the EAFP_ principle. Instead, you should
        handle :exc:`~websockets.exceptions.ConnectionClosed` exceptions.

        .. _EAFP: https://docs.python.org/3/glossary.html#term-eafp

        )re   r   rƒ   r†   rw   r‹   rL   rL   ru   Úopen˜  s   zWebSocketCommonProtocol.openc                 C  s   | j tju S )zÔ
        :obj:`True` when the connection is closed; :obj:`False` otherwise.

        Be aware that both :attr:`open` and :attr:`closed` are :obj:`False`
        during the opening and closing sequences.

        )re   r   ÚCLOSEDr‹   rL   rL   ru   Úclosed¦  s   	zWebSocketCommonProtocol.closedc                 C  ó&   | j tjurdS | jdu rdS | jjS )zø
        WebSocket close code, defined in `section 7.1.5 of RFC 6455`_.

        .. _section 7.1.5 of RFC 6455:
            https://www.rfc-editor.org/rfc/rfc6455.html#section-7.1.5

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

        Néî  )re   r   rš   rg   Úcoder‹   rL   rL   ru   Ú
close_code±  ó
   
z"WebSocketCommonProtocol.close_codec                 C  rœ   )zú
        WebSocket close reason, defined in `section 7.1.6 of RFC 6455`_.

        .. _section 7.1.6 of RFC 6455:
            https://www.rfc-editor.org/rfc/rfc6455.html#section-7.1.6

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

        NÚ )re   r   rš   rg   Úreasonr‹   rL   rL   ru   Úclose_reasonÃ  r    z$WebSocketCommonProtocol.close_reasonúAsyncIterator[Data]c                 C s,   z
	 |   ¡ I dH V  q ty   Y dS w )a<  
        Iterate on incoming messages.

        The iterator  exits normally when the connection is closed with the
        close code 1000 (OK) or 1001(going away). It raises
        a :exc:`~websockets.exceptions.ConnectionClosedError` exception when
        the connection is closed with any other code.

        TN)Úrecvr   r‹   rL   rL   ru   Ú	__aiter__Õ  s   €
ÿÿz!WebSocketCommonProtocol.__aiter__r$   c                 Ã  sÈ   | j dur
tdƒ‚t| jƒdkrO| j ¡ }|| _ ztj|| jgfdtj	it
| jƒ¤ŽI dH  W d| _ nd| _ w | ¡ sH| jrAdS |  ¡ I dH  t| jƒdks| j ¡ }| jdurb| j d¡ d| _|S )aš  
        Receive the next message.

        When the connection is closed, :meth:`recv` raises
        :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it
        raises :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal
        connection closure and
        :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol
        error or a network failure. This is how you detect the end of the
        message stream.

        Canceling :meth:`recv` is safe. There's no risk of losing the next
        message. The next invocation of :meth:`recv` will return it.

        This makes it possible to enforce a timeout by wrapping :meth:`recv`
        in :func:`~asyncio.wait_for`.

        Returns:
            Data: A string (:class:`str`) for a Text_ frame. A bytestring
            (:class:`bytes`) for a Binary_ frame.

            .. _Text: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.6
            .. _Binary: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.6

        Raises:
            ConnectionClosed: when the connection is closed.
            RuntimeError: if two coroutines call :meth:`recv` concurrently.

        NzPcannot call recv while another coroutine is already waiting for the next messager   Zreturn_when)ro   ÚRuntimeErrorÚlenrn   r>   rj   rP   Úwaitr†   ZFIRST_COMPLETEDr(   rw   r=   Úensure_openÚpopleftrp   Ú
set_result)rt   Zpop_message_waiterÚmessagerL   rL   ru   r¥   å  s6   €
ÿ
ÿþýé

zWebSocketCommonProtocol.recvr­   ú0Union[Data, Iterable[Data], AsyncIterable[Data]]c              	   Ã  s¬  |   ¡ I dH  | jdurt | j¡I dH  | jdust|ttttfƒr6t	|ƒ\}}|  
d||¡I dH  dS t|tƒr?tdƒ‚t|tƒrÃttt |ƒ}t|ƒ}zt|ƒ}W n
 ty_   Y dS w t	|ƒ\}}t ¡ | _zMz3|  
d||¡I dH  |D ]}t	|ƒ\}}||kr‰tdƒ‚|  
dt|¡I dH  qy|  
dtd¡I dH  W n ty¬   |  d¡ ‚ w W | j d¡ d| _dS | j d¡ d| _w t|tƒrRt|ƒ |¡}zt|ƒ |¡I dH }W n
 tyæ   Y dS w t	|ƒ\}}t ¡ | _zUz:|  
d||¡I dH  |2 z 3 dH W }t	|ƒ\}}||krtdƒ‚|  
dt|¡I dH  q 6 |  
dtd¡I dH  W n ty;   |  d¡ ‚ w W | j d¡ d| _dS | j d¡ d| _w tdƒ‚)	a–	  
        Send a message.

        A string (:class:`str`) is sent as a Text_ frame. A bytestring or
        bytes-like object (:class:`bytes`, :class:`bytearray`, or
        :class:`memoryview`) is sent as a Binary_ frame.

        .. _Text: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.6
        .. _Binary: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.6

        :meth:`send` also accepts an iterable or an asynchronous iterable of
        strings, bytestrings, or bytes-like objects to enable fragmentation_.
        Each item is treated as a message fragment and sent in its own frame.
        All items must be of the same type, or else :meth:`send` will raise a
        :exc:`TypeError` and the connection will be closed.

        .. _fragmentation: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.4

        :meth:`send` rejects dict-like objects because this is often an error.
        (If you want to send the keys of a dict-like object as fragments, call
        its :meth:`~dict.keys` method and pass the result to :meth:`send`.)

        Canceling :meth:`send` is discouraged. Instead, you should close the
        connection with :meth:`close`. Indeed, there are only two situations
        where :meth:`send` may yield control to the event loop and then get
        canceled; in both cases, :meth:`close` has the same effect and is
        more clear:

        1. The write buffer is full. If you don't want to wait until enough
           data is sent, your only alternative is to close the connection.
           :meth:`close` will likely time out then abort the TCP connection.
        2. ``message`` is an asynchronous iterator that yields control.
           Stopping in the middle of a fragmented message will cause a
           protocol error and the connection will be closed.

        When the connection is closed, :meth:`send` raises
        :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it
        raises :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal
        connection closure and
        :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol
        error or a network failure.

        Args:
            message (Union[Data, Iterable[Data], AsyncIterable[Data]): message
                to send.

        Raises:
            ConnectionClosed: when the connection is closed.
            TypeError: if ``message`` doesn't have a supported type.

        NTzdata is a dict-like objectFz data contains inconsistent typesó    éó  z)data must be str, bytes-like, or iterable)rª   rq   rP   ÚshieldÚ
isinstancer.   ÚbytesÚ	bytearrayÚ
memoryviewr#   Úwrite_framer   Ú	TypeErrorr	   r   r$   ÚiterÚnextÚStopIterationÚFuturer   Ú	ExceptionÚfail_connectionr¬   r   Útyper¦   Ú	__anext__ÚStopAsyncIteration)rt   r­   ÚopcodeÚdataZiter_messageZmessage_chunkZconfirm_opcodeZaiter_messagerL   rL   ru   Úsend4  s†   €7

ÿ

ÿ

üþ	
ÿÿÿ

ü
üþ	
ÿzWebSocketCommonProtocol.sendéè  r¡   rž   r¢   c              	   Ã  s¬   zt j|  t||ƒ¡| jfi t| jƒ¤ŽI dH  W n t jy(   |  ¡  Y nw zt j| j	| jfi t| jƒ¤ŽI dH  W n t jt j
fyJ   Y nw t  | j¡I dH  dS )ae  
        Perform the closing handshake.

        :meth:`close` waits for the other end to complete the handshake and
        for the TCP connection to terminate. As a consequence, there's no need
        to await :meth:`wait_closed` after :meth:`close`.

        :meth:`close` is idempotent: it doesn't do anything once the
        connection is closed.

        Wrapping :func:`close` in :func:`~asyncio.create_task` is safe, given
        that errors during connection termination aren't particularly useful.

        Canceling :meth:`close` is discouraged. If it takes too long, you can
        set a shorter ``close_timeout``. If you don't want to wait, let the
        Python process exit, then the OS will take care of closing the TCP
        connection.

        Args:
            code: WebSocket close code.
            reason: WebSocket close reason.

        N)rP   Úwait_forÚwrite_close_framer    r5   r(   r>   ÚTimeoutErrorr½   r†   ÚCancelledErrorr±   rŠ   )rt   rž   r¢   rL   rL   ru   ÚcloseÔ  s,   €þýüþýÿzWebSocketCommonProtocol.closec                 Ã  s   t  | j¡I dH  dS )a9  
        Wait until the connection is closed.

        This coroutine is identical to the :attr:`closed` attribute, except it
        can be awaited.

        This can make it easier to detect connection termination, regardless
        of its cause, in tasks that interact with the WebSocket connection.

        N)rP   r±   rk   r‹   rL   rL   ru   Úwait_closed  s   €z#WebSocketCommonProtocol.wait_closedrÂ   úOptional[Data]úAwaitable[None]c                 Ã  sœ   |   ¡ I dH  |durt|ƒ}|| jv rtdƒ‚|du s"|| jv r4t dt d¡¡}|du s"|| jv s"| j 	¡ | j|< |  
dt|¡I dH  t | j| ¡S )a  
        Send a Ping_.

        .. _Ping: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.5.2

        A ping may serve as a keepalive or as a check that the remote endpoint
        received all messages up to this point

        Canceling :meth:`ping` is discouraged. If :meth:`ping` doesn't return
        immediately, it means the write buffer is full. If you don't want to
        wait, you should close the connection.

        Canceling the :class:`~asyncio.Future` returned by :meth:`ping` has no
        effect.

        Args:
            data (Optional[Data]): payload of the ping; a string will be
                encoded to UTF-8; or :obj:`None` to generate a payload
                containing four random bytes.

        Returns:
            ~asyncio.Future: A future that will be completed when the
            corresponding pong is received. You can ignore it if you
            don't intend to wait.

            ::

                pong_waiter = await ws.ping()
                await pong_waiter  # only if you want to wait for the pong

        Raises:
            ConnectionClosed: when the connection is closed.
            RuntimeError: if another ping was sent with the same data and
                the corresponding pong wasn't received yet.

        Nz-already waiting for a pong with the same dataz!Ir1   T)rª   r"   rr   r§   ÚstructÚpackÚrandomÚgetrandbitsr>   rj   r¶   r   rP   r±   ©rt   rÂ   rL   rL   ru   Úping  s   €%
ÿzWebSocketCommonProtocol.pingr¯   c                 Ã  s0   |   ¡ I dH  t|ƒ}|  dt|¡I dH  dS )a<  
        Send a Pong_.

        .. _Pong: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.5.3

        An unsolicited pong may serve as a unidirectional heartbeat.

        Canceling :meth:`pong` is discouraged. If :meth:`pong` doesn't return
        immediately, it means the write buffer is full. If you don't want to
        wait, you should close the connection.

        Args:
            data (Data): payload of the pong; a string will be encoded to
                UTF-8.

        Raises:
            ConnectionClosed: when the connection is closed.

        NT)rª   r"   r¶   r   rÑ   rL   rL   ru   ÚpongR  s   €zWebSocketCommonProtocol.pongr   c                 C  s^   | j d ur | j jtv r | jd ur | jjtv r t| j | j| jƒ}n	t| j | j| jƒ}| j|_|S ©N)	rg   rž   r   rh   r   ri   r   rs   Ú	__cause__r€   rL   rL   ru   Úconnection_closed_excn  s    

ýýz-WebSocketCommonProtocol.connection_closed_excc                 Ã  sˆ   | j tju r| j ¡ rt | j¡I dH  |  ¡ ‚dS | j tj	u r%|  ¡ ‚| j tj
u r8t | j¡I dH  |  ¡ ‚| j tju s@J ‚tdƒ‚)zŠ
        Check that the WebSocket connection is open.

        Raise :exc:`~websockets.exceptions.ConnectionClosed` if it isn't.

        Nz*WebSocket connection isn't established yet)re   r   rƒ   r†   rw   rP   r±   rŠ   rÖ   rš   ÚCLOSINGrd   r   r‹   rL   rL   ru   rª   …  s   €
z#WebSocketCommonProtocol.ensure_openc              
   Ã  sä  zR	 |   ¡ I dH }|du rW dS | jdur?t| jƒ| jkr?| j ¡ | _zt | j¡I dH  W d| _nd| _w t| jƒ| jks| j 	|¡ | j
durS| j
 d¡ d| _
q tjyd } z|| _‚ d}~w ty~ } z|| _|  d¡ W Y d}~dS d}~w tttfy› } z|| _|  d¡ W Y d}~dS d}~w tyµ } z|| _|  d¡ W Y d}~dS d}~w tyÏ } z|| _|  d¡ W Y d}~dS d}~w tyñ } z| jjddd || _|  d	¡ W Y d}~dS d}~ww )
z‘
        Read incoming messages and put them in a queue.

        This coroutine runs in a task until the closing handshake is started.

        TNiê  r   iï  iñ  zdata transfer failed©Úexc_infor°   )Úread_messager7   r¨   rn   r>   rj   rp   rP   r±   Úappendro   r¬   rÈ   rs   r   r½   ÚConnectionErrorrÇ   ÚEOFErrorÚUnicodeDecodeErrorr   r¼   r2   Úerror)rt   r­   r   rL   rL   ru   r…   §  sX   €
û
ê€€€€€€ùz%WebSocketCommonProtocol.transfer_datac                 ƒ  sF  | j | jdI dH }|du rdS |jtkrd}n|jtkr!d}ntdƒ‚|jr3|r0|j d¡S |jS g ‰ | j‰|r[t	 
d¡}|dd‰ˆdu rQd‡ ‡fdd„}nd‡ ‡‡fdd„}nˆdu rgd‡ fdd„}nd‡ ‡fdd„}||ƒ |js—| j ˆdI dH }|du r‡tdƒ‚|jtkrtdƒ‚||ƒ |jrv|ržd ˆ ¡S d ˆ ¡S )z¿
        Read a single message from the connection.

        Re-assemble data frames if the message is fragmented.

        Return :obj:`None` when the closing handshake is started.

        )r6   NTFzunexpected opcodezutf-8Ústrict)ÚerrorsÚframer)   rG   rH   c                   s   ˆ   ˆ | j| j¡¡ d S rÔ   )rÛ   ÚdecoderÂ   Úfin©râ   )ÚchunksÚdecoderrL   ru   rÛ     s   z4WebSocketCommonProtocol.read_message.<locals>.appendc                   s6   ˆ   ˆ | j| j¡¡ tˆtƒsJ ‚ˆt| jƒ8 ‰d S rÔ   )rÛ   rã   rÂ   rä   r²   rC   r¨   rå   ©ræ   rç   r6   rL   ru   rÛ     s   c                   s   ˆ   | j¡ d S rÔ   )rÛ   rÂ   rå   )ræ   rL   ru   rÛ     s   c                   s,   ˆ   | j¡ tˆtƒsJ ‚ˆt| jƒ8 ‰d S rÔ   )rÛ   rÂ   r²   rC   r¨   rå   )ræ   r6   rL   ru   rÛ   #  s   zincomplete fragmented messager¡   r¯   )râ   r)   rG   rH   )Úread_data_framer6   rÁ   r   r   r   rä   rÂ   rã   ÚcodecsÚgetincrementaldecoderr   Újoin)rt   râ   ÚtextZdecoder_factoryrÛ   rL   rè   ru   rÚ   ì  s@   €	




ú	z$WebSocketCommonProtocol.read_messageúOptional[Frame]c                 Ã  s.  	 |   |¡I dH }|jtkr7t |j¡| _| jdurd| _z|  	| j|j¡I dH  W dS  t
y6   Y dS w |jtkrX| jtju rWz|  |j¡I dH  W nH t
yV   Y n@w n>|jtkr”|j| jv r“d}g }| j ¡ D ]\}}| |¡ | ¡ s~| d¡ ||jkr… nqlJ dƒ‚|D ]}| j|= qŒn|S q)zØ
        Read a single data frame from the connection.

        Process control frames received before the next data frame.

        Return :obj:`None` if a close frame is encountered before any data frame.

        TNFzping_id is in self.pings)Ú
read_framerÁ   r   r    ÚparserÂ   rg   rh   ri   rÆ   r   r   re   r   rƒ   rÓ   r   rr   ÚitemsrÛ   rw   r¬   )rt   r6   râ   Zping_idZping_idsrÒ   rL   rL   ru   ré   6  sN   €


ýý
þý



ÿ
€Ïz'WebSocketCommonProtocol.read_data_framer)   c                 Ã  s<   t j| jj| j || jdI dH }| jr| j d|¡ |S )z;
        Read a single frame from the connection.

        )Úmaskr6   rf   Nz< %s)r)   Úreadr_   Zreadexactlyr-   rf   rZ   r2   )rt   r6   râ   rL   rL   ru   rï   s  s   €üz"WebSocketCommonProtocol.read_framerä   rÁ   r³   c                 C  s@   t |t|ƒ|ƒ}| jr| j d|¡ |j| jj| j| jd d S )Nz> %s)rò   rf   )r)   r!   rZ   r2   Úwriter}   r-   rf   )rt   rä   rÁ   rÂ   râ   rL   rL   ru   Úwrite_frame_sync‚  s   
ýz(WebSocketCommonProtocol.write_frame_syncc              	   Ã  s€   z)| j 4 I d H š |  ¡ I d H  W d   ƒI d H  W d S 1 I d H s#w   Y  W d S  ty?   |  ¡  |  ¡ I d H  Y d S w rÔ   )rc   r‚   rÜ   r½   rª   r‹   rL   rL   ru   ÚdrainŒ  s   €2þûzWebSocketCommonProtocol.drain©Ú_staterø   c                Ã  s@   | j |urtd| j j› dƒ‚|  |||¡ |  ¡ I d H  d S )Nz#Cannot write to a WebSocket in the z state)re   r   Únamerõ   rö   )rt   rä   rÁ   rÂ   rø   rL   rL   ru   r¶   ›  s   €
ÿz#WebSocketCommonProtocol.write_framerÉ   r    úOptional[bytes]c                 Ã  sp   | j tju r6tj| _ | jr| j d¡ || _| jdurd| _|du r'| 	¡ }| j
dt|tjdI dH  dS dS )zé
        Write a close frame if and only if the connection state is OPEN.

        This dedicated coroutine must be used for writing close frames to
        ensure that at most one close frame is sent on a given connection.

        ú= connection is CLOSINGNTr÷   )re   r   rƒ   r×   rZ   r2   rh   rg   ri   Ú	serializer¶   r   )rt   rÉ   rÂ   rL   rL   ru   rÆ   ¦  s   €
óz)WebSocketCommonProtocol.write_close_framec                 Ã  s
  | j du rdS zY	 tj| j fi t| jƒ¤ŽI dH  | j d¡ |  ¡ I dH }| jduraztj	|| jfi t| jƒ¤ŽI dH  | j d¡ W n tj
y`   | jrV| j d¡ |  dd¡ Y W dS w q
 tjyj   ‚  tys   Y dS  ty„   | jjddd	 Y dS w )
a>  
        Send a Ping frame and wait for a Pong frame at regular intervals.

        This coroutine exits when the connection terminates and one of the
        following happens:

        - :meth:`ping` raises :exc:`ConnectionClosed`, or
        - :meth:`close_connection` cancels :attr:`keepalive_ping_task`.

        NTz% sending keepalive pingz% received keepalive pongz&! timed out waiting for keepalive pongr°   zkeepalive ping timeoutzkeepalive ping failedrØ   )r3   rP   r   r(   r>   r2   rZ   rÒ   r4   rÅ   rÇ   r½   rÈ   r   r¼   rß   )rt   Zpong_waiterrL   rL   ru   r‡   Á  sF   €
ÿþ
þýüéÿz&WebSocketCommonProtocol.keepalive_pingc                 Ã  sP  zžt | dƒrz| jI dH  W n
 tjy   Y nw t | dƒr$| j ¡  | jrFt | dƒrF|  ¡ I dH r=W |  ¡ I dH  dS | j	rF| j
 	d¡ | j ¡ r‚| j ¡ sŒ| j	rY| j
 	d¡ | j ¡  |  ¡ I dH roW |  ¡ I dH  dS | j	r–| j
 	d¡ W |  ¡ I dH  dS W |  ¡ I dH  dS W |  ¡ I dH  dS W |  ¡ I dH  dS |  ¡ I dH  w )a’  
        7.1.1. Close the WebSocket Connection

        When the opening handshake succeeds, :meth:`connection_open` starts
        this coroutine in a task. It waits for the data transfer phase to
        complete then it closes the TCP connection cleanly.

        When the opening handshake fails, :meth:`fail_connection` does the
        same. There's no data transfer phase in that case.

        r†   Nrˆ   ú!! timed out waiting for TCP closezx half-closing TCP connection)Úhasattrr†   rP   rÈ   rˆ   Úcancelr-   Úwait_for_connection_lostÚclose_transportrZ   r2   r}   Zcan_write_eofr~   Ú	write_eofr‹   rL   rL   ru   r‰   ø  s@   €
ÿ

í
úññú"z(WebSocketCommonProtocol.close_connectionc                 Ã  sˆ   | j  ¡ r| j ¡ rdS | jr| j d¡ | j ¡  |  ¡ I dH r$dS | jr-| j d¡ | jr6| j d¡ | j ¡  |  ¡ I dH  dS )z,
        Close the TCP connection.

        Nzx closing TCP connectionrý   zx aborting TCP connection)	rk   rw   r}   r~   rZ   r2   rÉ   r   Úabortr‹   rL   rL   ru   r  +  s   €

z'WebSocketCommonProtocol.close_transportc                 Ã  sZ   | j  ¡ s(ztjt | j ¡| jfi t| jƒ¤ŽI dH  W n
 tjy'   Y nw | j  ¡ S )z¹
        Wait until the TCP connection is closed or ``self.close_timeout`` elapses.

        Return :obj:`True` if the connection is closed and :obj:`False`
        otherwise.

        N)	rk   rw   rP   rÅ   r±   r5   r(   r>   rÇ   r‹   rL   rL   ru   r   J  s   €

þýÿ
z0WebSocketCommonProtocol.wait_for_connection_lostr   c                 C  sª   | j r
| j  d|¡ t| dƒr| j ¡  |dkrC| jtju rCt||ƒ}tj	| _| j r0| j  d¡ | j
du s7J ‚|| _|  dt| ¡ ¡ t| dƒsS| j |  ¡ ¡| _dS dS )a‹  
        7.1.7. Fail the WebSocket Connection

        This requires:

        1. Stopping all processing of incoming data, which means cancelling
           :attr:`transfer_data_task`. The close code will be 1006 unless a
           close frame was received earlier.

        2. Sending a close frame with an appropriate code if the opening
           handshake succeeded and the other side is likely to process it.

        3. Closing the connection. :meth:`close_connection` takes care of
           this once :attr:`transfer_data_task` exits after being canceled.

        (The specification describes these steps in the opposite order.)

        z!! failing connection with code %dr†   r   rû   NTrŠ   )rZ   r2   rþ   r†   rÿ   re   r   rƒ   r    r×   rg   rh   rõ   r   rü   r>   r„   r‰   rŠ   )rt   rž   r¢   rÉ   rL   rL   ru   r½   `  s   




ÿz'WebSocketCommonProtocol.fail_connectionc                 C  s>   | j tju sJ ‚|  ¡ }| j ¡ D ]}| |¡ | ¡  qdS )zŠ
        Raise ConnectionClosed in pending keepalive pings.

        They'll never receive a pong once the connection is closed.

        N)re   r   rš   rÖ   rr   ÚvaluesÚset_exceptionrÿ   )rt   r   rÒ   rL   rL   ru   Úabort_pingsš  s   

úz#WebSocketCommonProtocol.abort_pingsr}   úasyncio.BaseTransportc                 C  s.   t tj|ƒ}| | j¡ || _| j |¡ dS )aØ  
        Configure write buffer limits.

        The high-water limit is defined by ``self.write_limit``.

        The low-water limit currently defaults to ``self.write_limit // 4`` in
        :meth:`~asyncio.WriteTransport.set_write_buffer_limits`, which should
        be all right for reasonable use cases of this library.

        This is the earliest point where we can get hold of the transport,
        which means it's the best point for configuring it.

        N)r   rP   Ú	TransportZset_write_buffer_limitsr9   r}   r_   Zset_transportr—   rL   rL   ru   Úconnection_made®  s   z'WebSocketCommonProtocol.connection_mader   úOptional[Exception]c                 C  s¦   t j| _| j d¡ |  ¡  | j d¡ 	 | jdur*|du r$| j 	¡  n| j 
|¡ | js/dS | j}|du r8dS d| _| ¡ rAdS |du rL| d¡ dS | 
|¡ dS )z=
        7.1.4. The WebSocket Connection is Closed.

        z= connection is CLOSEDN)r   rš   re   r2   rZ   r  rk   r¬   r_   Úfeed_eofr  r`   ra   rw   )rt   r   rz   rL   rL   ru   Úconnection_lostÃ  s(   
z'WebSocketCommonProtocol.connection_lostc                 C  s   | j rJ ‚d| _ d S )NT)r`   r‹   rL   rL   ru   Úpause_writingê  s   

z%WebSocketCommonProtocol.pause_writingc                 C  sB   | j sJ ‚d| _ | j}|d urd | _| ¡ s| d ¡ d S d S d S )NF)r`   ra   rw   r¬   ry   rL   rL   ru   Úresume_writingî  s   
ýz&WebSocketCommonProtocol.resume_writingc                 C  s   | j  |¡ d S rÔ   )r_   Z	feed_datarÑ   rL   rL   ru   Údata_receivedø  s   z%WebSocketCommonProtocol.data_receivedc                 C  s   | j  ¡  dS )aª  
        Close the transport after receiving EOF.

        The WebSocket protocol has its own closing handshake: endpoints close
        the TCP or TLS connection after sending and receiving a close frame.

        As a consequence, they never need to write after receiving EOF, so
        there's no reason to keep the transport open by returning :obj:`True`.

        Besides, that doesn't work on TLS connections.

        N)r_   r  r‹   rL   rL   ru   Úeof_receivedû  s   z$WebSocketCommonProtocol.eof_received)r2   r@   r3   rA   r4   rA   r5   rA   r6   rB   r7   rB   r8   rC   r9   rC   r:   rD   r;   rB   r<   rE   r=   r,   r>   rF   r?   rA   rG   rH   )rG   rH   )rG   rD   )rG   rB   )rG   rE   )rG   r   )rG   r,   )rG   r¤   )rG   r$   )r­   r®   rG   rH   )rÄ   r¡   )rž   rC   r¢   r.   rG   rH   rÔ   )rÂ   rË   rG   rÌ   )r¯   )rÂ   r$   rG   rH   )rG   r   )rG   rË   )r6   rB   rG   rî   )r6   rB   rG   r)   )rä   r,   rÁ   rC   rÂ   r³   rG   rH   )
rä   r,   rÁ   rC   rÂ   r³   rø   rC   rG   rH   )rÉ   r    rÂ   rú   rG   rH   )r   r¡   )r}   r  rG   rH   )r   r
  rG   rH   )rÂ   r³   rG   rH   )3Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú__annotations__r/   rv   r{   r‚   rŒ   Úpropertyr:   r;   r<   r   rŽ   r™   r›   rŸ   r£   r¦   r¥   rÃ   rÉ   rÊ   rÒ   rÓ   rÖ   rª   r…   rÚ   ré   rï   rõ   rö   r   rƒ   r¶   rÆ   r‡   r‰   r  r   r½   r  r	  r  r  r  r  r  rL   rL   rL   ru   r*   ?   s’   
 dï 






O !
98


"
E
J
=


ÿÿ

7
3

:


'


Ú
websocketsú!Iterable[WebSocketCommonProtocol]r­   r$   rG   rH   c                 C  sb   t |ttttfƒstdƒ‚t|ƒ\}}| D ]}|jtj	urq|j
dur'tdƒ‚| d||¡ qdS )ar  
    Broadcast a message to several WebSocket connections.

    A string (:class:`str`) is sent as a Text_ frame. A bytestring or
    bytes-like object (:class:`bytes`, :class:`bytearray`, or
    :class:`memoryview`) is sent as a Binary_ frame.

    .. _Text: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.6
    .. _Binary: https://www.rfc-editor.org/rfc/rfc6455.html#section-5.6

    :func:`broadcast` pushes the message synchronously to all connections even
    if their write buffers are overflowing. There's no backpressure.

    :func:`broadcast` skips silently connections that aren't open in order to
    avoid errors on connections where the closing handshake is in progress.

    If you broadcast messages faster than a connection can handle them,
    messages will pile up in its write buffer until the connection times out.
    Keep low values for ``ping_interval`` and ``ping_timeout`` to prevent
    excessive memory usage by slow connections when you use :func:`broadcast`.

    Unlike :meth:`~websockets.server.WebSocketServerProtocol.send`,
    :func:`broadcast` doesn't support sending fragmented messages. Indeed,
    fragmentation is useful for sending large messages without buffering
    them in memory, while :func:`broadcast` buffers one copy per connection
    as fast as possible.

    Args:
        websockets (Iterable[WebSocketCommonProtocol]): WebSocket connections
            to which the message will be sent.
        message (Data): message to send.

    Raises:
        RuntimeError: if a connection is busy sending a fragmented message.
        TypeError: if ``message`` doesn't have a supported type.

    zdata must be str or bytes-likeNz!busy sending a fragmented messageT)r²   r.   r³   r´   rµ   r·   r#   re   r   rƒ   rq   r§   rõ   )r  r­   rÁ   rÂ   rJ   rL   rL   ru   r+     s   &
ù)r  r  r­   r$   rG   rH   );Ú
__future__r   rP   rê   rl   rT   rÏ   rÍ   rQ   rM   Útypingr   r   r   r   r   r   r	   r
   r   r   r   r   Ú
connectionr   Zdatastructuresr   Ú
exceptionsr   r   r   r   r   r   rf   r   Úframesr   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   Zcompatibilityr(   Zframingr)   Ú__all__ÚProtocolr*   r+   rL   rL   rL   ru   Ú<module>   s@    8 4           W