
    ,hR                       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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 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/m0Z0m1Z1m2Z2m3Z3m4Z4 ddl5m6Z6 dgZ7 G d dejT                        Z8	 d	 	 	 	 	 	 	 ddZ9de9_:        y)    )annotationsN)AsyncIterableAsyncIterator	AwaitableIterableMapping)TracebackType)AnyLiteralcastoverload   )ConcurrencyErrorConnectionClosedConnectionClosedOKProtocolError)DATA_OPCODES	BytesLike	CloseCodeFrameOpcode)RequestResponse)CLOSEDOPENEventProtocolState)Data
LoggerLikeSubprotocol   )TimeoutErroraiteranextasyncio_timeoutasyncio_timeout_at)	Assembler
Connectionc                  6   e Zd ZdZd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: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Zd@dAdZdBdZd:dCdZdDdEdZdFdZdGd ZdBd!ZdBd"ZdBd#Zej:                  ed$	 	 	 dHd%       ZdBd&Z dId'Z!dJd(Z"dKd)Z#dBd*Z$dBd+Z%dBd,Z&dGd-Z'dBd.Z(y)Lr)   aC  
    :mod:`asyncio` 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.asyncio.client.ClientConnection` or
    :class:`~websockets.asyncio.server.ServerConnection`.

       
      i   )ping_intervalping_timeoutclose_timeout	max_queuewrite_limitc                  || _         || _        || _        || _        t	        |t
              s||d f}|| _        t	        |t
              r|d f}|| _        t        j                  | j                   j                  d| i      | j                   _
        | j                   j                  | _        	 | j                   j                  | _
        	 | j                   j                  | _        d | _        	 d | _        	 t        j                          | _        |  d | _        d | _        i | _        d| _        	 d | _        d | _        | j"                  j1                         | _        d| _        t7        j8                         | _        y )N	websocketr   F)protocolr.   r/   r0   
isinstanceintr1   r2   loggingLoggerAdapterloggeriddebugrequestresponseasyncioget_running_looploopclose_deadlinefragmented_send_waiterpong_waiterslatencykeepalive_taskrecv_exccreate_futureconnection_lost_waiterpausedcollectionsdequedrain_waiters)selfr5   r.   r/   r0   r1   r2   s          _/var/www/html/Resume-Scraper/venv/lib/python3.12/site-packages/websockets/asyncio/connection.py__init__zConnection.__init__4   sk    !*(*i%):"D)I"k3'&-K&  '44MM  $ 
 "]]--B"&--"6"6)]]((
 (,()-) ,,.	 	 -1 DH# OQ
	 :> /3 =AII<S<S<U# " 	    c                8    | j                   j                  d      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`.

        sockname	transportget_extra_inforN   s    rO   local_addresszConnection.local_address        ~~,,Z88rQ   c                8    | j                   j                  d      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`.

        peernamerT   rW   s    rO   remote_addresszConnection.remote_address   rY   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.

        )r5   staterW   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.

        )r5   subprotocolrW   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.

        )r5   
close_coderW   s    rO   rc   zConnection.close_code   s     }}'''rQ   c                .    | j                   j                  S rb   )r5   close_reasonrW   s    rO   re   zConnection.close_reason   s     }})))rQ   c                   K   | S wN rW   s    rO   
__aenter__zConnection.__aenter__   s     s   c                   K   || j                          d {    y | j                  t        j                         d {    y 7 -7 wrg   )closer   INTERNAL_ERROR)rN   exc_type	exc_value	tracebacks       rO   	__aexit__zConnection.__aexit__   s>      **,**Y55666 6s!   A
A'A
 AA
A
c               h   K   	 	 | j                          d{    7 # t        $ r Y yw xY ww)aZ  
        Iterate on incoming messages.

        The iterator calls :meth:`recv` and yields messages asynchronously 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   rW   s    rO   	__aiter__zConnection.__aiter__   s6     	 IIK'' '! 		s    2# !	# 	/2/2c                   K   y wrg   rh   rN   decodes     rO   rr   zConnection.recv   s	     8;   c                   K   y wrg   rh   ru   s     rO   rr   zConnection.recv   s	     ;>rw   Nc                   K   y wrg   rh   ru   s     rO   rr   zConnection.recv   s	     >Arw   c                X  K   	 | j                   j                  |       d{   S 7 # t        $ r Y nt        $ r t        d      dt        $ r}| j                         4 d{  7   | j                  j                  t        j                  |j                   d|j                          ddd      d{  7   n# 1 d{  7  sw Y   nxY wY d}~nd}~ww xY wt        j                  | j                         d{  7   | j                  j                  | j                   w)aq  
        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.

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

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

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

        Args:
            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 coroutines call :meth:`recv` or
                :meth:`recv_streaming` concurrently.

        NzRcannot call recv while another coroutine is already running recv or recv_streaming at position )recv_messagesgetEOFErrorr   UnicodeDecodeErrorsend_contextr5   failr   INVALID_DATAreasonstartr?   shieldrI   	close_excrG   )rN   rv   excs      rO   rr   zConnection.recv   s     ^	++//7777 	 	"<  " 	((*  ""**zzl-		{;    	 nnT88999mm%%4==8s   D*) ') D*) 	CD*CC$A'%C)AB?-C8B;9C?C	CC	CD*C%D*D&D*c                     y rg   rh   ru   s     rO   recv_streamingzConnection.recv_streamingD  s    KNrQ   c                     y rg   rh   ru   s     rO   r   zConnection.recv_streamingG  s    NQrQ   c                     y rg   rh   ru   s     rO   r   zConnection.recv_streamingJ  s    QTrQ   c               j  K   	 | j                   j                  |      2 3 d{   }| 7 
6 y# t        $ r Y nt        $ r t        d      dt        $ r}| j                         4 d{  7   | j                  j                  t        j                  |j                   d|j                          ddd      d{  7   n# 1 d{  7  sw Y   nxY wY d}~nd}~ww xY wt        j                  | j                         d{  7   | j                  j                  | j                   w)a  
        Receive the next message frame by frame.

        This method is designed for receiving fragmented messages. It returns an
        asynchronous 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`.

        Canceling :meth:`recv_streaming` before receiving the first frame is
        safe. Canceling it after receiving one or more frames leaves the
        iterator in a partially consumed state, making the connection unusable.
        Instead, you should close the connection with :meth:`close`.

        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 coroutines call :meth:`recv` or
                :meth:`recv_streaming` concurrently.

        Nz\cannot call recv_streaming while another coroutine is already running recv or recv_streamingr{   )r|   get_iterr~   r   r   r   r5   r   r   r   r   r   r?   r   rI   r   rG   )rN   rv   framer   s       rO   r   zConnection.recv_streamingM  s
    X	#11::6B  eB 	 	"<  " 	((*  ""**zzl-		{;    	 nnT88999mm%%4==8s   D32 0.02 02 D3	C'D3C'C"-A0.C"2AC6C"CC"C	CC	C"D3"C''%D3D&D3c                &  K   | j                   4t        j                  | j                          d{    | j                   4t        |t              r| j                         4 d{    |du r*| j                  j                  |j                                n)| j                  j                  |j                                ddd      d{    yt        |t              re| j                         4 d{    |du r| j                  j                  |       n| j                  j                  |       ddd      d{    yt        |t              rt        d      t        |t              rt        |      }	 t        |      }| j                   J | j"                  j%                         | _         	 t        |t              r| j                         4 d{    |du r,| j                  j                  |j                         d       n+| j                  j                  |j                         d       ddd      d{    d}nt        |t              rk| j                         4 d{    |du r| j                  j                  |d       n| j                  j                  |d       ddd      d{    d}nt        d      |D ]  }t        |t              rW|rU| j                         4 d{    | j                  j'                  |j                         d       ddd      d{    jt        |t              rI|sG| j                         4 d{    | j                  j'                  |d       ddd      d{    t        d       | j                         4 d{    | j                  j'                  dd       ddd      d{    | j                   j1                  d       d| _         yt        |t2              rt5        |      }	 t7        |       d{   }| j                   J | j"                  j%                         | _         	 t        |t              r|du rU| j                         4 d{    | j                  j                  |j                         d       ddd      d{    nT| j                         4 d{    | j                  j                  |j                         d       ddd      d{    d}nt        |t              r|du rG| j                         4 d{    | j                  j                  |d       ddd      d{    nF| j                         4 d{    | j                  j                  |d       ddd      d{    d}nt        d
      |2 3 d{   }t        |t              rW|rU| j                         4 d{    | j                  j'                  |j                         d       ddd      d{    pt        |t              rI|sG| j                         4 d{    | j                  j'                  |d       ddd      d{    t        d      t        d      7 7 [7 # 1 d{  7  sw Y   yxY w7 7 # 1 d{  7  sw Y   yxY w# t         $ r Y yw xY w7 )7 # 1 d{  7  sw Y   xY w7 7 b# 1 d{  7  sw Y   sxY w7 =7 # 1 d{  7  sw Y   xY w7 7 # 1 d{  7  sw Y   xY w7 7 # 1 d{  7  sw Y   xY w# t(        $ rl | j                         4 d{  7   | j                  j+                  t,        j.                  d	       ddd      d{  7    # 1 d{  7  sw Y    xY ww xY w# | j                   j1                  d       d| _         w xY w7 # t8        $ r Y yw xY w7 7 u# 1 d{  7  sw Y   1xY w7 t7 <# 1 d{  7  sw Y   MxY w7 %7 # 1 d{  7  sw Y   xY w7 7 # 1 d{  7  sw Y   xY w7 7 7 p# 1 d{  7  sw Y   xY w7 ]7 3# 1 d{  7  sw Y   xY w6 | j                         4 d{  7   | j                  j'                  dd       ddd      d{  7   n# 1 d{  7  sw Y   nxY wnx# t(        $ rl | j                         4 d{  7   | j                  j+                  t,        j.                  d	       ddd      d{  7    # 1 d{  7  sw Y    xY ww xY w| j                   j1                  d       d| _         y# | j                   j1                  d       d| _         w xY w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 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://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`.)

        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: Message to send.

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

        NFTzdata is a dict-like object)finz"iterable must contain bytes or strz#iterable must contain uniform typesrQ   zerror in fragmented messagez(async iterable must contain bytes or strz)async iterable must contain uniform typesz4data must be str, bytes, iterable, or async iterable)rC   r?   r   r6   strr   r5   send_binaryencode	send_textr   r   	TypeErrorr   iternextStopIterationrA   rH   send_continuation	Exceptionr   r   rl   
set_resultr   r$   r%   StopAsyncIteration)rN   messagetextchunkschunkr   achunkss          rO   sendzConnection.send  s;	    H ))5..!<!<=== ))5 gs#((* > >5=MM--gnn.>?MM++GNN,<=	> > > +((* 7 74<MM++G4MM--g6	7 7 7 )899 *']FV ..66*.))*A*A*CD'.3eS)#002 O O5= MM55elln%5P MM33ELLN3N	O O
 "Fy1#002 H H4< MM33Eu3E MM55e5G	H H
 #F#$HII $ OE!%-&#'#4#4#6 W W MM;;ELLNPU;VW W W#E95f#'#4#4#6 N N MM;;Eu;MN N N ((MNNO  ,,. C CMM33CT3BC C ++66t<.2+ /GnG#Gn, ..66*.))*A*A*CD'03eS)u}#'#4#4#6 Q Q MM55elln%5PQ Q Q $(#4#4#6 O O MM33ELLN3NO O!Fy1t|#'#4#4#6 F F MM33Eu3EF F F $(#4#4#6 H H MM55e5GH H"F#$NOO $+ U U%!%-&#'#4#4#6 W W MM;;ELLNPU;VW W W#E95f#'#4#4#6 N N MM;;Eu;MN N N ((STT* RSSc >> > > > >7 7 7 7 7" ! O O O O OH H H H HW W W W WN N N N NC C C C C    ,,.  MM&&!005  
   
  ++66t<.2+ -% Q Q Q Q QO O O O O
