
    ,hf                    *   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 d dlmZ d dl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mZ dd	lm Z m!Z! dd
l"m#Z#m$Z$m%Z%m&Z&m'Z' ddlm(Z(m)Z)m*Z* ddl+m,Z, ddl-m.Z. dgZ/ G d d      Z0y)    )annotationsN)IterableIteratorMapping)TracebackType)AnyLiteraloverload   )ConcurrencyErrorConnectionClosedConnectionClosedOKProtocolError)DATA_OPCODES	BytesLike	CloseCodeFrameOpcode)RequestResponse)CLOSEDOPENEventProtocolState)Data
LoggerLikeSubprotocol   )	Assembler)Deadline
Connectionc                  n   e Zd ZdZdZddddd	 	 	 	 	 	 	 	 	 	 	 	 	 d,dZed-d       Zed-d	       Zed.d
       Z	ed/d       Z
ed0d       Zed1d       Zd2dZ	 	 	 	 	 	 	 	 d3dZd4dZed5d       Zed6d       Zed7d5d       Ze	 d7	 	 	 	 	 d6d       Ze	 d8	 	 	 	 	 d9d       Zd8d9dZed:d       Zed;d       Zed7d<d       Zd7d<dZ	 d7	 	 	 	 	 d=dZej*                  dfd>dZ	 	 d?	 	 	 	 	 d@dZdAdBd ZdCd!ZdDd"ZdEd#ZdEd$ZdEd%ZdEd&Zej@                  e!d'	 	 	 dFd(       Z"dEd)Z#dGd*Z$dEd+Z%y)Hr"   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                  || _         || _        || _        || _        || _        t        |t              s||d f}|| _        t        j                  | j                  j                  d| i      | j                  _
        | j                  j                  | _        	 | j                  j                  | _
        	 | j                  j                  | _        d | _        	 d | _        	 t        j                          | _        t        j                          | _        t'        | j                  | j$                  j(                  | j$                  j*                  d| _        d | _        d| _        i | _        d| _        	 d | _        d | _        t        j:                  | j<                  d      | _        | j>                  jA                          y )N	websocket)pauseresumeFr   Ttargetdaemon)!socketprotocolr'   r(   r)   
