
    A>qj                    z   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Zd dlZd dlmZmZmZ d dlmZ d dlmZmZmZmZ ddlmZmZmZmZ ddlmZmZm Z m!Z! dd	l"m#Z#m$Z$ dd
l%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+ ddlm,Z,m-Z-m.Z.m/Z/m0Z0 ddl1m2Z2 ddl3m4Z4 dgZ5 G d d      Z6ddd	 	 	 	 	 	 	 	 	 	 	 ddZ7de7_8        y)    )annotationsN)IterableIteratorMapping)TracebackType)AnyLiteralSelfoverload   )ConcurrencyErrorConnectionClosedConnectionClosedOKProtocolError)DATA_OPCODESPONG	CloseCodeFrame)RequestResponse)CLOSED
CONNECTINGOPENEventProtocolState)	BytesLikeDataDataLike
LoggerLikeSubprotocol   )	Assembler)Deadline
Connectionc                  ~   e Zd ZdZdZddddd	 	 	 	 	 	 	 	 	 	 	 	 	 d/dZed0d       Zed0d	       Zed1d
       Z	ed2d       Z
ed3d       Zed4d       Zd5dZ	 	 	 	 	 	 	 	 d6dZd7dZed8d       Zed9d       Zed:d8d       Ze	 d:	 	 	 	 	 d9d       Ze	 d;	 	 	 	 	 d<d       Zd;d<dZed=d       Zed>d       Zed:d?d       Zd:d?dZdd	 	 	 	 	 d@dZej*                  df	 	 	 	 	 dAdZ	 d:d d!	 	 	 	 	 dBd"ZdCdDd#ZdEd$ZdFd%ZdGd&ZdGd'ZdGd(ZdGd)Zej@                  e!d*	 	 	 dHd+       Z"dGd,Z#dId-Z$dGd.Z%y)Jr%   a?  
    :mod:`threading` implementation of a WebSocket connection.

    :class:`Connection` provides APIs shared between WebSocket servers and
    clients.

    You shouldn't use it directly. Instead, use
    :class:`~websockets.sync.client.ClientConnection` or
    :class:`~websockets.sync.server.ServerConnection`.

    i      
      )ping_intervalping_timeoutclose_timeout	max_queuec               p   || _         || _        || _        || _        || _        t        |t              s||d }}n|\  }}t        j                  | j                  j                  d| i      | j                  _	        | j                  j                  | _
        	 | j                  j                  | _	        	 | j                  j                  | _        d | _        	 d | _        	 t        j                         | _        t        j                         | _        t%        ||| j"                  j&                  | j"                  j(                        | _        d | _        d| _        i | _        d| _        	 d | _        d | _        t        j8                  | j:                  d      | _        | j<                  j?                          y )N	websocket)pauseresumeFg        Ttargetdaemon) socketprotocolr*   r+   r,   