F F F F FH H H H HUW W W W WN N N N N $+  ,,. C CMM33CT3BC C C C C    ,,.  MM&&!005  
   
  ++66t<.2+ ++66t<.2+s
  /hZ?h$h'[(h+A[h[)h8[9h<<[#8h[ <h[8 -h:$^ \^ "A\>^ 	\

+^ 5\#6^ 9A \)9^ \&=^ \?^ ,]2^ =]>+^ )]*^ -]!^ ]%^ <]7=^  ]=^ )]:*^ .?h.`5 <`2=`5 -h/(e ae ,a
e ae ,a -e 0,a&e 'a#(/e a<e b9e a?e be "b e be  c/$b4%c/('e b7e ,b=?e 
b:+e 6c7e :ce #c$e 4hhh[[[h h#[5)[,*[51h8	\h\h^ 
^ \ \\ 	^ &^ )\</\20\<7	^ ^ ]	]]		^ ^ !]4	']*(]4	/	^ :^ =^^^^ `0^31`5+_2 `+_.,`2`	8_;9`	 `` $`//h2`5 5	a>h ahe e 
aaa	e #e &a9,a/-a94	e ?e bb	b	e e b1$b'%b1,e 4c/7e :e =c	cc		e e c,	c" c,	'e de 	d9'e 2d53e 9e?e ee g* g,e/-g1+f.g'f*(g.g 	4f75g 	<gg* #h*$hhc                V  K   	 | j                         4 d{    | j                  +| j                  j                  t        j
                  d       n| j                  j                  ||       ddd      d{    y7 h7 # 1 d{  7  sw Y   yxY w# t        $ r Y yw xY w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.

        Nzclose during fragmented message)r   rC   r5   r   r   rl   