isinstanceintr*   loggingLoggerAdapterloggeriddebugrequestresponse	threadingLockprotocol_mutexrecv_flow_controlr    acquirereleaserecv_messagesclose_deadlinesend_in_progresspong_waiterslatencykeepalive_threadrecv_excThreadrecv_eventsrecv_events_threadstart)selfr2   r3   r'   r(   r)   r*   s          \/var/www/html/Resume-Scraper/venv/lib/python3.12/site-packages/websockets/sync/connection.py__init__zConnection.__init__/   s     *(*i%):"D)I"  '44MM  $ 
 "]]--B"&--"6"6)]]((
 (,()-) (nn. "+!1 '^^((00))11
 04 !& OQ
	 :> /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`.

        )r2   getsocknamerN   s    rO   local_addresszConnection.local_address        {{&&((rQ   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`.

        )r2   getpeernamerT   s    rO   remote_addresszConnection.remote_address   rV   rQ   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.

        )r3   staterT   s    rO   r[   zConnection.state   s     }}"""rQ   c                .    | j                   j                  S )z~
        Subprotocol negotiated during the opening handshake.

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

        )r3   subprotocolrT   s    rO   r]   zConnection.subprotocol   s     }}(((rQ   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.

        )r3   
close_coderT   s    rO   r`   zConnection.close_code   s     }}'''rQ   c                .    | j                   j                  S r_   )r3   close_reasonrT   s    rO   rb   zConnection.close_reason   s     }})))rQ   c                    | S N rT   s    rO   	__enter__zConnection.__enter__   s    rQ   c                h    || j                          y | j                  t        j                         y rd   )closer   INTERNAL_ERROR)rN   exc_type	exc_value	tracebacks       rO   __exit__zConnection.__exit__   s%     JJLJJy//0rQ   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   rT   s    rO   __iter__zConnection.__iter__   s0     	iik! ! 		s   ' 	$'$'c                     y rd   re   rN   timeoutdecodes      rO   ro   zConnection.recv       ILrQ   c                     y rd   re   rr   s      rO   ro   zConnection.recv       LOrQ   Nc                    y rd   re   rr   s      rO   ro   zConnection.recv   s    SVrQ   c                    y rd   re   rr   s      rO   ro   zConnection.recv  s     rQ   c                     y rd   re   rr   s      rO   ro   zConnection.recv  s     rQ   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`.

        If the message is fragmented, wait until all fragments are received,
        reassemble them, and return 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 a string (: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 )rC   getEOFErrorr   UnicodeDecodeErrorsend_contextr3   failr   INVALID_DATAreasonrM   rL   join	close_excrI   )rN   rs   rt   excs       rO   ro   zConnection.recv  s    `	%%))'6:: 	 	"<  " 	""$ ""**zzl-		{;  	 	$$&mm%%4==8s3    	B8B8B3AB"	B3"B+	'B33B8c                     y rd   re   rN   rt   s     rO   recv_streamingzConnection.recv_streamingR  s    FIrQ   c                     y rd   re   r   s     rO   r   zConnection.recv_streamingU  ru   rQ   c                     y rd   re   r   s     rO   r   zConnection.recv_streamingX  rw   rQ   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 return bytestrings (:class:`bytes`). This may be useful to
              optimize performance when decoding isn't needed.
            * Set ``decode=True`` to force UTF-8 decoding of Binary_ frames
              and return strings (:class:`str`). This is 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|   )rC   get_iterr~   r   r   r   r3   r   r   r   r   rM   rL   r   r   rI   )rN   rt   r   s      rO   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c                   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)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://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 a bytestring or bytes-like object
          (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) as 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.

        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'data iterable must contain bytes or strz(data iterable must contain uniform typesrQ   zerror in fragmented messagez$data must be str, bytes, or iterable)r4   strr   rE   r   r3   send_binaryencode	send_textr   r   	TypeErrorr   iternextStopIterationsend_continuation	Exceptionr   r   ri   )rN   messagetextchunkschunkr   s         rO   sendzConnection.send  s#   r 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#$MNN $ 
TE!%-&!..0 W#'#8#88 MM;;ELLNPU;VW W $E95f!..0 N#'#8#88 MM;;Eu;MN N ((RSS
T &&( 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)a  
        Perform the closing handshake.

        :meth:`close` waits for the other end to complete the handshake, for the
        TCP connection to terminate, and for all incoming messages to be read
        with :meth:`recv`.

        :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   rE   r3   r   r   ri   
send_closer   )rN   coder   s      rO   rh   zConnection.close9  s|     	 ""$ ;((MM&&!009
 MM,,T6:; ; ;   	 	s/   A; AA/&A; /A84A; 8A; ;	BBc                T   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)a8  
        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_event = ws.ping()
                pong_event.wait()  # only if you want to wait for the pong

        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    )r4   r   bytesr   r   r   r   rF   r   structpackrandomgetrandbitsr=   r   time	monotonicr3   	send_ping)rN   dataack_on_closepong_waiters       rO   pingzConnection.pingY  s    L dI&;Dc";;=D<==  	t(((&'VWW ,$$*;*;";{{4););B)?@ ,$$*;*;"; $//+K'2DNN4Dl&SDd#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)	r4   r   r   r   r   r   r   r3   	send_pongrN   r   s     rO   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        j                  u r%| j                  t        |j                               yy)zx
        Process one incoming event.

        This method is overridden in subclasses to handle the handshake.

        N)r4   r   opcoder   rC   putr   PONGacknowledge_pingsr   r   )rN   events     rO   process_eventzConnection.process_event  s]     %''<<<'""5)<<6;;&""5#45 'rQ   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)	r?   rF   r   r   itemsappendsetrG   AssertionError)rN   r   pong_timestampping_idping_idsr   ping_timestamp_ack_on_closes           rO   r   zConnection.acknowledge_pings  s    
    	/4,,,	/ 	/
 "^^-N GH
 ""((*	J  (!d?#1N#BDLJ %%HII $ /%%g./3	/ 	/ 	/s   B?A"B?	,B??Cc                    | j                   j                  t        u sJ | j                  j	                         D ]  \  }}}|s
|j                           | j                  j                          y)zK
        Acknowledge pending pings when the connection is closed.

        N)r3   r[   r   rF   valuesr   clear)rN   r   _ping_timestampr   s       rO   acknowledge_pending_pingsz$Connection.acknowledge_pending_pings  s_    
 }}""f,,:>:K:K:R:R:T 	"6K,!	" 	!rQ   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.

        NT)r   z% sent keepalive pingz% received keepalive pongz&- timed out waiting for keepalive pongzkeepalive ping timeoutzkeepalive ping failedexc_info)r'   rL   r   rG   is_aliver   r   r:   r8   r(   waitr   r3   r   r   ri   r   error)rN   r   s     rO   	keepalivezConnection.keepalive  sb   
 !!--	F '',,T-?-?$,,-NO..779"&)))">K ::KK%%&=>$$0"''(9(9::: KK--.IJ:: KK--.VW!..0  MM.. ) 8 8 8
 9  (    	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.

        NTr/   )r'   r=   rJ   r   rH   rM   rT   s    rO   start_keepalivezConnection.start_keepalive  sF    
 )$-$4$4~~%D! !!'') *rQ   c                R   	 	 	 | j                   5  | j                  3| j                  j                  | j                  j	                                ddd       | j                  j                  | j                        }|dk(  rn| j                  5  | j                  j                  |       | j                  j                         }	 | j                          | j                  j!                         r&| j                  t#        | j$                        | _        ddd       D ]  }| j'                  |        5| j                  5  | j                  j)                          | j                  j                         }| j                          ddd       D ]  }| j'                  |        	 | j-                          y# 1 sw Y   mx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# | j-                          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 the ``self.socket`` is closed.

        TNz! error while receiving datar   rQ   ! error while sending dataunexpected internal error)r@   rD   r2   
settimeoutrs   ro   recv_bufsizer   r:   r8   r?   set_recv_excr3   receive_dataevents_received	send_dataclose_expectedr!   r)   r   receive_eofr   close_socket)rN   r   r   eventsr   s        rO   rK   zConnection.recv_events  s   ^	 // R..: KK2243F3F3N3N3PQR  ;;++D,=,=>D 3; (( OMM..t4 "]]::<F( }}335  ..62:4;M;M2ND/7OH $ .E&&u-.y D $$ 	!))+ 668  	!    *""5)* wR R ! zz)):%) *  ,, /))#./ / /8 % :: KK-- <)- .  ))#.+O OO OT	! 	!(  	'KK9DI$$ '!!#&' ' '	' s  J- G A F;-G =J- 6JH:A J.J- AJ 	 J- )L ;G G 	H75H2H!	H2!H*	&H2-J- 2H77J- :	J:J=J
J- JJJJ-  J*%J- -	L6)LK:1	L:L	?LL LL L&)expected_statec             #  L  K   d}d}d}| j                   5  | j                  j                  |u r[	 d | j                  j                         r*d}| j                  J t        | j                        | _        	 | j                          nd}d}ddd       |r| j                  | j                  }n| 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}~vd}~ww xY w# 1 sw Y   x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::

            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)r?   r3   r[   r   rD   r!   r)   r   r   r:   r8   r   r   r   rs   rL   r   r   TimeoutErrorr   r   r   )rN   r   wait_for_closeraise_close_excoriginal_excr   rs   s          rO   r   zConnection.send_context  s    . -1    .	'}}""n4%+ }}335)-  $22::.6t7I7I.J++(  "&"&].	'j ""*,, --55u5M##((1&&//1 $+++,PQ #'(( 4%%l34
 ##((*--))|;	 Y % 
+:: KK-- <)- .  */*.'*
+3 &'78   'KK%%&AD%Q &+N&*O#&L'.	' .	'J4 4s   H$HGAH8E<HBH$H0AH$<	F?/F:4H:F??HH#H=HHHHH$H!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.

        Raises:
            OSError: When a socket operations fails.

        N)r?   lockedr3   data_to_sendrD   r2   r   rs   sendallshutdownSHUT_WROSErrorr   s     rO   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)zf
        Set recv_exc, if not set yet.

        This method requires holding protocol_mutex.

        N)r?   r   rI   )rN   r   s     rO   r   zConnection.set_recv_exc  s/     ""))++== DM !rQ   c                   	 | j                   j                  t         j                         | j                   j	                          | j
                  5  | j                  j                          | j                  j                  t        u sJ 	 ddd       | j                  j	                          | j                          y# t        $ r Y w xY w# 1 sw Y   Cx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)r2   r   	SHUT_RDWRr   rh   r?   r3   r   r[   r   rC   r   rT   s    rO   r   zConnection.close_socket  s    	KK  !1!12 	    	1MM%%'==&&&000	1
 	  " 	&&(  			1 	1s   )B> 9C>	C
	C
C)r2   zsocket.socketr3   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"   )rj   ztype[BaseException] | Nonerk   BaseException | Nonerl   zTracebackType | Noner   r   )r   Iterator[Data])rs   r   rt   Literal[True]r   r   )rs   r   rt   Literal[False]r   r   rd   )NN)rs   r   rt   bool | Noner   r   )rt   r   r   zIterator[str])rt   r   r   zIterator[bytes])rt   r   r   r   )r   zData | Iterable[Data]r   r   r   r   )r   r5   r   r   r   r   )NF)r   zData | Noner   boolr   zthreading.Event)rQ   )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   rP   propertyrU   rY   r[   r]   r`   rb   rf   rm   rp   r
   ro   r   r   r   NORMAL_CLOSURErh   r   r   r   r   r   r   r   rK   
contextlibcontextmanagerr   r   r   r   r   re   rQ   rO   r"   r"       s   
 L ')%'&(@BY(Y( Y(
 $Y( #Y( $Y( >Y( 
Y(z 
) 
) 
) 
) 
# 
# ) ) 	( 	( 	* 	*	1,	1 (	1 (		1
 
	1( L LO OV V&*#7E	  BF#4?	 D9L I IL LO O<9B !^D&^D ^D 
	^D@ !* 8 8 D !"99 9 
	9v*66/B"%FN*g R  !%k< k< 
	k< k<Z,	 )rQ   )1
__future__r   r  r6   r   r2   r   r=   r   uuidcollections.abcr   r   r   typesr   typingr   r	   r
   
exceptionsr   r   r   r   framesr   r   r   r   r   http11r   r   r3   r   r   r   r   r   r   r   r   messagesr    utilsr!   __all__r"   re   rQ   rO   <module>r     sl    "         7 7  ) )  G F & ; ; 2 2   .P) P)rQ   