isinstanceintloggingLoggerAdapterloggeriddebugrequestresponse	threadingLockprotocol_mutexrecv_flow_controlr#   acquirereleaserecv_messagesclose_deadlinesend_in_progresspending_pingslatencykeepalive_threadrecv_excThreadrecv_eventsrecv_events_threadstart)	selfsockr6   r*   r+   r,   r-   max_queue_highmax_queue_lows	            Y/opt/rentech/trading_bot/.venv/lib/python3.12/site-packages/websockets/sync/connection.py__init__zConnection.__init__1   s     *(*i%):,5tMN,5)NM  '44MM  $ 
 "]]--B"&--"6"6)]]((
 (,()-) (nn. "+!1 '((00))11	
 04 !& PR!
	 :> /3
 #,"2"2###
 	%%'    c                6    | j                   j                         S )z
        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`.

        )r5   getsocknamerQ   s    rU   local_addresszConnection.local_address        {{&&((rW   c                6    | j                   j                         S )z
        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`.

        )r5   getpeernamerZ   s    rU   remote_addresszConnection.remote_address   r\   rW   c                .    | j                   j                  S )aI  
        State of the WebSocket connection, defined in :rfc:`6455`.

        This attribute is provided for completeness. Typical applications
        shouldn't check its value. Instead, they should call :meth:`~recv` or
        :meth:`send` and handle :exc:`~websockets.exceptions.ConnectionClosed`
        exceptions.

        )r6   staterZ   s    rU   ra   zConnection.state   s     }}"""rW   c                .    | j                   j                  S )z~
        Subprotocol negotiated during the opening handshake.

        :obj:`None` if no subprotocol was negotiated.

        )r6   subprotocolrZ   s    rU   rc   zConnection.subprotocol   s     }}(((rW   c                .    | j                   j                  S a)  
        State of the WebSocket connection, defined in :rfc:`6455`.

        This attribute is provided for completeness. Typical applications
        shouldn't check its value. Instead, they should inspect attributes
        of :exc:`~websockets.exceptions.ConnectionClosed` exceptions.

        )r6   
close_coderZ   s    rU   rf   zConnection.close_code   s     }}'''rW   c                .    | j                   j                  S re   )r6   close_reasonrZ   s    rU   rh   zConnection.close_reason   s     }})))rW   c                    | S N rZ   s    rU   	__enter__zConnection.__enter__   s    rW   c                h    || j                          y | j                  t        j                         y rj   )closer   INTERNAL_ERROR)rQ   exc_type	exc_value	tracebacks       rU   __exit__zConnection.__exit__   s%     JJLJJy//0rW   c              #  R   K   	 	 | j                          # t        $ r Y yw xY ww)aC  
        Iterate on incoming messages.

        The iterator calls :meth:`recv` and yields messages in an infinite loop.

        It exits when the connection is closed normally. It raises a
        :exc:`~websockets.exceptions.ConnectionClosedError` exception after a
        protocol error or a network failure.

        N)recvr   rZ   s    rU   __iter__zConnection.__iter__   s0     	iik! ! 		s   ' 	$'$'c                     y rj   rk   rQ   timeoutdecodes      rU   ru   zConnection.recv       ILrW   c                     y rj   rk   rx   s      rU   ru   zConnection.recv       LOrW   Nc                    y rj   rk   rx   s      rU   ru   zConnection.recv  s    SVrW   c                    y rj   rk   rx   s      rU   ru   zConnection.recv  s     rW   c                     y rj   rk   rx   s      rU   ru   zConnection.recv  s     rW   c                   	 | j                   j                  ||      S # t        $ r Y nt        $ r t        d      dt        $ rs}| j                         5  | j                  j                  t        j                  |j                   d|j                          ddd       n# 1 sw Y   nxY wY d}~nd}~ww xY w| j                  j                          | j                  j                  | j                  )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 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.

        If ``timeout`` is :obj:`None`, block until a message is received. If
        ``timeout`` is set, wait up to ``timeout`` seconds for a message to be
        received and return it, else raise :exc:`TimeoutError`. If ``timeout``
        is ``0`` or negative, check if a message has been received already and
        return it, else raise :exc:`TimeoutError`.

        When the message is fragmented, :meth:`recv` waits until all fragments
        are received, reassembles them, and returns the whole message.

        Args:
            timeout: Timeout for receiving a message in seconds.
            decode: Set this flag to override the default behavior of returning
                :class:`str` or :class:`bytes`. See below for details.

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

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

            You may override this behavior with the ``decode`` argument:

            * Set ``decode=False`` to disable UTF-8 decoding of Text_ frames and
              return a bytestring (:class:`bytes`). This improves performance
              when decoding isn't needed, for example if the message contains
              JSON and you're using a JSON library that expects a bytestring.
            * Set ``decode=True`` to force UTF-8 decoding of Binary_ frames and
              return strings (:class:`str`). This may be useful for servers that
              send binary frames instead of text frames.

        Raises:
            ConnectionClosed: When the connection is closed.
            ConcurrencyError: If two threads call :meth:`recv` or
                :meth:`recv_streaming` concurrently.

        zOcannot call recv while another thread is already running recv or recv_streamingN at position )rF   getEOFErrorr   UnicodeDecodeErrorsend_contextr6   failr   INVALID_DATAreasonrP   rO   join	close_excrL   )rQ   ry   rz   excs       rU   ru   zConnection.recv  s    `	%%))'6:: 	 	"<  " 	""$ ""**zzl-		{;  	 	$$&mm%%4==8s3    	B8B8B3AB"	B3"B+	'B33B8c                     y rj   rk   rQ   rz   s     rU   recv_streamingzConnection.recv_streamingV  s    FIrW   c                     y rj   rk   r   s     rU   r   zConnection.recv_streamingY  r{   rW   c                     y rj   rk   r   s     rU   r   zConnection.recv_streaming\  r}   rW   c              #    K   	 | j                   j                  |      E d{    y7 # t        $ r Y nt        $ r t        d      dt        $ rs}| j                         5  | j                  j                  t        j                  |j                   d|j                          ddd       n# 1 sw Y   nxY wY d}~nd}~ww xY w| j                  j                          | j                  j                  | j                  w)a  
        Receive the next message frame by frame.

        This method is designed for receiving fragmented messages. It returns an
        iterator that yields each fragment as it is received. This iterator must
        be fully consumed. Else, future calls to :meth:`recv` or
        :meth:`recv_streaming` will raise
        :exc:`~websockets.exceptions.ConcurrencyError`, making the connection
        unusable.

        :meth:`recv_streaming` raises the same exceptions as :meth:`recv`.

        Args:
            decode: Set this flag to override the default behavior of returning
                :class:`str` or :class:`bytes`. See below for details.

        Returns:
            An iterator of strings (:class:`str`) for a Text_ frame or
            bytestrings (:class:`bytes`) for a Binary_ frame.

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

            You may override this behavior with the ``decode`` argument:

            * Set ``decode=False`` to disable UTF-8 decoding of Text_ frames and
              yield bytestrings (:class:`bytes`). This improves performance
              when decoding isn't needed.
            * Set ``decode=True`` to force UTF-8 decoding of Binary_ frames and
              yield strings (:class:`str`). This may be useful for servers that
              send binary frames instead of text frames.

        Raises:
            ConnectionClosed: When the connection is closed.
            ConcurrencyError: If two threads call :meth:`recv` or
                :meth:`recv_streaming` concurrently.

        NzYcannot call recv_streaming while another thread is already running recv or recv_streamingr   )rF   get_iterr   r   r   r   r6   r   r   r   r   rP   rO   r   r   rL   )rQ   rz   r   s      rU   r   zConnection.recv_streaming_  s     N	))226::: ; 	 	"<  " 	""$ ""**zzl-		{;  	 	$$&mm%%4==8sZ   D* (* D* 	CDCB?!AB.%	B?.B7	3B?:D?C>D)textc                  t        |t              r| j                         5  | j                  rt	        d      |du r*| j
                  j                  |j                                n)| j
                  j                  |j                                ddd       yt        |t              rl| j                         5  | j                  rt	        d      |du r| j
                  j                  |       n| j
                  j                  |       ddd       yt        |t              rt        d      t        |t              r]t        |      }	 t        |      }	 t        |t              r| j                         5  | j                  rt	        d      d| _        |du r,| j
                  j                  |j                         d       n+| j
                  j                  |j                         d       ddd       d}nt        |t              ry| j                         5  | j                  rt	        d      d| _        |du r| j
                  j                  |d       n| j
                  j                  |d       ddd       d}nt        d      |D ]  }t        |t              rU|rS| j                         5  | j                  sJ | j
                  j!                  |j                         d       ddd       ht        |t              rG|sE| j                         5  | j                  sJ | j
                  j!                  |d       ddd       t        d       | j                         5  | j
                  j!                  d	d       d| _        ddd       yyt        d      # 1 sw Y   yxY w# 1 sw Y   yxY w# t        $ r Y yw xY w# 1 sw Y   xY w# 1 sw Y   cxY w# 1 sw Y   `xY w# 1 sw Y   mxY w# 1 sw Y   pxY w# t        $ r  t"        $ rQ | j                         5  | j
                  j%                  t&        j(                  d
       ddd        # 1 sw Y    xY ww xY w)aF	  
        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://datatracker.ietf.org/doc/html/rfc6455#section-5.6
        .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6

        You may override this behavior with the ``text`` argument:

        * Set ``text=True`` to send an UTF-8 bytestring or bytes-like object
          (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) in a
          Text_ frame. This improves performance when the message is already
          UTF-8 encoded, for example if the message contains JSON and you're
          using a JSON library that produces a bytestring.
        * Set ``text=False`` to send a string (:class:`str`) in a Binary_
          frame. This may be useful for servers that expect binary frames
          instead of text frames.

        :meth:`send` also accepts an 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://datatracker.ietf.org/doc/html/rfc6455#section-5.4

        :meth:`send` rejects dict-like objects because this is often an error.
        (If you really 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`.)

        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: Message to send.
            text: Force sending in a Text_ or Binary_ frame.

        Raises:
            ConnectionClosed: When the connection is closed.
            ConcurrencyError: If the connection is sending a fragmented message.
            TypeError: If ``message`` doesn't have a supported type.

        z=cannot call send while another thread is already running sendFNTzdata is a dict-like object)finz"iterable must contain bytes or strz#iterable must contain uniform typesrW   zerror in fragmented messagez$data must be str, bytes, or iterable)r7   strr   rH   r   r6   send_binaryencode	send_textr   r   	TypeErrorr   iternextStopIterationsend_continuation	Exceptionr   r   ro   )rQ   messager   chunkschunkr   s         rU   sendzConnection.send  s)   v gs#""$ >((*W  5=MM--gnn.>?MM++GNN,<=> > +""$ 7((*W  4<MM++G4MM--g67 7 )899 *']FV>eS)**, 
O00"2!:#  15-5= MM55elln%5P MM33ELLN3N
O "Fy1**, 
H00"2!:#  15-4< MM33Eu3E MM55e5G
H #F#$HII $ 
OE!%-&!..0 W#'#8#88#8 MM;;ELLNPU;VW W $E95f!..0 N#'#8#88#8 MM;;Eu;MN N ((MNN
O &&( 2MM33CT3B,1D)2 2( BCCI> >7 7* ! 
O 
O
H 
H$W WN N2 2 $    &&( MM&&!005
 
 s   A/N)9AN5O  P 9A:O3+P AO<=P 9:O*3+P ,O7
%P /%PP )N25N>	OOOP O'"P *O4	/P 7P	<P P	P "Q32+Q&	Q3&Q/	+Q3 c                   	 | j                         5  | j                  r+| j                  j                  t        j
                  d       n| j                  j                  ||       ddd       y# 1 sw Y   yxY w# t        $ r Y yw xY w)ar  
        Perform the closing handshake.

        :meth:`close` waits for the other end to complete the handshake and
        for the TCP connection to terminate.

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

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

        zclose during fragmented messageN)r   rH   r6   r   r   ro   
send_closer   )rQ   coder   s      rU   rn   zConnection.close?  s|    &	 ""$ ;((MM&&!009
 MM,,T6:; ; ;   	 	s/   A; AA/&A; /A84A; 8A; ;	BBFack_on_closec               X   t        |t              rt        |      }n.t        |t              r|j	                         }n|t        d      | j                         5  || j                  v rt        d      ||| j                  v r;t        j                  dt        j                  d            }|,|| j                  v r;t        j                         }t        j                          }|||f| j                  |<   | j"                  j%                  |       |cddd       S # 1 sw Y   yxY w)a[  
        Send a Ping_.

        .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#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

        Args:
            data: Payload of the ping. A :class:`str` will be encoded to UTF-8.
                If ``data`` is :obj:`None`, the payload is four random bytes.
            ack_on_close: when this option is :obj:`True`, the event will also
                be set when the connection is closed. While this avoids getting
                stuck waiting for a pong that will never arrive, it requires
                checking that the state of the connection is still ``OPEN`` to
                confirm that a pong was received, rather than the connection
                being closed.

        Returns:
            An event that will be set when the corresponding pong is received.
            You can ignore it if you don't intend to wait.

            ::

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

        Raises:
            ConnectionClosed: When the connection is closed.
            ConcurrencyError: If another ping was sent with the same data and
                the corresponding pong wasn't received yet.

        Ndata must be str or bytes-likez-already waiting for a pong with the same dataz!I    )r7   r   bytesr   r   r   r   rI   r   structpackrandomgetrandbitsr@   r   time	monotonicr6   	send_ping)rQ   datar   pong_receivedping_timestamps        rU   pingzConnection.pingb  s   P dI&;Dc";;=D<==  	!t)))&'VWW ,$$*<*<"<{{4););B)?@ ,$$*<*<"< &OO-M!^^-N(5~|'TDt$MM##D) 	! 	! 	!s   AD 1D  AD  D)c                   t        |t              rt        |      }n,t        |t              r|j	                         }nt        d      | j                         5  | j                  j                  |       ddd       y# 1 sw Y   yxY w)ab  
        Send a Pong_.

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

        An unsolicited pong may serve as a unidirectional heartbeat.

        Args:
            data: Payload of the pong. A :class:`str` will be encoded to UTF-8.

        Raises:
            ConnectionClosed: When the connection is closed.

        r   N)	r7   r   r   r   r   r   r   r6   	send_pongrQ   r   s     rU   pongzConnection.pong  sk     dI&;Dc";;=D<==  	*MM##D)	* 	* 	*s   A>>Bc                    t        |t              sJ |j                  t        v r| j                  j                  |       |j                  t        u r%| j                  t        |j                               yy)zx
        Process one incoming event.

        This method is overridden in subclasses to handle the handshake.

        N)
r7   r   opcoder   rF   putr   acknowledge_pingsr   r   )rQ   events     rU   process_eventzConnection.process_event  s\     %'''<<<'""5)<<4""5#45  rW   c                   | j                   5  || j                  vr
	 ddd       yt        j                         }d}g }| j                  j	                         D ];  \  }\  }}}|j                  |       |j                          ||k(  s1||z
  | _         n t        d      |D ]  }| j                  |=  	 ddd       y# 1 sw Y   yxY w)z;
        Acknowledge pings when receiving a pong.

        Nz!solicited pong not found in pings)	rB   rI   r   r   itemsappendsetrJ   AssertionError)rQ   r   pong_timestampping_idping_idsr   r   _ack_on_closes           rU   r   zConnection.acknowledge_pings  s    
    	04---	0 	0
 "^^-N GH
 ##))+	J  (!!#d?#1N#BDLJ %%HII $ 0&&w/03	0 	0 	0s   B?A"B?	,B??Cc                   | j                   j                         sJ | j                  j                  t        u sJ | j
                  j                         D ]  \  }}}|s
|j                           | j
                  j                          y)zK
        Acknowledge pending pings when the connection is closed.

        N)	rB   lockedr6   ra   r   rI   valuesr   clear)rQ   r   _ping_timestampr   s       rU   terminate_pending_pingsz"Connection.terminate_pending_pings  s|    
 ""))+++}}""f,,,<@<N<N<U<U<W 	$8M?L!!#	$ 	  "rW   c                6   | j                   J 	 	 | j                  j                  | j                   | j                  z
         | j                  j	                         sy	 | j                  d      }| j                  r| j                  j                  d       | j                  |j                  | j                        r(| j                  r| j                  j                  d       nk| j                  r| j                  j                  d       | j                         5  | j                  j                  t        j                  d       ddd       yC# t        $ r Y yw xY w# 1 sw Y   xY w# t         $ r  | j                  j#                  dd	       Y yw xY w)
zT
        Send a Ping frame and wait for a Pong frame at regular intervals.

        NTr   z% sent keepalive pingz% received keepalive pongz&- timed out waiting for keepalive pongzkeepalive ping timeoutzkeepalive ping failedexc_info)r*   rO   r   rJ   is_aliver   r   r=   r;   r+   waitr   r6   r   r   ro   r   error)rQ   r   s     rU   	keepalivezConnection.keepalive  se   
 !!---	F '',,T-?-?$,,-NO..779$(II4I$@M ::KK%%&=>$$0$))$*;*;<:: KK--.IJ:: KK--.VW!..0  MM.. ) 8 8 8
 7  (    	FKK5E	FsU   AE/ E 1B-E/ +E#	E/ E/ 	E E/ E  E/ #E,(E/ /&FFc                    | j                   At        j                  | j                  d      | _        | j                  j                          yy)zS
        Run :meth:`keepalive` in a thread, unless keepalive is disabled.

        NTr2   )r*   r@   rM   r   rK   rP   rZ   s    rU   start_keepalivezConnection.start_keepalive  sF    
 )$-$4$4~~%D! !!'') *rW   c                   d}	 |sV	 | j                   5  	 ddd       | j                  3| j                  j                  | j                  j	                                | j                  j                  | j                        }|dk(  rn| j                  5  | j                  j                  |       | j                  j                         }	 | j                          | j                  j!                         rD| j                  t#        | j$                        | _        | j                  j&                  t(        u rd}ddd       D ]  }| j+                  |        |sV| j                  5  | j                  j-                          | j                  j                         }| j                          ddd       D ]  }| j+                  |        	 | j1                          y# 1 sw Y   xY w# t        $ rf}| j                  r| j                  j                  dd       | j                  5  | j                  |       ddd       n# 1 sw Y   nxY wY d}~d}~ww xY w# t        $ rM}| j                  r| j                  j                  dd       | j                  |       Y d}~ddd       Sd}~ww xY w# 1 sw Y   xY w# 1 sw Y   xY w# t        $ r[}| j                  j/                  dd       | j                  5  | j                  |       ddd       n# 1 sw Y   nxY wY d}~bd}~ww xY w# | j1                          w xY w)	z
        Read incoming data from the socket and process events.

        Run this method in a thread as long as the connection is alive.

        ``recv_events()`` exits immediately when ``self.socket`` is closed.

        FNz! error while receiving dataTr   rW   ! error while sending dataunexpected internal error)rC   rG   r5   
settimeoutry   ru   recv_bufsizer   r=   r;   rB   set_recv_excr6   receive_dataevents_received	send_dataclose_expectedr$   r,   ra   r   r   receive_eofr   close_socket)rQ   close_expected_while_connectingr   r   eventsr   s         rU   rN   zConnection.recv_events+  s   $ +0'b	 5// **6..t/B/B/J/J/LM;;++D,=,=>D 3; (( CMM..t4 "]]::<F( }}335..62:4;M;M2ND/==..*<>B;9CJ $ .E&&u-. 6L $$ 	!))+ 668  	!    *""5)* } 
 ! zz)):%) *  ,, /))#./ / /8 % :: KK-- <)- .  ))#.+C CC CX	! 	!(  	'KK9DI$$ '!!#&' ' '	' s  K G- G A,G- K 6J8IAJ89"K K )AK. K L9  G*%G- -	I65I+I=	II	IK IK 	J5(:J0"J8&
K 0J55J88K=K K
K 	L6)L1L	L1L(	$L1+L9 1L66L9 9M)expected_statec             #    K   d}d}d}| j                   5  | j                  j                  |u r[	 d | j                  j                         r*d}| j                  J t        | j                        | _        	 | j                          n*d}| j                  t        | j                        | _        d}ddd       |r| j                  J | j                  j                  d      }| j                  j!                  |       | j                  j#                         r7|J t%        d      }d}| j                   5  | j'                  |       ddd       |rA| j)                          | j                  j!                          | j                  j*                  |y# t        $ r:}| j                  r| j                  j                  dd       d}d}|}Y d}~"d}~ww xY w# t        t        f$ r  t        $ r.}| j                  j                  dd       d}d}|}Y d}~kd}~ww xY w# 1 sw Y   uxY w# 1 sw Y   xY ww)	a  
        Create a context for writing to the connection from user code.

        On entry, :meth:`send_context` acquires the connection lock and checks
        that the connection is open; on exit, it writes outgoing data to the
        socket and releases the connection lock::

            with self.send_context():
                self.protocol.send_text(message.encode())

        When the connection isn't open on entry, when the connection is expected
        to close on exit, or when an unexpected error happens, terminating the
        connection, :meth:`send_context` waits until the connection is closed
        then raises :exc:`~websockets.exceptions.ConnectionClosed`.

        FNTr   r   r   )raise_if_elapsedz"timed out while closing connection)rB   r6   ra   r   rG   r$   r,   r   r   r=   r;   r   r   r   ry   rO   r   r   TimeoutErrorr   r   r   )rQ   r   wait_for_closeraise_close_excoriginal_excr   ry   s          rU   r   zConnection.send_context  s:    . -1    0	'}}""n4$+ }}335)-
  $22:::.6t7I7I.J++(  "&&&.*243E3E*FD'"&a0	'n &&222))1151IG##((1&&//1 $++++,PQ #'(( 4%%l34
 ##((*--))|;	 Y % 
+:: KK-- <)- .  */*.'*
+1 &'78   'KK%%&AD%Q &+N&*O#&L'0	' 0	'H4 4s   H?H&GAH&8F+H&3BH?9H3AH?	G /GH&GH&H#5#HH&H##H&&H0+H?3H<8H?c                   | j                   j                         sJ | j                  j                         D ]  }|r[| j                  3| j
                  j                  | j                  j                                | j
                  j                  |       `	 | j
                  j                  t
        j                          y# t        $ r Y w xY w)z\
        Send outgoing data.

        This method requires holding protocol_mutex.

        N)rB   r   r6   data_to_sendrG   r5   r   ry   sendallshutdownSHUT_WROSErrorr   s     rU   r   zConnection.send_data  s     ""))+++MM..0 		D&&2KK**4+>+>+F+F+HI##D)KK((8		  s   )C	CCc                d    | j                   j                         sJ | j                  || _        yy)z
        Set recv_exc, if not set yet.

        This method requires holding protocol_mutex and must be called only from
        the thread running recv_events().

        N)rB   r   rL   )rQ   r   s     rU   r   zConnection.set_recv_exc#  s2     ""))+++== DM !rW   c                   	 | j                   j                  t         j                         	 | j                   j	                          | j
                  5  | j                  j                          | j                  j                  t        u sJ | j                  j	                          | j                          ddd       y# t        $ r Y w xY w# t        $ r Y w xY w# 1 sw Y   yxY w)z
        Shutdown and close socket. Close message assembler.

        Calling close_socket() guarantees that recv_events() terminates. Indeed,
        recv_events() may block only on socket.recv() or on recv_messages.put().

        N)r5   r   	SHUT_RDWRr   rn   rB   r6   r   ra   r   rF   r   rZ   s    rU   r   zConnection.close_socket/  s    	KK  !1!12	KK    	+MM%%'==&&&000 $$& ((*	+ 	+  		  	 		+ 	+s/   )B> C A#C>	C
	C
	CCC%)rR   zsocket.socketr6   r   r*   float | Noner+   r   r,   r   r-   z*int | None | tuple[int | None, int | None]returnNone)r   r   )r   r   )r   zSubprotocol | None)r   z
int | None)r   z
str | None)r   r
   )rp   ztype[BaseException] | Nonerq   BaseException | Nonerr   zTracebackType | Noner   r   )r   Iterator[Data])ry   r   rz   Literal[True]r   r   )ry   r   rz   Literal[False]r   r   rj   )NN)ry   r   rz   bool | Noner   r   )rz   r   r   zIterator[str])rz   r   r   zIterator[bytes])rz   r  r   r   )r   zDataLike | Iterable[DataLike]r   r  r   r   )r   zCloseCode | intr   r   r   r   )r   zDataLike | Noner   boolr   zthreading.Event)rW   )r   r   r   r   )r   r   r   r   )r   r   r   r   )r   r   )r   r   r   zIterator[None])r   r   r   r   )&__name__
__module____qualname____doc__r   rV   propertyr[   r_   ra   rc   rf   rh   rl   rs   rv   r   ru   r   r   r   NORMAL_CLOSURErn   r   r   r   r   r   r   r   rN   
contextlibcontextmanagerr   r   r   r   r   rk   rW   rU   r%   r%   "   s   
 L ')%'&(@B[([( [(
 $[( #[( $[( >[( 
[(~ 
) 
) 
) 
) 
# 
# ) ) 	( 	( 	* 	*	1,	1 (	1 (		1
 
	1( L LO OV V&*#7E	  BF#4?	 D9L I IL LO O<9D !	`D.`D 	`D
 
`DH !* 8 8!! ! 
	!J !%<! #	<!<! 	<!
 
<!|*660B#$FL*v p  !%j< j< 
	j< j<X&
 +rW   F)raise_exceptionsr   c               n   t        t              r|du rdndj                         n$t        t              r	|du rdndnt	        d      rg d	fd}t        j                  j                  d
i |5 }|j                  ||        ddd       rrt        d      yy# 1 sw Y   xY w)a
  
    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://datatracker.ietf.org/doc/html/rfc6455#section-5.6
    .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6

    You may override this behavior with the ``text`` argument:

    * Set ``text=True`` to send an UTF-8 bytestring or bytes-like object
      (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) in a
      Text_ frame. This improves performance when the message is already
      UTF-8 encoded, for example if the message contains JSON and you're
      using a JSON library that produces a bytestring.
    * Set ``text=False`` to send a string (:class:`str`) in a Binary_
      frame. This may be useful for servers that expect binary frames
      instead of text frames.

    :func:`broadcast` relies on :class:`concurrent.futures.ThreadPoolExecutor`
    to send the messages. Make sure the thread pool is large enough relative to
    the number of clients, so that slow or stuck connections don't clog it. If
    that's an issue, then you should be using an asynchronous implementation.
    You can configure the thread pool by passing additional keyword arguments to
    :func:`broadcast`, such as ``max_workers``.

    Unlike :meth:`~websockets.asyncio.connection.Connection.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.

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

    :func:`broadcast` ignores failures to write the message on some connections.
    It continues writing to other connections. You may set ``raise_exceptions``
    to :obj:`True` to record failures and raise all exceptions in a :pep:`654`
    :exc:`ExceptionGroup`.

    While :func:`broadcast` makes more sense for servers, it works identically
    with clients, if you have a use case for opening connections to many servers
    and broadcasting a message to them.

    Args:
        websockets: WebSocket connections to which the message will be sent.
        message: Message to send.
        raise_exceptions: Whether to raise an exception in case of failures.
        text: Force sending in Text_ or Binary_ frames.

    Raises:
        TypeError: If ``message`` doesn't have a supported type.

    Fr   r   Tzdata must be str or bytesc                   | j                   5  | j                  j                  t        ur
	 d d d        y | j                  rDrt        d      }j                  |       n| j                  j                  d       	 d d d        y 	  t        | j                               | j                          d d d        y # t        $ rp}r$t        d      }||_        j                  |       n@| j                  j                  dt        j                  |      d   j!                                Y d }~}d }~ww xY w# 1 sw Y   y xY w)Nzsending a fragmented messagez/skipped broadcast: sending a fragmented messagezfailed to write messagez.skipped broadcast: failed to write message: %sr   )rB   r6   ra   r   rH   r   r   r;   warninggetattrr   r   RuntimeError	__cause__rr   format_exception_onlystrip)
connection	exceptionwrite_exception
exceptionsr   r  send_methods      rU   send_messagezbroadcast.<locals>.send_message  s*    && 	""((4	 	 **# 01O PI%%i0%%--I 	 	 :
++[9'B$$&%	 	&  	# ,-F GI*9I'%%i0%%--H!77HKQQS	'	 	s6   D7AD7,B;;	D4A&D/*D7/D44D77E Nzskipped broadcast)r  r%   r   r   rk   )
r7   r   r   r   r   
concurrentfuturesThreadPoolExecutormapExceptionGroup)	connectionsr   r  r   kwargsr  executorr  r  s	    ``    @@rU   	broadcastr"  V  s    @ '3'+u}m+.."	GY	'%)T\k}344&(
 B 
			.	.	8	8 0H\;/0 J0*== '0 0s   >B++B4zwebsockets.sync.server)r  zIterable[Connection]r   r   r  r  r   r  r   r   r   r   )9
__future__r   concurrent.futuresr  r	  r9   r   r5   r   r@   r   rr   uuidcollections.abcr   r   r   typesr   typingr   r	   r
   r   r  r   r   r   r   framesr   r   r   r   http11r   r   r6   r   r   r   r   r   r   r   r   r   r    r!   messagesr#   utilsr$   __all__r%   r"  r  rk   rW   rU   <module>r.     s    "           7 7  / /  : 9 & G G G G   .k+ k+p! #p>%p>p> 	p>
 p> p> 
p>h 0	 rW   