send_closer   )rN   coder   s      rO   rk   zConnection.closei  s     	 ((* ; ;..:MM&&!009
 MM,,T6:; ; ; ; ; ; ;   	 	sz   B)B BB AB0B ;B<B  B)B B BBBB B)B 	B&#B)%B&&B)c                ^   K   t        j                  | j                         d{    y7 w)z
        Wait until the connection is closed.

        :meth:`wait_closed` waits for the closing handshake to complete and for
        the TCP connection to terminate.

        N)r?   r   rI   rW   s    rO   wait_closedzConnection.wait_closed  s       nnT88999s   #-+-c                  K   t        |t              rt        |      }n.t        |t              r|j	                         }n|t        d      | j                         4 d{    || j                  v rt        d      ||| j                  v r;t        j                  dt        j                  d            }|,|| j                  v r;| j                  j                         }|| j                  j                         f| j                  |<   | j                   j#                  |       |cddd      d{    S 7 7 # 1 d{  7  sw Y   yxY w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.

        Returns:
            A future that will be completed when the corresponding pong is
            received. You can ignore it if you don't intend to wait. The result
            of the future is the latency of the connection in seconds.

            ::

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

        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    )r6   r   bytesr   r   r   r   rD   r   structpackrandomgetrandbitsrA   rH   timer5   	send_ping)rN   datapong_waiters      rO   pingzConnection.ping  s%    < dI&;Dc";;=D<==$$& 	 	t(((&'VWW ,$$*;*;";{{4););B)?@ ,$$*;*;"; ))113K (3DIINN4D&EDd#MM##D)	 	 	 	 	 	 	sV   AE!D;"E%AD?;D?
