K iiiddlmZddlZddlZddlZddlZddlZddlZddlZ ddl Z ddl m Z m Z mZddlmZddlmZmZmZddlmZddlmZmZdd lmZmZmZmZmZdd l m!Z!m"Z"dd l#m$Z$dd l%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,dd l-m.Z.ddlm/Z/m0Z0m1Z1m2Z2ddl3m4Z4m5Z5ddlm6Z6m7Z7ddl8m9Z9m:Z:ddl;mZ>gdZ?Gdde>Z@GddZAeAZB d ddZCy)) annotationsN) AsyncIterator GeneratorSequence) TracebackType)AnyCallablecast)asyncio_timeout)Headers HeadersLike) InvalidHeaderInvalidHeaderValueInvalidMessageNegotiationError SecurityError)ClientExtensionFactory Extension) enable_client_permessage_deflate)build_authorization_basicbuild_extension build_hostbuild_subprotocolparse_extensionparse_subprotocolvalidate_subprotocols) USER_AGENT)ExtensionHeader LoggerLikeOrigin Subprotocol) WebSocketURI parse_uri)InvalidStatusCodeRedirectHandshake) build_requestcheck_response) read_response)WebSocketCommonProtocol)connect unix_connectWebSocketClientProtocolceZdZdZdZdZddddded d fdZd dZddZ e dd Z e dd Z d dd Z xZS)r.a WebSocket client connection. :class:`WebSocketClientProtocol` provides :meth:`recv` and :meth:`send` coroutines for receiving and sending messages. It supports asynchronous iteration to receive messages:: async for message in websocket: await process(message) The iterator exits normally when the connection is closed with close code 1000 (OK) or 1001 (going away) or without a close code. It raises a :exc:`~websockets.exceptions.ConnectionClosedError` when the connection is closed with any other code. See :func:`connect` for the documentation of ``logger``, ``origin``, ``extensions``, ``subprotocols``, ``extra_headers``, and ``user_agent_header``. See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``, ``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``. TclientN)loggerorigin extensions subprotocols extra_headersuser_agent_headerc |tjd}t| dd|i|||_||_||_||_||_y)Nwebsockets.clientr1) logging getLoggersuper__init__r2available_extensionsavailable_subprotocolsr5r6) selfr1r2r3r4r5r6kwargs __class__s ^/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/websockets/legacy/client.pyr=z WebSocketClientProtocol.__init__MsW >&&':;F 11&1 $.!&2#*!2cT||_||_|jrQ|jjd||j D]"\}}|jjd||$d|d}|t |z }|j j|jy)zF Write request line and headers to the HTTP request. z> GET %s HTTP/1.1z> %s: %szGET z HTTP/1.1 N) pathrequest_headersdebugr1 raw_itemsstr transportwriteencode)r@rFheaderskeyvaluerequests rCwrite_http_requestz*WebSocketClientProtocol.write_http_requestas  & :: KK  14 8%//1 : U !!*c59 : m,3w< W^^-.rDcrK t|jd{\}}}|jrR|j j d|||j D]"\}}|j j d||$||_||jfS7{#t$r}td|d}~wwxYww)a< Read status line and headers from the HTTP response. If the response contains a body, it may be read from ``self.reader`` after this coroutine returns. Raises: InvalidMessage: If the HTTP message is malformed or isn't an HTTP/1.1 GET response. Nz%did not receive a valid HTTP responsez< HTTP/1.1 %d %sz< %s: %s)r*reader ExceptionrrHr1rIresponse_headers)r@ status_codereasonrNexcrOrPs rCread_http_responsez*WebSocketClientProtocol.read_http_responseus S1>t{{1K+K (K :: KK  0+v F%//1 : U !!*c59 :!(D1111,L S !HIs R Ss8B7BBBA3B7B B4# B//B44B7cdg}|jd}|r| tdt|Dcgc] }t|c}g}|D]Q\}}|D]7}|j|k7r |j ||} |j | Atd|d||Scc}w#t$rY^wxYw)a/ Handle the Sec-WebSocket-Extensions HTTP response header. Check that each extension is supported, as well as its parameters. Return the list of accepted extensions. Raise :exc:`~websockets.exceptions.InvalidHandshake` to abort the connection. :rfc:`6455` leaves the rules up to the specification of each :extension. To provide this level of flexibility, for each extension accepted by the server, we check for a match with each extension available in the client configuration. If no match is found, an exception is raised. If several variants of the same extension are accepted by the server, it may be configured several times, which won't make sense in general. Extensions must implement their own requirements. For this purpose, the list of previously accepted extensions is provided. Other requirements, for example related to mandatory extensions or the order of extensions, may be implemented by overriding this method. Sec-WebSocket-Extensionszno extensions supportedzUnsupported extension: name = z , params = )get_allrsumrnameprocess_response_paramsappend) rNr>accepted_extensions header_values header_valueparsed_header_valuesr_response_paramsextension_factory extensions rCprocess_extensionsz*WebSocketClientProtocol.process_extensionss>02(BC #+&'@AA:=CPQ<.QSU; *> %o)=%(--5 !$5$M$M+-@% (..y9#,+""&{?2CE/ 8#"?R,! !sB$B## B/.B/c d}|jd}|rs| tdt|Dcgc] }t|c}g}t |dkDrt dddj ||d}||vrtd||Scc}w) z Handle the Sec-WebSocket-Protocol HTTP response header. Check that it contains exactly one supported subprotocol. Return the selected subprotocol. NSec-WebSocket-Protocolzno subprotocols supportedr%zmultiple values: z, rzunsupported subprotocol: )r]rr^rlenrjoin)rNr? subprotocolrcrdres rCprocess_subprotocolz+WebSocketClientProtocol.process_subprotocols+/ (@A %-&'BCC:=ERS\"<0SUW; '(1,(,' 2F(G'HI /q1K"88&)B;-'PQQTsB cKt}t|j|j|j|d<|j rt |j |d<|||d<t|}|8t|Dcgc]}|j|jf c}} | |d<|t|} | |d<|j|j|j|jr|jd|j|j!|j"||j%d{\} } | dvrd | vr t'd t)| d | d k7r t+| | t-| ||j/| ||_|j3| ||_|j7ycc}w7w) a9 Perform the client side of the opening handshake. Args: wsuri: URI of the WebSocket server. origin: Value of the ``Origin`` header. extensions: List of supported extensions, in order in which they should be negotiated and run. subprotocols: List of supported subprotocols, in order of decreasing preference. extra_headers: Arbitrary HTTP headers to add to the handshake request. Raises: InvalidHandshake: If the handshake fails. Host AuthorizationNr!r\rkz User-Agent)i-i.i/i3i4Locatione)r rhostportsecure user_inforr(rr_get_request_paramsrr5updater6 setdefaultrR resource_namerZrr'r&r)rir3rornconnection_open) r@wsurir2r>r?r5rGrOrgextensions_headerprotocol_headerrWrVs rC handshakez!WebSocketClientProtocol.handshakes0")",UZZU\\"R ??/H0OO ,  (.OH %O,  + /.B)'++->-Q-Q-ST!  ;LO6 7 ! -/0FGO8GO4 5    )  " "4#5#5 6  ! !  & &|T5K5K L  3 3_E.2.E.E.G(G% % 3 3!11#J//#$4Z$@A A C #K1AB B'-11 2  33 4  K&)Hs A7G9#F=BG8G9B G)r1LoggerLike | Noner2 Origin | Noner3'Sequence[ClientExtensionFactory] | Noner4Sequence[Subprotocol] | Noner5HeadersLike | Noner6 str | NonerArreturnNone)rFrJrNr rr)rztuple[int, Headers])rNr r>rrzlist[Extension])rNr r?rrzSubprotocol | None)NNNN) r~r#r2rr>rr?rr5rrr)__name__ __module__ __qualname____doc__ is_clientsiderr=rRrZ staticmethodriror __classcell__)rBs@rCr.r./s=4I D %) $>B59,0(23"3 3 < 3 3 3*3&33 3(/(24F#F#EF# F#F#P""2N" ""N!%HL?C,0 MMMF M != M * M MrDr.ceZdZdZeej jddZddddddde dddddd d d d  dd Z dd Z e ej jddZ e ej jddZe ej jddZe ej jddZddZddZ ddZd dZddZeZy)!Connecta Connect to the WebSocket server at ``uri``. Awaiting :func:`connect` yields a :class:`WebSocketClientProtocol` which can then be used to send and receive messages. :func:`connect` can be used as a asynchronous context manager:: async with connect(...) as websocket: ... The connection is closed automatically when exiting the context. :func:`connect` can be used as an infinite asynchronous iterator to reconnect automatically on errors:: async for websocket in connect(...): try: ... except websockets.exceptions.ConnectionClosed: continue The connection is closed automatically after each iteration of the loop. If an error occurs while establishing the connection, :func:`connect` retries with exponential backoff. The backoff delay starts at three seconds and increases up to one minute. If an error occurs in the body of the loop, you can handle the exception and :func:`connect` will reconnect with the next iteration; or you can let the exception bubble up and break out of the loop. This lets you decide which errors trigger a reconnection and which errors are fatal. Args: uri: URI of the WebSocket server. create_protocol: Factory for the :class:`asyncio.Protocol` managing the connection. It defaults to :class:`WebSocketClientProtocol`. Set it to a wrapper or a subclass to customize connection handling. logger: Logger for this client. It defaults to ``logging.getLogger("websockets.client")``. See the :doc:`logging guide <../../topics/logging>` for details. compression: The "permessage-deflate" extension is enabled by default. Set ``compression`` to :obj:`None` to disable it. See the :doc:`compression guide <../../topics/compression>` for details. origin: Value of the ``Origin`` header, for servers that require it. extensions: List of supported extensions, in order in which they should be negotiated and run. subprotocols: List of supported subprotocols, in order of decreasing preference. extra_headers: Arbitrary HTTP headers to add to the handshake request. user_agent_header: Value of the ``User-Agent`` request header. It defaults to ``"Python/x.y.z websockets/X.Y"``. Setting it to :obj:`None` removes the header. open_timeout: Timeout for opening the connection in seconds. :obj:`None` disables the timeout. See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``, ``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``. Any other keyword arguments are passed the event loop's :meth:`~asyncio.loop.create_connection` method. For example: * You can set ``ssl`` to a :class:`~ssl.SSLContext` to enforce TLS settings. When connecting to a ``wss://`` URI, if ``ssl`` isn't provided, a TLS context is created with :func:`~ssl.create_default_context`. * You can set ``host`` and ``port`` to connect to a different host and port from those found in ``uri``. This only changes the destination of the TCP connection. The host name from ``uri`` is still used in the TLS handshake for secure connections and in the ``Host`` header. Raises: InvalidURI: If ``uri`` isn't a valid WebSocket URI. OSError: If the TCP connection fails. InvalidHandshake: If the opening handshake fails. ~asyncio.TimeoutError: If the opening handshake times out. WEBSOCKETS_MAX_REDIRECTS10Ndeflate i i)create_protocolr1 compressionr2r3r4r5r6 open_timeout ping_interval ping_timeout close_timeoutmax_size max_queue read_limit write_limitc |jdd}|d}ntjdt| |} |jdd}|t}ntjdt||}|jdd}|jdd}|t j }n|}tjd tt|}|jr|jd d n|jd  td |d k(r t|}n|td|| t|ttdtf|}t!j"|fid|d|d|d|d|d| d| d| d| d|d|d|d|d|j$d|j&d|jd|d|}|jd dr5|jd!d}t!j"|j(||fi|}n|jd"|j$|j&}}n2d#\}}|jd r|jd$|j$|jd|}|jd|}t!j"|j*|||fi|}| |_|t/j0d%}||_||_||_||_y)&Ntimeoutrzrename timeout to close_timeoutklasszrename klass to create_protocol legacy_recvFloopzremove loop argumentsslTzQconnect() received a ssl argument for a ws:// URI, use a wss:// URI to enable TLSrzunsupported compression: .r1r2r3r4r5r6rrrrrrrrurvrwunixrFsock)NNserver_hostnamer8)popwarningswarnDeprecationWarningr.asyncioget_event_loopr$rwr{get ValueErrorrrr r functoolspartialrurvcreate_unix_connectioncreate_connectionrr:r;r1_create_connection_uri_wsuri)r@urirr1rr2r3r4r5r6rrrrrrrrrArrr_looprr~factoryrFrrurvs rCr=zConnect.__init__s=.!' 9d ; ?G MM;=O P  #M7=jj$6O =+E MM;=O P  "#O#JJ}e< 39**VT2J =))+DD MM02D E# <<   eT * ZZ  *1  ) #9*EJ  $8 FG G  # !, /x-D(DEW##    "  &  (  0 ( & (    " $  ! "<<# $$% &' , ::fe $%zz&$7D ) 1 1++Wd!>D!  zz&!)"ZZd( d::e$%%&7D::fd+D::fd+D ) 1 1&&t!?E! ) >&&':;F #4  rDc |j}|j}tjj ||}t |}|j r|j s td|j |j k(xr4|j|jk(xr|j|jk(}|s|jjd}|j sA|j r5d|jd<|jjjddtj|j g|jit#|j|j|j}tj|jj g||j|jfi|jj|_ ||_||_y)Nzredirect from WSS to WSrTrwr)rurv)rrurllibparseurljoinr$rwrrurvrargskeywordsr{rrfuncdict)r@rold_uri old_wsurinew_uri new_wsuri same_originrs rChandle_redirectzConnect.handle_redirect"s))KK ,,&&w4g&    I$4$4 9: :    0 0 0 1)..0 1)..0 --2215G## (8(8-1  *''00;;E4H'' w''inn9>>RG '0&7&7'',,'9>>9>>:'))22'D #  rD WEBSOCKETS_BACKOFF_INITIAL_DELAY5WEBSOCKETS_BACKOFF_MIN_DELAYz3.1WEBSOCKETS_BACKOFF_MAX_DELAYz90.0WEBSOCKETS_BACKOFF_FACTORz1.618c pK|j|jz } |4d{}|dddd{|j}.7&7#1d{7swY#xYw#t$rE}||jk(rtj|jz}|j j d|tjt||djtj|d{7n{|j j dt|tjt||djtjt|d{7||jz}t||j}Yd}~d}~wwxYww)Nz0connect failed; reconnecting in %.1f seconds: %srz0connect failed again; retrying in %d seconds: %s) BACKOFF_MINBACKOFF_FACTORrUrandomBACKOFF_INITIALr1info tracebackformat_exception_onlytypestriprsleepintmin BACKOFF_MAX)r@ backoff_delayprotocolrY initial_delays rC __aiter__zConnect.__aiter__Tso((4+>+>>  1##8"N##8!% 0 0 =##### !D$4$44$*MMOd6J6J$JMKK$$J%!77S 3GJPPR  "-- 666KK$$JM*!77S 3GJPPR  "--M(:;;; -0C0C C #M43C3C D / sF6A$A A$A A$A A$ F6 A$ A$A!A A!A$$ F3.BF.DA;F.=F>*F.(F6.F33F6c"K|d{S7wNr9r@s rC __aenter__zConnect.__aenter__xszzs  cTK|jjd{y7wr)rclose)r@exc_type exc_valuers rC __aexit__zConnect.__aexit__{s mm!!###s (&(c>|jjSr)__await_impl__ __await__rs rCrzConnect.__await__s""$..00rDc Kt|j4d{t|jD]}|j d{\}} |j |j |j|j|j|jd{||_ |ccdddd{St)d77707#t$rN}|j|jd{7|j|j Yd}~d}~wt"t$j&f$r+|j|jd{7wxYw#1d{7swYyxYww)N)r2r>r?r5ztoo many redirects)r rrangeMAX_REDIRECTS_ALLOWEDrrrr2r>r?r5rr'fail_connection wait_closedrrrUrCancelledErrorr)r@ _redirects _transportrrYs rCrzConnect.__await_impl__sa"4#4#45 : :#D$>$>? : -1-D-D-F'F$ H$",, '-5-J-J/7/N/N&.&<&< -"%-DM#O- : : : :.$$8991 :'F  :)2,,."..000((11!7#9#9:,,."..000! : : :sFC F,E1 C E1A C C!C% E1/ F;C<F E1 FE1CF E.#D'D  D'"E1'?E.&E) 'E..E11F7E: 8F?F)&rrJrz-Callable[..., WebSocketClientProtocol] | Noner1rrrr2rr3rr4rr5rr6rr float | Nonerrrrrrr int | NonerrrrrrrArrr)rrJrr)rz&AsyncIterator[WebSocketClientProtocol])rr.)rztype[BaseException] | NonerzBaseException | NonerzTracebackType | Nonerr)rz-Generator[Any, None, WebSocketClientProtocol])rrrrrosenvironrrrr=rfloatrrrrrrrrr__iter__r9rDrCrrMsQf  /I4 PQ JN$("+ $>B59,0(2%'&(%'&*$ $ '} }G } " }  }}<}3}*}&}#}$}#}$} !}"#}$%}&'}()}* +}~) ZBJJNN+MsSTO 'EuMNK 'EvNOK2::>>*EwOPN 1H$,$($( $  $1::HrDrc  td||dd|S)a Similar to :func:`connect`, but for connecting to a Unix socket. This function builds upon the event loop's :meth:`~asyncio.loop.create_unix_connection` method. It is only available on Unix. It's mainly useful for debugging servers listening on Unix sockets. Args: path: File system path to the Unix socket. uri: URI of the WebSocket server; the host is used in the TLS handshake for secure connections and in the ``Host`` header. T)rrFrr9)r,)rFrrAs rCr-r-s*  ;sD ;F ;;rD)Nzws://localhost/)rFrrrJrArrr)D __future__rrrr:rrr urllib.parserrcollections.abcrrrtypesrtypingrr r asyncio.compatibilityr datastructuresr r exceptionsrrrrrr3rrextensions.permessage_deflaterrNrrrrrrrhttp11rrr r!r"rr#r$r&r'rr(r)httpr*rr+__all__r.rr,r-r9rDrCr s" >>&&31;L EE)<4- A[5[|YYx  < < <<