K iddlmZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlmZmZmZmZmZddlmZmZmZmZddlmZddlmZddlmZmZm Z m!Z!m"Z"m#Z#dd l$m%Z%dd l&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0dd l1m2Z2dd lm3Z3m4Z4m5Z5d dl6m7Z7m8Z8m9Z9dgZ:GddejvZ< d ddZ=de=_>y)) annotationsN) AsyncIterable AsyncIterator AwaitableIterableMapping)AnyCallableDequecast)asyncio_timeout)Headers)ConnectionClosedConnectionClosedErrorConnectionClosedOK InvalidState PayloadTooBig ProtocolError) Extension) OK_CLOSE_CODES OP_BINARYOP_CLOSEOP_CONTOP_PINGOP_PONGOP_TEXTClose CloseCodeOpcode)State)Data LoggerLike Subprotocol)Frame prepare_ctrl prepare_dataWebSocketCommonProtocolceZdZUdZded<dZded<ddddd d d d dddd ddd  d:dZd;dZd;dZd;dZ e ddZ e d?dZe d?dZe d@dZe d@dZe d=dZe d` for details. The ``close_timeout`` parameter defines a maximum wait time for completing the closing handshake and terminating the TCP connection. For legacy reasons, :meth:`close` completes in at most ``5 * close_timeout`` seconds for clients and ``4 * close_timeout`` for servers. ``close_timeout`` is a parameter of the protocol because websockets usually calls :meth:`close` implicitly upon exit: * on the client side, when using :func:`~websockets.legacy.client.connect` as a context manager; * on the server side, when the connection handler terminates. To apply a timeout to any other API, wrap it in :func:`~asyncio.timeout` or :func:`~asyncio.wait_for`. The ``max_size`` parameter enforces the maximum size for incoming messages in bytes. The default value is 1 MiB. If a larger message is received, :meth:`recv` will raise :exc:`~websockets.exceptions.ConnectionClosedError` and the connection will be closed with code 1009. The ``max_queue`` parameter sets the maximum length of the queue that holds incoming messages. The default value is ``32``. Messages are added to an in-memory queue when they're received; then :meth:`recv` pops from that queue. In order to prevent excessive memory consumption when messages are received faster than they can be processed, the queue must be bounded. If the queue fills up, the protocol stops processing incoming data until :meth:`recv` is called. In this situation, various receive buffers (at least in :mod:`asyncio` and in the OS) will fill up, then the TCP receive window will shrink, slowing down transmission to avoid packet loss. Since Python can use up to 4 bytes of memory to represent a single character, each connection may use up to ``4 * max_size * max_queue`` bytes of memory to store incoming messages. By default, this is 128 MiB. You may want to lower the limits, depending on your application's requirements. The ``read_limit`` argument sets the high-water limit of the buffer for incoming bytes. The low-water limit is half the high-water limit. The default value is 64 KiB, half of asyncio's default (based on the current implementation of :class:`~asyncio.StreamReader`). The ``write_limit`` argument sets the high-water limit of the buffer for outgoing bytes. The low-water limit is a quarter of the high-water limit. The default value is 64 KiB, equal to asyncio's default (based on the current implementation of ``FlowControlMixin``). See the discussion of :doc:`memory usage <../../topics/memory>` for details. Args: logger: Logger for this server. It defaults to ``logging.getLogger("websockets.protocol")``. See the :doc:`logging guide <../../topics/logging>` for details. ping_interval: Interval between keepalive pings in seconds. :obj:`None` disables keepalive. ping_timeout: Timeout for keepalive pings in seconds. :obj:`None` disables timeouts. close_timeout: Timeout for closing the connection in seconds. For legacy reasons, the actual timeout is 4 or 5 times larger. max_size: Maximum size of incoming messages in bytes. :obj:`None` disables the limit. max_queue: Maximum number of incoming messages in receive buffer. :obj:`None` disables the limit. read_limit: High-water mark of read buffer in bytes. write_limit: High-water mark of write buffer in bytes. bool is_client undefinedstrsideNi iF)logger ping_interval ping_timeout close_timeoutmax_size max_queue read_limit write_limithostportsecure legacy_recvlooptimeoutc| rtjdt|d}ntjdt||}| tj} ntjdt||_||_||_||_||_ ||_ ||_ tj|_ |tj d}tj"|d|i|_ |j'tj(|_| |_| |_| |_| |_| |_tj6|dz| |_d |_d|_tj>|_ tBjD|_#|j*r|j$j+d | | | g|_$d|_% d|_&d|_'d|_(| jS|_*tWjX|_-d|_.d|_/d|_0i|_1d |_2 |d|_3||y) Nzlegacy_recv is deprecated zrename timeout to close_timeoutzremove loop argumentzwebsockets.protocol websocketr )limitr>Fz= connection is CONNECTINGr)4warningswarnDeprecationWarningasyncioget_event_loopr3r4r5r6r7r8r9uuiduuid4idlogging getLogger LoggerAdapterr2 isEnabledForDEBUGdebugr>_host_port_securer= StreamReaderreader_paused _drain_waiterLock _drain_lockr! CONNECTINGstate extensions subprotocol close_rcvd close_sentclose_rcvd_then_sent create_futureconnection_lost_waiter collectionsdequemessages_pop_message_waiter_put_message_waiter_fragmented_message_waiterpingslatencytransfer_data_exc)selfr2r3r4r5r6r7r8r9r:r;r<r=r>r?s `/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/websockets/legacy/protocol.py__init__z WebSocketCommonProtocol.__init__s.&  MM57I J ?G MM;=O P  #M <))+D MM02D E*(*  "$&"ZZ\B >&&'<=F")"7"7d@S"T )((7     & **qtL  :>"<<> %% :: KK  : ; 4 0 1,./31)-(,15! =Arbrmwaiters rn _drain_helperz%WebSocketCommonProtocol._drain_helper0sp  & & + + -&'89 9|| ##~!1!1!333((*# sA9B;B<BcK|j|jj}|||j7|jjrt j dd{|j d{y77w)Nr)rV exception transport is_closingrGsleeprwrmexcs rn_drainzWebSocketCommonProtocol._drain<su ;; "++'')C >> %~~((*mmA&&&  """'"s$A)B +B ,B B B  B c|jtjusJtj|_|jr|j j d|j j|j|_ |j j|j|_ |j j|j|_ y)z Callback when the WebSocket opening handshake completes. Enter the OPEN state and start the data transfer phase. z= connection is OPENN)r\r!r[OPENrQr2r> create_task transfer_datatransfer_data_taskkeepalive_pingkeepalive_ping_taskclose_connectionclose_connection_taskrms rnconnection_openz'WebSocketCommonProtocol.connection_openLszzU-----ZZ :: KK  4 5"&))"7"78J8J8L"M#'99#8#89L9L9N#O %)YY%:%:4;P;P;R%S"rpcv|jrdnd}tjd|dt|jS)Nremote_address local_addressuse z[0] instead of host)r,rDrErFrRrm alternatives rnr:zWebSocketCommonProtocol.host_3*...&o  [M)<=?QRzzrpcv|jrdnd}tjd|dt|jS)Nrrrz[1] instead of port)r,rDrErFrSrs rnr;zWebSocketCommonProtocol.porterrpcNtjdt|jS)Nzdon't use secure)rDrErFrTrs rnr<zWebSocketCommonProtocol.secureks (*<=||rpc\ |j}|jdS#t$rYywxYw)a( Local address of the connection. For IPv4 connections, this is a ``(host, port)`` tuple. The format of the address depends on the address family; see :meth:`~socket.socket.getsockname`. :obj:`None` if the TCP connection isn't established yet. socknameNrzget_extra_infoAttributeErrorrmrzs rnrz%WebSocketCommonProtocol.local_addressr7 8I++J7 7    ++c\ |j}|jdS#t$rYywxYw)a) Remote address of the connection. For IPv4 connections, this is a ``(host, port)`` tuple. The format of the address depends on the address family; see :meth:`~socket.socket.getpeername`. :obj:`None` if the TCP connection isn't established yet. peernameNrrs rnrz&WebSocketCommonProtocol.remote_addressrrct|jtjuxr|jj S)a{ :obj:`True` when the connection is open; :obj:`False` otherwise. This attribute may be used to detect disconnections. However, this approach is discouraged per the EAFP_ principle. Instead, you should handle :exc:`~websockets.exceptions.ConnectionClosed` exceptions. .. _EAFP: https://docs.python.org/3/glossary.html#term-eafp )r\r!rrrrrs rnopenzWebSocketCommonProtocol.opens.zzUZZ'N0G0G0L0L0N,NNrpc:|jtjuS)z :obj:`True` when the connection is closed; :obj:`False` otherwise. Be aware that both :attr:`open` and :attr:`closed` are :obj:`False` during the opening and closing sequences. )r\r!CLOSEDrs rnclosedzWebSocketCommonProtocol.closedszzU\\))rpc|jtjury|jtj S|jj S)z WebSocket close code, defined in `section 7.1.5 of RFC 6455`_. .. _section 7.1.5 of RFC 6455: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 :obj:`None` if the connection isn't closed yet. N)r\r!rr_rABNORMAL_CLOSUREcoders rn close_codez"WebSocketCommonProtocol.close_codes= ::U\\ ) __ $-- -??'' 'rpc|jtjury|jy|jjS)z WebSocket close reason, defined in `section 7.1.6 of RFC 6455`_. .. _section 7.1.6 of RFC 6455: https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6 :obj:`None` if the connection isn't closed yet. N)r\r!rr_reasonrs rn close_reasonz$WebSocketCommonProtocol.close_reasons4 ::U\\ ) __ $??)) )rpchK |jd{7#t$rYywxYww)aU Iterate on incoming messages. The iterator exits normally when the connection is closed with the close code 1000 (OK) or 1001 (going away) or without a close code. It raises a :exc:`~websockets.exceptions.ConnectionClosedError` exception when the connection is closed with any other code. N)recvrrs rn __aiter__z!WebSocketCommonProtocol.__aiter__s6  IIK'''!   s 2#! # /2/2c|K|j tdt|jdkr|jj }||_ t j||jgt jd{d|_|js%|jry|jd{t|jdkr|jj}|j"|jjdd|_|S7#d|_wxYw7uw)a Receive the next message. When the connection is closed, :meth:`recv` raises :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it raises :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal connection closure and :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol error or a network failure. This is how you detect the end of the message stream. Canceling :meth:`recv` is safe. There's no risk of losing the next message. The next invocation of :meth:`recv` will return it. This makes it possible to enforce a timeout by wrapping :meth:`recv` in :func:`~asyncio.timeout` or :func:`~asyncio.wait_for`. Returns: A string (:class:`str`) for a Text_ frame. 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 Raises: ConnectionClosed: When the connection is closed. RuntimeError: If two coroutines call :meth:`recv` concurrently. NzPcannot call recv while another coroutine is already waiting for the next messager) return_when)rg RuntimeErrorlenrfr>rbrGwaitrFIRST_COMPLETEDrrr= ensure_openpopleftrh set_result)rmpop_message_waitermessages rnrzWebSocketCommonProtocol.recvs,<  # # /: $-- A%7;yy7N7N7P '9D $ 0ll')@)@A ' 7 7 ,0( &**,##**,,,-$-- A%2--'')  # # /  $ $ / / 5'+D $5 ,0(-sCAD<4D.D, D. 7D<D:D<"A D<,D.. D77D<cK|jd{|j4tj|jd{|j4t |t t ttfr*t|\}}|jd||d{yt |tr tdt |trttt|}t!|} t#|}t|\}}|j&j)|_ |jd||d{|D]?}t|\}}||k7r td|jdt*|d{A|jdt*dd{ |jj7dd|_yt |t8r%tt:t8tgt<tft?|j@|} tt:t<tgtBtft?|jD|d{}t|\}}|j&j)|_ |jd||d{|23d{}t|\}}||k7r td|jdt*|d{Gtd777v#t$$rYywxYw777#t,tj.f$r!|j1t2j4wxYw#|jj7dd|_wxYw7'#tF$rYywxYw7776|jdt*dd{7n=#t,tj.f$r!|j1t2j4wxYw |jj7dd|_y#|jj7dd|_wxYww)aZ 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 :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 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. NTzdata is a dict-like objectFz data contains inconsistent typesrpz)data must be str, bytes-like, or iterable)$rrirGshield isinstancer.bytes bytearray memoryviewr( write_framer TypeErrorrr r"iternext StopIterationr>rbr ExceptionCancelledErrorfail_connectionrINTERNAL_ERRORrrr rtyperr __anext__StopAsyncIteration)rmropcodedata iter_messagefragmentconfirm_opcode aiter_messages rnsendzWebSocketCommonProtocol.send6sl   --9..!@!@A A A--9 gUIzB C'0LFD""46 6 6 )89 9 *8D>73G=L  -(1LFD.2ii.E.E.GD + 7&&ufd;;;!-AH+7+A(ND%/'(JKK**5'4@@@ A&&tWc::://::4@26/ /D--. d0CCDW ''M "mD12IdOCD'11" "!! (1LFD.2ii.E.E.GD + 7&&ufd;;;'4AA(+7+A(ND%/'(JKK**5'4@@@ GH HO ! B 7 !  <A;w556 $$Y%=%=>  //::4@26/!&  <AA '4&&tWc:::w556 $$Y%=%=>  ;//::4@26///::4@26/svQL2Q L QAQL AQ3 L>-Q,L0L'AL0L* L0%L-&L0+A9Q%AN-N.N2-Q O6N&7O=N,N(N,9O>N*?O QQQ L$!Q#L$$Q'L0*L0-L00:M**M--$NQN N# Q"N##Q&O(N,*O,OO O P/:PP/ #Q/$QQrcK t|j4d{|jt||d{dddd{ t|j4d{|jd{dddd{t j|jd{y777s#1d{7swYxYw#tj $r|j YwxYw777t#1d{7swYxYw#tj tjf$rYwxYw7w)ae Perform the closing handshake. :meth:`close` waits for the other end to complete the handshake and for the TCP connection to terminate. As a consequence, there's no need to await :meth:`wait_closed` after :meth:`close`. :meth:`close` is idempotent: it doesn't do anything once the connection is closed. Wrapping :func:`close` in :func:`~asyncio.create_task` is safe, given that errors during connection termination aren't particularly useful. Canceling :meth:`close` is discouraged. If it takes too long, you can set a shorter ``close_timeout``. If you don't want to wait, let the Python process exit, then the OS will take care of closing the TCP connection. Args: code: WebSocket close code. reason: WebSocket close reason. N) rr5write_close_framerrG TimeoutErrorrrrrr)rmrrs rnclosezWebSocketCommonProtocol.closes,8 #&t'9'9: B B,,U4-@AAA B B 't'9'9: . .---- . . nnT778881 BA B B B B## #  "  #  .- . . . .$$g&<&<=    9sE CCCCCC CCCD/D0D3D DD  DDD"E :E;E CCCC C CC#D>E DE DD D DD DD#EE EE c^Ktj|jd{y7w)a9 Wait until the connection is closed. This coroutine is identical to the :attr:`closed` attribute, except it can be awaited. This can make it easier to detect connection termination, regardless of its cause, in tasks that interact with the WebSocket connection. N)rGrrcrs rn wait_closedz#WebSocketCommonProtocol.wait_closed s nnT88999s #-+-c K|jd{| t|}||jvr td|||jvr;t j dt jd}|,||jvr;|jj}tj}||f|j|<|jdt|d{tj|S77w)aW Send a Ping_. .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2 A ping may serve as a keepalive, as a check that the remote endpoint received all messages up to this point, or to measure :attr:`latency`. Canceling :meth:`ping` is discouraged. If :meth:`ping` doesn't return immediately, it means the write buffer is full. If you don't want to wait, you should close the connection. Canceling the :class:`~asyncio.Future` returned by :meth:`ping` has no effect. Args: data: Payload of the ping. A string 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. RuntimeError: If another ping was sent with the same data and the corresponding pong wasn't received yet. Nz-already waiting for a pong with the same dataz!Ir1T)rr'rjrstructpackrandom getrandbitsr>rbtime perf_counterrrrGr)rmr pong_waiterping_timestamps rnpingzWebSocketCommonProtocol.pingsJ    %D 4:: NO Olddjj0;;tV%7%7%;K|jtjurR|jj r7t j |jd{|jy|jtjur|j|jtjur7t j |jd{|j|jtjusJtd77?w)z Check that the WebSocket connection is open. Raise :exc:`~websockets.exceptions.ConnectionClosed` if it isn't. Nz*WebSocket connection isn't established yet) r\r!rrrrrGrrrrCLOSINGr[rrs rnrz#WebSocketCommonProtocol.ensure_opens :: #&&++-nnT%?%?@@@0022 :: %,,. . :: & ..!;!;< < <,,. .zzU-----GHH'A =s%ADDA?DD>DDcK |jd{}|y|jt|j|jk\rq|jj |_ tj|j d{d|_t|j|jk\rq|jj||j"|jjdd|_ 77{#d|_wxYw#tj$r }||_ d}~wt$r0}||_ |jt j"Yd}~yd}~wt$t&t(t*j,f$r0}||_ |jt j.Yd}~yd}~wt0$r0}||_ |jt j2Yd}~yd}~wt4$r0}||_ |jt j6Yd}~yd}~wt8$rM}|j:j=dd||_ |jt j>Yd}~yd}~wwxYww)z Read incoming messages and put them in a queue. This coroutine runs in a task until the closing handshake is started. TNzdata transfer failedexc_info) read_messager7rrfr>rbrhrGrappendrgrrrlrrrPROTOCOL_ERRORConnectionErrorrEOFErrorsslSSLErrorrUnicodeDecodeError INVALID_DATArMESSAGE_TOO_BIGrr2errorr)rmrr~s rnrz%WebSocketCommonProtocol.transfer_datas= ; $ 1 1 33?>>-dmm,>37993J3J3L0<")..1I1I"JJJ7;D4 dmm,> $$W-++7,,77=/3D,-3K7;D4%% %(D "  ;%(D "  !9!9 : :xF =&)D "  !;!; < <! 9%(D "  !7!7 8 8 <%(D "  !:!: ; ; ; KK  4t  D%(D "  !9!9 : : ;sJDD DJA D."DD D)D?A D D DDJ-D55 J&E,'J,&J&F=8J= J &G4/J4 J&H+&J+ J7AI?:J?JJcK|j|jd{}|y|jtk(rd}n!|jtk(rd}n t d|j r(|r|jjS|jSg|j|r1tjd}|ddfd }ndfd }ndfd }ndfd }|||j sZ|jd{}| t d |jtk7r t d|||j sZ|rdjSdjS7V7kw)z Read a single message from the connection. Re-assemble data frames if the message is fragmented. Return :obj:`None` when the closing handshake is started. )r6NTFzunexpected opcodezutf-8strict)errorscpjj|j|jyr)rdecoderfin)framedecoder fragmentss rnrz4WebSocketCommonProtocol.read_message..appends$$$W^^EJJ %JKrpcjj|j|jt t sJt |jzyr)rrrrrintr)rrrr6s rnrz4WebSocketCommonProtocol.read_message..appendsF$$W^^EJJ %JK%h444EJJ/Hrpc<j|jyr)rr)rrs rnrz4WebSocketCommonProtocol.read_message..appends$$UZZ0rpcj|jttsJt |jzyr)rrrrr)rrr6s rnrz4WebSocketCommonProtocol.read_message..append%s7$$UZZ0%h444EJJ/Hrpzincomplete fragmented messagerrp)rr&returnNone) read_data_framer6rrrrrrrcodecsgetincrementaldecoderrjoin)rmrtextdecoder_factoryrrrr6s @@@rnrz$WebSocketCommonProtocol.read_messagesj**DMM*BB = <<7 "D \\Y &D 34 4 99*.5::$$& >EJJ >!# == $::7CO%X6GL 001 0 u ))...AAE}#$CDD||w&#$788 5M )))))44)))44}CnBs) FE;C,FE>AF%F>FcK |j|d{}|jtk(rgtj|j |_|jd|_ |j|j |j d{y|jtk(rA|jtjur |j|j d{n|jt k(r|j |j"vrt%j&}d}g}|j"j)D]X\}\}}|j+||j-s|j/||z ||j k(sN||z |_n t3d|D]}|j"|=n|S779#t$rYywxYw7#t$rY$wxYww)z Read a single data frame from the connection. Process control frames received before the next data frame. Return :obj:`None` if a close frame is encountered before any data frame. NFz!solicited pong not found in pings) read_framerrrparserr_r`rarrrr\r!rrrrjrritemsrrrrrkAssertionError)rmr6rpong_timestampping_idping_idsrrs rnrz'WebSocketCommonProtocol.read_data_frame7s//(33E||x'#(++ejj"9??.05D-00%**MMM(::+"ii 333 (::+%)%6%6%8N#G!HBF**BRBRBTR>!>+~ 0*//1'22>N3RS"ejj0+9N+JDL! R--PQQ#+0 JJw/0  g3N'4+sG-GAG-()G G G 0G-G%G&G*B+G-2G- G GG-GG-G G*'G-)G**G-cKtj|jj|j ||j d{}|j r|jj d||S7.w)z; Read a single frame from the connection. )maskr6r]Nz< %s)r&readrV readexactlyr,r]rQr2)rmr6rs rnrz"WebSocketCommonProtocol.read_framevsc jj KK # #^^#    :: KK  fe ,  sAA9A7 /A9ct|t||}|jr|jjd||j |j j|j |jy)Nz> %s)rr])r&r rQr2writerzr,r])rmrrrrs rnwrite_frame_syncz(WebSocketCommonProtocol.write_frame_syncs[c6&>40 :: KK  fe , NN   rpc.K |j4d{|jd{dddd{y7-77 #1d{7swYyxYw#t$r,|j|j d{7YywxYwwr)rZrrrrrs rndrainzWebSocketCommonProtocol.drains %'' $ $kkm## $ $ $# $ $ $ $ %  """$ $ $  %sBAAAAAA AAABAAAAA AABA,B B  BBBB_statecK|j|ur#td|jjd|j||||j d{y7w)Nz#Cannot write to a WebSocket in the z state)r\rnamerr)rmrrrr s rnrz#WebSocketCommonProtocol.write_framesY ::V #5djjoo5FfM  c640jjlsAA"A A"cxK|jtjurtj|_|jr|j j d||_|jd|_||j}|jdt|tjd{yy7w)z Write a close frame if and only if the connection state is OPEN. This dedicated coroutine must be used for writing close frames to ensure that at most one close frame is sent on a given connection. = connection is CLOSINGNTr) r\r!rrrQr2r`r_ra serializerr)rmrrs rnrz)WebSocketCommonProtocol.write_close_frames :: #DJzz !!";<#DO*,0)|(""44 "N N N $ OsB/B:1B82B:cK|jy tj|jd{|jj d|j d{}|j T t|j 4d{|d{dddd{|jj d77g7>767(#1d{7swY8xYw#tj$rJ|jr|jj d|jtjdYywxYw#t$rYyt$r |jjddYywxYww) a> Send a Ping frame and wait for a Pong frame at regular intervals. This coroutine exits when the connection terminates and one of the following happens: - :meth:`ping` raises :exc:`ConnectionClosed`, or - :meth:`close_connection` cancels :attr:`keepalive_ping_task`. NTz% sending keepalive pingz% received keepalive pongz&- timed out waiting for keepalive pongzkeepalive ping timeoutzkeepalive ping failedr)r3rGr|r2rQrr4rrrrrrrr)rmrs rnrz&WebSocketCommonProtocol.keepalive_pings`    %  FmmD$6$6777 !!"<=$(IIK/ $$0#243D3D#E.. #.-- ..  ))*EF70. . ....#//:: KK--.VW,,%444    F KK  5  E FsF#E C 2E 'C(E 9C,CC,CCC! C,,C-C, E E C,CC,C)C C)%C,,AE E FE  E E?F%E?<F>E??FcK t|dr |jd{t|dr|jj |j ret|drY|jd{r |jd{y|jr|jjd|jjr|jr|jjd |jj|jd{r |jd{y|jr|jjd|jd{y7j#tj$rY~wxYw717#ttf$rYwxYw777A#|jd{7wxYww)a 7.1.1. Close the WebSocket Connection When the opening handshake succeeds, :meth:`connection_open` starts this coroutine in a task. It waits for the data transfer phase to complete then it closes the TCP connection cleanly. When the opening handshake fails, :meth:`fail_connection` does the same. There's no data transfer phase in that case. rNr!- timed out waiting for TCP closezx half-closing TCP connection)hasattrrrGrrcancelr,wait_for_connection_lostclose_transportrQr2rz can_write_eof write_eofOSErrorrrs rnrz(WebSocketCommonProtocol.close_connections( )t121111 t23((//1~~'$0D"E668882&&( ( (1::KK%%&IJ~~++-::KK%%&EF NN,,.66888&&( ( ( ::KK%%&IJ &&( ( (I2--94 ) .9 ) ($&&( ( (sG& GF F F AG6F'7G<G&F*G&A(G>F-G+G,G1G&GG& 'G1G&GG& F F$ G#F$$G*G&-F?<G>F??GG&G&G#GG##G&c2K|jjr|jjry|jr|j j d|jj |jd{ry|jr|j j d|jr|j j d|jj|jd{y77w)z, Close the TCP connection. Nzx closing TCP connectionr(zx aborting TCP connection) rcrrrzr{rQr2rr+abortrs rnr,z'WebSocketCommonProtocol.close_transport%s  & & + + -$..2K2K2M  :: KK  8 9 ..0 0 0  :: KK  A B :: KK  9 : ++--- 1 .s%B D D BD DDDcK|jjsV t|j4d{t j |jd{dddd{|jjS7U707"#1d{7swY2xYw#tj $rYJwxYww)z Wait until the TCP connection is closed or ``self.close_timeout`` elapses. Return :obj:`True` if the connection is closed and :obj:`False` otherwise. N)rcrrrr5rGrrrs rnr+z0WebSocketCommonProtocol.wait_for_connection_lostBs**//1 *4+=+=>FF!..)D)DEEEFF**//11FEFFFF''  sCB(B B(#BBB# B(.B/B(3C B(BB(B%B B%!B((B>;C=B>>Ccx|jr|jjd|t|dr|jj |t j k7r|jtjurt||}tj|_|jr|jjd|jJ||_ |jdt|j!t|ds/|j"j%|j'|_yy)a 7.1.7. Fail the WebSocket Connection This requires: 1. Stopping all processing of incoming data, which means cancelling :attr:`transfer_data_task`. The close code will be 1006 unless a close frame was received earlier. 2. Sending a close frame with an appropriate code if the opening handshake succeeded and the other side is likely to process it. 3. Closing the connection. :meth:`close_connection` takes care of this once :attr:`transfer_data_task` exits after being canceled. (The specification describes these steps in the opposite order.) z!! failing connection with code %drr$NTr)rQr2r)rr*rrr\r!rrrr_r`rrr%r>rrr)rmrrrs rnrz'WebSocketCommonProtocol.fail_connectionUs. :: KK  A4 H 4- .  # # * * , 9-- -$** 2J$'EDJzz !!";< ??* **#DO  ! !$%//2C Dt45)-)>)>t?T?T?V)WD &6rpc|jtjusJ|j}|jj D]&\}}|j ||j(y)z Raise ConnectionClosed in pending keepalive pings. They'll never receive a pong once the connection is closed. N)r\r!rrrjvalues set_exceptionr*)rmr~r_ping_timestamps rn abort_pingsz#WebSocketCommonProtocol.abort_pingssezzU\\)))((*,0JJ,=,=,? ! (K  % %c *     !rpcttj|}|j|j||_|j j|y)a Configure write buffer limits. The high-water limit is defined by ``self.write_limit``. The low-water limit currently defaults to ``self.write_limit // 4`` in :meth:`~asyncio.WriteTransport.set_write_buffer_limits`, which should be all right for reasonable use cases of this library. This is the earliest point where we can get hold of the transport, which means it's the best point for configuring it. N)r rG Transportset_write_buffer_limitsr9rzrV set_transportrs rnconnection_madez'WebSocketCommonProtocol.connection_madesE**I6 ))$*:*:;" !!),rpctj|_|jj d|j |j jd |j8||jjn|jj||jsy|j}|yd|_ |jry||jdy|j|y)z= 7.1.4. The WebSocket Connection is Closed. z= connection is CLOSEDN)r!rr\r2rQr8rcrrVfeed_eofr6rWrXrr)rmr~rvs rnconnection_lostz'WebSocketCommonProtocol.connection_losts \\  23  ##..t4 {{&;KK((*KK--c2<<''F~!%D {{}{!!$'$$S)rpc.|jrJd|_y)NT)rWrs rn pause_writingz%WebSocketCommonProtocol.pause_writings<< rpc|jsJd|_|j}|*d|_|js|jdyyy)NF)rWrXrrrrus rnresume_writingz&WebSocketCommonProtocol.resume_writingsO||| ##  !%D ;;=!!$'! rpc:|jj|yr)rV feed_datars rn data_receivedz%WebSocketCommonProtocol.data_receiveds d#rpc8|jjy)a Close the transport after receiving EOF. The WebSocket protocol has its own closing handshake: endpoints close the TCP or TLS connection after sending and receiving a close frame. As a consequence, they never need to write after receiving EOF, so there's no reason to keep the transport open by returning :obj:`True`. Besides, that doesn't work on TLS connections. N)rVr?rs rn eof_receivedz$WebSocketCommonProtocol.eof_receiveds rp)r2zLoggerLike | Noner3 float | Noner4rJr5rJr6 int | Noner7rKr8rr9rr: str | Noner;rKr< bool | Noner=r+r>z asyncio.AbstractEventLoop | Noner?rJrr)rr)rrL)rrK)rrM)rr )rr+)rzAsyncIterator[Data])rr")rz+Data | Iterable[Data] | AsyncIterable[Data]rr)rrrr.rrr)r Data | NonerzAwaitable[float])rp)rr"rr)rr)rrN)r6rKrz Frame | None)r6rKrr&)rr+rrrrrr) rr+rrrrr rrr)rrrz bytes | Nonerr)rzzasyncio.BaseTransportrr)r~zException | Nonerr)rrrr)6__name__ __module__ __qualname____doc____annotations__r/rorwrrpropertyr:r;r<rrrrrrrrrrNORMAL_CLOSURErrrrrrrrrrrrr!rrrrrr,r+rrr8r=r@rBrDrGrIrprnr)r)6s_HOD# %)&(%'&*$ $ "!15 $#O7"O7$ O7 # O7 $ O7O7O7O7O7O7O7O7O7 /!O7"#O7$ %O7d # T&   88&88& O O**(("**""L\]I<]I ]IB,,595959  59n :9+v46. IDD;LG5R=~   % EJJJ  !$ ,1 >A   O2+FZ4)l.:2*..<X<X<X  <X|!(-*$*L($ rpc t|ttttfs t d|r#t jdddkr tdg}t|\}}|D]z}|jtjur |j;|rtd}j|n|j j#dg |j%d||||rr t3d |yy#t&$r{}|r$td }||_j|nJ|j j#d t+j,t/||d j1Yd}~d}~wwxYw) 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.legacy.protocol.WebSocketCommonProtocol.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. zdata must be str or bytes-likeNr ) z.raise_exceptions requires at least Python 3.11zsending a fragmented messagez/skipped broadcast: sending a fragmented messageTzfailed to write messagez.skipped broadcast: failed to write message: %srzskipped broadcast)rr.rrrrsys version_info ValueErrorr(r\r!rrirrr2warningrrr tracebackformat_exception_onlyrstripExceptionGroup) websocketsrraise_exceptions exceptionsrrrBrywrite_exceptions rn broadcastrf sod gUIzB C899   BQ ' )MN N (LFD ??%** ,   / / ;()GH !!),  ((E    & &tVT :>J0*==' ()BC &5 #!!),  ((D33_-'   s C00 E49A0E//E4zwebsockets.legacy.server)F)rbz!Iterable[WebSocketCommonProtocol]rr"rcr+rr)? __future__rrGr rdrLrrrrZrr^rIrDcollections.abcrrrrrtypingr r r r asyncio.compatibilityrdatastructuresrrdrrrrrrr]rframesrrrrrrrrrr protocolr!r"r#r$framingr&r'r(__all__Protocolr)rfrPrVrprnrqs"   VV--3$#   2266 % %Jg..Jl.#\>1\> \>\> \>@2 rp