AD?)E5D=6E=E?EEEEc                V  K   t        |t              rt        |      }n,t        |t              r|j	                         }nt        d      | j                         4 d{    | j                  j                  |       ddd      d{    y7 07 # 1 d{  7  sw Y   yxY w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)	r6   r   r   r   r   r   r   r5   	send_pongrN   r   s     rO   pongzConnection.pong  s      dI&;Dc";;=D<==$$& 	* 	*MM##D)	* 	* 	* 	* 	* 	* 	*sH   AB)B B)#B?B)
BB)B)B&BB&"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)r6   r   opcoder   r|   putr   PONGacknowledge_pingsr   r   )rN   events     rO   process_eventzConnection.process_event  s]     %''<<<'""5)<<6;;&""5#45 'rQ   c                p   || j                   vry| j                  j                         }d}g }| j                   j                         D ]M  \  }\  }}|j	                  |       ||z
  }|j                         s|j                  |       ||k(  sF|| _         n t        d      |D ]  }| j                   |=  y)z;
        Acknowledge pings when receiving a pong.

        Nz!solicited pong not found in pings)	rD   rA   r   itemsappenddoner   rE   AssertionError)rN   r   pong_timestampping_idping_idsr   ping_timestamprE   s           rO   r   zConnection.acknowledge_pings  s     t((() 6:6G6G6M6M6O 		F2G2k>OOG$$~5G##%&&w/$&		F !!DEE   	+G!!'*	+rQ   c                F   | j                   j                  t        u sJ | j                   j                  }| j                  j                         D ]6  \  }}|j                         s|j                  |       |j                          8 | j                  j                          y)z
        Raise ConnectionClosed in pending pings.

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

        N)
r5   r^   r   r   rD   valuesr   set_exceptioncancelclear)rN   r   r   _ping_timestamps       rO   abort_pingszConnection.abort_pings  s     }}""f,,mm%%,0,=,=,D,D,F 	!(K##%))#.
  	! 	!rQ   c                  K   | j                   J d}	 	 t        j                  | j                   |z
         d{    | j                          d{   }| j                  r| j
                  j	                  d       | j                  T	 t        | j                        4 d{    | d{   }ddd      d{    | j
                  j	                  d       7 7 7 >7 67 (# 1 d{  7  sw Y   8xY w# t        j                  $ r | j                  r| j
                  j	                  d       | j                         4 d{  7   | j                  j                  t        j                  d       ddd      d{  7   t        d      # 1 d{  7  sw Y   t        d      xY ww xY w# t        $ r  | j
                  j!                  d	d
       Y yw xY ww)zT
        Send a Ping frame and wait for a Pong frame at regular intervals.

        Ng        Tz% sent keepalive pingz% received keepalive pongz&- timed out waiting for keepalive pongzkeepalive ping timeoutzKsend_context() should wait for connection_lost(), which cancels keepalive()zkeepalive ping failedexc_info)r.   r?   sleepr   r<   r:   r/   r&   r#   r   r5   r   r   rl   r   r   error)rN   rE   r   s      rO   	keepalivezConnection.keepalive#  s    
 !!--&	F mmD$6$6$@AAA %)IIK/::KK%%&=>$$0#243D3D#E 8 8
 -8&7G8 8 ))*EF/  B 08
 '88 8 8 8 #// :: KK--.VW#'#4#4#6   MM.. ) 8 8 8  
 -8   
 -8   	FKK5E	Fs   G'&F; CF; C!7F; C> $C#%C> (C).C%/C)3C> >C'?C> F; !F; #C> %C)'C> )C;/C20C;7C> >AF8EF8+F<F8F
F8F4	F!F4	&F88F; ;&G$!G'#G$$G'c                z    | j                   /| j                  j                  | j                               | _        yy)zQ
        Run :meth:`keepalive` in a task, unless keepalive is disabled.

        N)r.   rA   create_taskr   rF   rW   s    rO   start_keepalivezConnection.start_keepaliveR  s3    
 )"&))"7"78H"ID *rQ   )expected_statec              &  K   d}d}d}| j                   j                  |u r	 d | j                   j                         rHd}| j                  :| j                  J | j
                  j                         | j                  z   | _        	 | j                          | j                          d{    nHd}| j                  8| j                  ,| j
                  j                         | j                  z   | _        d}|rV	 t        | j                        4 d{    t!        j"                  | j$                         d{    ddd      d{    |rX| j*                  j-                          t!        j"                  | j$                         d{    | j                   j.                  |y7 # t        $ r9}| 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}~<d}~ww xY w7 (7 7 # 1 d{  7  sw Y   xY w# t&        $ r& |J t'        d      }d}| j)                  |       Y 8w xY w7 w)ap  
        Create a context for writing to the connection from user code.

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

            async 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`.

        FNT! error while sending datar   zunexpected internal errorz"timed out while closing connection)r5   r^   close_expectedr0   rB   rA   r   	send_datadrainr   r<   r:   r   r   r   r'   r?   r   rI   r#   set_recv_excrU   abortr   )rN   r   wait_for_closeraise_close_excoriginal_excr   s         rO   r   zConnection.send_contextZ  se    , -1==.0#' ==//1%)N
 ))5#22::.2iinn.>ASAS.S+
'NN$**,&& "N!!-&&.*.))..*:T=O=O*OD'"O 0-d.A.AB F F!..)D)DEEEF F NN  "..!<!<===--))|;	 M '  'zz))*FQU)V &+N&*O#&L'5 "#34  #!!"=!M "'"&"#\FEF F F F 0 $+++,PQ #'!!,/0 >s   JG6 A"J
#F1 -F..F1 2AJ>I H?I #I>I?II II >JJJ.F1 1	G3:/G.)J.G33J6H<#H71J7H<<J?I II IIII +JJJJc                   | j                   j                         D ]  }|r| j                  j                  |       !| j                  j	                         rC| j
                  r| j                  j                  d       	 | j                  j                          ~| j
                  r| j                  j                  d       | j                  j                           y# t        t        f$ r Y w xY w)zl
        Send outgoing data.

        Raises:
            OSError: When a socket operations fails.

        zx half-closing TCP connectionzx closing TCP connectionN)r5   data_to_sendrU   writecan_write_eofr<   r:   	write_eofOSErrorRuntimeErrorrk   r   s     rO   r   zConnection.send_data  s     MM..0 	+D$$T* >>//1zz))*IJ002
 zz))*DENN((*%	+ $\2 s   >CC/.C/c                ,    | j                   || _         yy)z0
        Set recv_exc, if not set yet.

        N)rG   )rN   r   s     rO   r   zConnection.set_recv_exc  s    
 == DM !rQ   c                    t        t        j                  |      }t        | j                  |j
                  |j                  d| _         |j                  | j                    || _
        y )N)pauseresume)r   r?   	Transportr(   r1   pause_readingresume_readingr|   set_write_buffer_limitsr2   rU   )rN   rU   s     rO   connection_madezConnection.connection_made  sY    **I6	&^^))++

 	*	))4+;+;<"rQ   c                "   | j                   j                          | j                   j                  t        u sJ | j	                  |       | j
                  j                          | j                          | j                  | j                  j                          | j                  j                  d        | j                  rOd| _        | j                  D ]8  }|j                         r||j                  d        (|j                  |       : y y NF)r5   receive_eofr^   r   r   r|   rk   r   rF   r   rI   r   rJ   rM   r   r   )rN   r   waiters      rO   connection_lostzConnection.connection_lost  s     	!!#}}""f,,# 	  "*&&(
 	##..t4 ;;DK,, 2{{}{))$/,,S12 rQ   c                .    | j                   rJ d| _         y )NT)rJ   rW   s    rO   pause_writingzConnection.pause_writing  s    ;;rQ   c                    | j                   sJ d| _         | j                  D ]$  }|j                         r|j                  d        & y r   )rJ   rM   r   r   rN   r   s     rO   resume_writingzConnection.resume_writing  s?    {{(( 	(F;;=!!$'	(rQ   c                  K   | j                   j                         rt        j                  d       d {    | j                  r\| j
                  j                         }| j                  j                  |       	 | d {    | j                  j                  |       y y 7 m7 ## | j                  j                  |       w xY ww)Nr   )
rU   
is_closingr?   r   rJ   rA   rH   rM   r   remover   s     rO   r   zConnection.drain  s      >>$$&--""" ;;YY,,.F%%f-2""))&1  # ""))&1s:   3CB#AC<B' B%B' C%B' 'CCc                   | j                   j                  |       | j                   j                         }	 | j                          | j                   j                         rD| j                  8| j                  ,| j                  j                         | j                  z   | _
        |D ]  }| j                  |        y # t        $ rD}| j
                  r| j                  j                  dd       | j                  |       Y d }~d }~ww xY w)Nr   Tr   )r5   receive_dataevents_receivedr   r   r<   r:   r   r   r0   rB   rA   r   r   )rN   r   eventsr   r   s        rO   data_receivedzConnection.data_received2  s    ""4( ..0	#NN =='') !!-&&.*.))..*:T=O=O*OD' 	&Eu%	&  	#zz!!">!Nc""	#s   B> >	D:DDc                    | j                   j                          | j                   j                         }| j                          |D ]  }| j	                  |        y rg   )r5   r   r  r   r   )rN   r  r   s      rO   eof_receivedzConnection.eof_receivedL  sQ    !!# ..0 	  	&Eu%	&rQ   )r5   r   r.   float | Noner/   r  r0   r  r1   z*int | None | tuple[int | None, int | None]r2   zint | tuple[int, int | None]returnNone)r	  r
   )r	  r   )r	  zSubprotocol | None)r	  z
int | None)r	  z
str | None)r	  r)   )rm   ztype[BaseException] | Nonern   BaseException | Nonero   zTracebackType | Noner	  r
  )r	  AsyncIterator[Data])rv   Literal[True]r	  r   )rv   Literal[False]r	  r   rg   )rv   bool | Noner	  r   )rv   r  r	  zAsyncIterator[str])rv   r  r	  zAsyncIterator[bytes])rv   r  r	  r  )r   z+Data | Iterable[Data] | AsyncIterable[Data]r   r  r	  r
  )i   )r   r7   r   r   r	  r
  )r	  r
  )r   zData | Noner	  zAwaitable[float])rQ   )r   r   r	  r
  )r   r   r	  r
  )r   r   r	  r
  )r   r   r	  zAsyncIterator[None])r   r  r	  r
  )rU   zasyncio.BaseTransportr	  r
  )r   zException | Noner	  r
  ))__name__
__module____qualname____doc__rP   propertyrX   r\   r^   r`   rc   re   ri   rp   rs   r   rr   r   r   rk   r   r   r   r   r   r   r   r   
contextlibasynccontextmanagerr   r   r   r   r   r   r   r   r   r  r  rh   rQ   rO   r)   r)   '   sC   
  ')%'&(@B49S
S
 $	S

 #S
 $S
 >S
 2S
 
S
n 
9 
9 
9 
9 
# 
# ) ) 	( 	( 	* 	*	7,	7 (	7 (		7
 
	7$ ; ;> >A AC9J N NQ QT TB9N !VT<VT VT 
	VTp>:3j*66+<"*-F^J ## !%b< b< 
	b< $b<H+8 #2@
(2(&4&rQ   c           
     0   t        |t              rd}|j                         }nt        |t              rd}nt	        d      |r#t
        j                  dd dk  rt        d      g }| D ]  }|j                  j                  t        ur |j                  ;|rt        d      }j                  |       n|j                  j                  d	       g	  t!        |j                  |      |       |j#                           |rrt3        d|      yy# t$        $ r{}|r$t'        d
      }||_        j                  |       nJ|j                  j                  dt+        j,                  t/        |      |      d   j1                                Y d}~'d}~ww 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

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

    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
    ``ping_interval`` and ``ping_timeout`` low to prevent excessive memory usage
    from slow connections.

    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. On Python 3.11 and above, 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.

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

    r   r   zdata must be str or bytesNr   )      z.raise_exceptions requires at least Python 3.11zsending a fragmented messagez/skipped broadcast: sending a fragmented messagezfailed to write messagez.skipped broadcast: failed to write message: %sr   zskipped broadcast)r6   r   r   r   r   sysversion_info
ValueErrorr5   r^   r   rC   r   r   r:   warninggetattrr   r   r   	__cause__ro   format_exception_onlytypestripExceptionGroup)connectionsr   raise_exceptionssend_method
exceptions
connection	exceptionwrite_exceptions           rO   	broadcastr,  m  s   d '3!.."	GY	'#344BQ')MNN&(
! "
 $$D0,,8,-KL	!!),!!))E 	 6GJ''5g>  ")"H J0*== '  	()BC	&5	#!!),!!))D33_-' 	 	s   ,D	FA0FFzwebsockets.asyncio.server)F)r%  zIterable[Connection]r   r   r&  boolr	  r
  );
__future__r   r?   rK   r  r8   r   r   r  ro   uuidcollections.abcr   r   r   r   r   typesr	   typingr
   r   r   r   r(  r   r   r   r   framesr   r   r   r   r   http11r   r   r5   r   r   r   r   r   r   r    r!   compatibilityr#   r$   r%   r&   r'   messagesr(   __all__r)   r,  r  rh   rQ   rO   <module>r8     s    "       
   V V  / /  G F & ; ; 2 2    .w&!! w&R" #d>%d>d> d> 
	d>P 3	 rQ   