K i{,ddlmZddlZddlZddlZddlZddlZddlZddl Z ddl m Z m Z mZddlmZddlmZmZmZmZddlmZmZddlmZmZdd lmZmZmZm Z m!Z!m"Z"dd l#m$Z$dd l%m&Z&dd l'm(Z(m)Z)m*Z*dd l+m,Z,m-Z-ddl.m/Z/m0Z0ddl1m2Z2ddlm3Z3m4Z4m5Z5ddl6m7Z7m8Z8m9Z9m:Z:m;Z;ddlZ>ddl?m@Z@gdZAeBejjddZEGdde@ZFd)dZGGddZH d* d+dZI ddlJmKZKddlLm7ZMeKjeKjeKjeKjd ZPd!d"d!d"d ZQ d,d#ZR d- d.d%ZTGd&d'ejZV d- d/d(ZWy#eS$r d,d$ZRYEwxYw)0) annotationsN) AsyncIterator GeneratorSequence) TracebackType)AnyCallableLiteralcast)ClientProtocolbackoff)Headers HeadersLike)InvalidMessageInvalidProxyMessageInvalidProxyStatus InvalidStatus ProxyError SecurityError)ClientExtensionFactory) enable_client_permessage_deflate)build_authorization_basic build_hostvalidate_subprotocols) USER_AGENTResponse) CONNECTINGEvent) StreamReader) LoggerLikeOrigin Subprotocol)Proxy WebSocketURI get_proxy parse_proxy parse_uri) TimeoutErrorasyncio_timeout) Connection)connect unix_connectClientConnectionWEBSOCKETS_MAX_REDIRECTS10cpeZdZdZdddddd d fdZdef d d Zd fd ZxZS)r/a$ :mod:`asyncio` implementation of a WebSocket client connection. :class:`ClientConnection` 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. The ``ping_interval``, ``ping_timeout``, ``close_timeout``, ``max_queue``, and ``write_limit`` arguments have the same meaning as in :func:`connect`. Args: protocol: Sans-I/O connection.   ping_interval ping_timeout close_timeout max_queue write_limitcr|t||||||||jj|_y)Nr7)super__init__loop create_future response_rcvd)selfprotocolr8r9r:r;r< __class__s _/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/websockets/asyncio/client.pyr?zClientConnection.__init__BsC   '%'#  48993J3J3LNcK|jt4d{|jj|_|%|jj j ||&|jj jd||jj|jdddd{tj|j|jgtjd{|jj|jjy77w#1d{7swYxYw7Kw)z1 Perform the opening handshake. )expected_stateN User-Agent) return_when) send_contextrrDr-requestheadersupdate setdefault send_requestasynciowaitrBconnection_lost_waiterFIRST_COMPLETED handshake_exc)rCadditional_headersuser_agent_headers rF handshakezClientConnection.handshakeWs$$J$? 5 5==002DL!- $$++,>? , $$// >OP MM & &t|| 4  5 5ll   ! process_event)rCeventrEs rFr^zClientConnection.process_eventtsI == eX. ..!DM    ) )$ / G !% (rG)rDr r8 float | Noner9r`r:r`r;*int | None | tuple[int | None, int | None]r<int | tuple[int, int | None]returnNone)rWHeadersLike | NonerX str | Nonercrd)r_rrcrd) __name__ __module__ __qualname____doc__r?rrYr^ __classcell__)rEs@rFr/r/)s8')%'&(@B49M M$ M # M $ M>M2M M.26(2...&.  .: ) )rGr/ct|tttjfryt|trt|j t ryt|tr|jjdvry|S)a Determine whether a connection error is retryable or fatal. When reconnecting automatically with ``async for ... in connect(...)``, if a connection attempt fails, :func:`process_exception` is called to determine whether to retry connecting or to raise the exception. This function defines the default behavior, which is to retry on: * :exc:`EOFError`, :exc:`OSError`, :exc:`asyncio.TimeoutError`: network errors; * :exc:`~websockets.exceptions.InvalidStatus` when the status code is 500, 502, 503, or 504: server or proxy errors. All other exceptions are considered fatal. You can change this behavior with the ``process_exception`` argument of :func:`connect`. Return :obj:`None` if the exception is retryable i.e. when the error could be transient and trying to reconnect with the same parameters could succeed. The exception will be logged at the ``INFO`` level. Return an exception, either ``exc`` or a new exception, if the exception is fatal i.e. when trying to reconnect will most likely produce the same error. That exception will be raised, breaking out of the retry loop. N)iiii) r\OSErrorr*rRr __cause__EOFErrorrr[ status_code)excs rFprocess_exceptionrrsc>#w/C/CDE#~&:cmmX+N#}%#,,*B*BG+  JrGceZdZdZdddddededdddddd ddd  dd Zdd Zdd ZddZ ddZ e Z ddZ ddZ ddZy)r-u Connect to the WebSocket server at ``uri``. This coroutine returns a :class:`ClientConnection` instance, which you can use to send and receive messages. :func:`connect` may be used as an asynchronous context manager:: from websockets.asyncio.client import connect 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 If the connection fails with a transient error, it is retried with exponential backoff. If it fails with a fatal error, the exception is raised, breaking out of the loop. The connection is closed automatically after each iteration of the loop. Args: uri: URI of the WebSocket server. 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. 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. additional_headers (HeadersLike | None): 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. proxy: If a proxy is configured, it is used by default. Set ``proxy`` to :obj:`None` to disable the proxy or to the address of a proxy to override the system configuration. See the :doc:`proxy docs <../../topics/proxies>` for details. process_exception: When reconnecting automatically, tell whether an error is transient or fatal. The default behavior is defined by :func:`process_exception`. Refer to its documentation for details. open_timeout: Timeout for opening the connection in seconds. :obj:`None` disables the timeout. 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. :obj:`None` disables the timeout. max_size: Maximum size of incoming messages in bytes. :obj:`None` disables the limit. max_queue: High-water mark of the buffer where frames are received. It defaults to 16 frames. The low-water mark defaults to ``max_queue // 4``. You may pass a ``(high, low)`` tuple to set the high-water and low-water marks. If you want to disable flow control entirely, you may set it to ``None``, although that's a bad idea. write_limit: High-water mark of write buffer in bytes. It is passed to :meth:`~asyncio.WriteTransport.set_write_buffer_limits`. It defaults to 32 KiB. You may pass a ``(high, low)`` tuple to set the high-water and low-water marks. logger: Logger for this client. It defaults to ``logging.getLogger("websockets.client")``. See the :doc:`logging guide <../../topics/logging>` for details. create_connection: Factory for the :class:`ClientConnection` managing the connection. Set it to a wrapper or a subclass to customize connection handling. Any other keyword arguments are passed to 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 ``server_hostname`` to override the host name from ``uri`` in the TLS handshake. * 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. * You can set ``sock`` to provide a preexisting TCP socket. You may call :func:`socket.create_connection` (not to be confused with the event loop's :meth:`~asyncio.loop.create_connection` method) to create a suitable client socket and customize it. When using a proxy: * Prefix keyword arguments with ``proxy_`` for configuring TLS between the client and an HTTPS proxy: ``proxy_ssl``, ``proxy_server_hostname``, ``proxy_ssl_handshake_timeout``, and ``proxy_ssl_shutdown_timeout``. * Use the standard keyword arguments for configuring TLS between the proxy and the WebSocket server: ``ssl``, ``server_hostname``, ``ssl_handshake_timeout``, and ``ssl_shutdown_timeout``. * Other keyword arguments are used only for connecting to the proxy. Raises: InvalidURI: If ``uri`` isn't a valid WebSocket URI. InvalidProxy: If ``proxy`` isn't a valid proxy. OSError: If the TCP connection fails. InvalidHandshake: If the opening handshake fails. TimeoutError: If the opening handshake times out. NdeflateTr4r3ir5r6)origin extensions subprotocols compressionrWrXproxyrr open_timeoutr8r9r:max_sizer;r<loggercreate_connectionc R ||_ t|dk(r tn|td|t j dt d  f d }||_||_||_ ||_ | |_ | |_ |_ ||_y)Nrtzunsupported compression: zwebsockets.clientcF t|  }|  }|S)N)rurvrwr{r|r7)r )urirD connectionr:r}rvr|r;r{rur8r9rwr<s rFprotocol_factoryz*connect.__init__..protocol_factoryWsE%%)! H++)+#' J rG)rr%rcr/)rrr ValueErrorlogging getLoggerr/ryrrWrXrrrzr|connection_kwargs)rCrrurvrwrxrWrXryrrrzr8r9r:r{r;r<r|r}kwargsrs ``` ```````` rFr?zconnect.__init__)s<  # !, / ) #9*EJ  $8 FG G >&&':;F  $ 0   * 0"4!2!2( !'rGcKtj}jj}t j j }|jddrd}|jdd}|dur t}dfd }jrJ|jdd|jdj|jd'td |jd td |jddr |j|fi|d{\}}|S|t|}|j dd d k(rHt#||jd dd{}|j$|fd|i|d{\}}|S|j dddk(rM|ii}} } | j'D]@\} } | j)ds| dk(r| || <"| j)dr | | | dd<<| | | <B|j dk(r.| jdd| jd'td| jd tdt+|fdj,i| d{} |}| j/||jdd}|durt1j2}|#|j4| ||fi|d{}|J|} |j7| |St9d|jd8|jdj|jdj:|j$|fi|d{\}}|S7F77777w)zCreate TCP or Unix connection.unixFNsockTc&jSN)r)rCws_urisrFfactoryz*connect.create_connection..factorys((0 0rGsslserver_hostnamez*ssl=None is incompatible with a wss:// URIz-ssl argument is incompatible with a ws:// URIsocks local_addr)rhttpproxy_httpsz5proxy_ssl=None is incompatible with an https:// proxyz8proxy_ssl argument is incompatible with an http:// proxyrXzunsupported proxyhostportrcr/)rRget_running_looprcopyr(rrygetr&securerPrrpopcreate_unix_connectionr'schemeconnect_socks_proxyr}items startswithconnect_http_proxyrX set_protocol ssl_modulecreate_default_context start_tlsconnection_madeAssertionErrorr)rCr@rryr_r proxy_parsedr all_kwargs proxy_kwargskeyvalue transportr new_transportrs` @rFr}zconnect.create_connectionus'')'',,.488$  ::fe $E ::f  )E D=f%E 1 ==   eT *   / =zz% ( !MNNzz% , !PQQ ::fe $"=$"="=g"P"PPMAzFE &u-L""2A&'10 %zz,= '=d&<&<'''! :pg$$Ra(F2392r&L ","2"2"42JC~~e,7H0H&+s 105 SW-,1 S) 2 &&'1 ++E48#''.6(S$''.:(V#5 #'+&<&<## # %Y &&z2jj-$;$;;=C?*8$..!:s+6<+%M)444 -I**95%%899zz&!)!!&&++6!!&&++6"8$"8"8"KF"KKMAzGQ  !8%LspD'N+M1,A N6M47NM7C*N>M:?A NM< BN'M>( N4N7N:N<N>Ncbt|tr0|jjdvrd|jjvs|St |j }tjj|j |jjd}t |}|jjdtd|dS|jr|jstd|S|j|jk7s2|j|jk7s|j |j k7rp|jjddrtd |d S|jjd |jjd td |d S|S)z Determine whether a connection error is a redirect that can be followed. Return the new URI if it's a valid redirect. Else, return an exception. ),i-i.i/i3i4Locationrzcannot follow redirect to z with a preexisting socketz)cannot follow redirect to non-secure URI rFz'cannot follow cross-origin redirect to z with a Unix socketrrz with an explicit host or port)r\rr[rprNr(rurllibparseurljoinrrrrrrr)rCrq old_ws_urinew_uri new_ws_uris rFprocess_redirectzconnect.process_redirects sM * ((cll222Jtxx( ,,&&txx1E1Ej1QRw'   ! ! % %f - 9,WI5OP    Z%6%6 #LWI!VW W   !2!2 2*//1*//1%%))&%8!=gYG)*&&**62>))--f5A!=gYG45 rGc>|jjSr)__await_impl__ __await__rCs rFrzconnect.__await__s""$..00rGcjK t|j4d{ttD]}|j d{|_ |j j |j|jd{|j j|j ccdddd{St'dtd777U7#tj$r&|j jjt$r_}|j jj|j|}t!|t"r ||_Yd}~@||ur||d}~wwxYw#1d{7swYyxYw#t($r}t)d|d}~wwxYww)Nz more than z redirectsz"timed out during opening handshake)r+rzrange MAX_REDIRECTSr}rrYrWrXstart_keepaliverRCancelledErrorrabort Exceptionrr\strrrr*)rCrrq uri_or_excs rFrzconnect.__await_impl__s( N&t'8'89# P# P}-"PA,0,B,B,D&DDO/"oo77 33 228779#.C# P# P# P"PD(*]O:(NOOG# P&D # P#1111779$611779%)%:%:3%? %j#6'1DH$%,!",#5%6# P# P# PJ NCD# M NsF3FCF&FC F3CCC 'F1 F=C>FF3FFFCFAE>A E9+F1E99E>>FFF FFF3F F0 F++F00F3c"K|d{S7wrrs rF __aenter__zconnect.__aenter__Jszzs  cTK|jjd{y7wr)rclose)rCexc_type exc_value tracebacks rF __aexit__zconnect.__aexit__Ms oo##%%%s (&(c "Kd} |4d{}|dddd{d}$77 #1d{7swYxYw#t$r} |j|}n#t$r }|}Yd}~nd}~wwxYw||ur|||| t}t|}|jj d|t jt||djtj|d{7Yd}~d}~wwxYww)Nz0connect failed; reconnecting in %.1f seconds: %sr) rrrrnextr|inforformat_exception_onlytypestriprRsleep)rCdelaysrDrqnew_exc raised_excdelays rF __aiter__zconnect.__aiter__Ws*.$ ##8"N##FK#####  )"44S9G )(G) c>&!s*>$YFV    F33DIsCAFLLN  mmE***; sDA*A. A,ADAAA7 AA D  AD A4(A/*D/A44BD;C><DDD  D)(rrruz Origin | Nonervz'Sequence[ClientExtensionFactory] | NonerwzSequence[Subprotocol] | NonerxrfrWrerXrfryzstr | Literal[True] | Nonerrz'Callable[[Exception], Exception | None]rzr`r8r`r9r`r:r`r{z int | Noner;rar<rbr|zLoggerLike | Noner}ztype[ClientConnection] | Nonerrrcrdr)rqrrczException | str)rcz&Generator[Any, None, ClientConnection])rztype[BaseException] | NonerzBaseException | NonerzTracebackType | Nonercrd)rczAsyncIterator[ClientConnection])rgrhrirjrrrr?r}rrr__iter__rrrrrGrFr-r-suux!%>B59"+15(2,0EV%'&(%'&($@B49$(;?5J( J(  J( < J(3J( J(/J(&J(*J(CJ(#J( $!J("##J($$%J(()J(*>+J(,2-J(0"1J(495J(89J(: ;J(X_B;~1)NZH&,&(&( &  &'rGr-c P||jdd}nd}td|d|d|S)a Connect to a WebSocket server listening on a Unix socket. This function accepts the same keyword arguments as :func:`connect`. It's 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. ``uri`` defaults to ``ws://localhost/`` or, when a ``ssl`` argument is provided, to ``wss://localhost/``. rzws://localhost/zwss://localhost/T)rrpathr)rr-)rrrs rFr.r.s9* { ::e  $#C$C  ;sD ;F ;;rG) ProxyType)r$)socks5hsocks5socks4asocks4TFc pKtt|j|j|j|j |j t|j} |j|j|jfi|d{S7#t$rt$r}td|d}~wwxYww)z0Connect via a SOCKS proxy and return the socket.Nz failed to connect to SOCKS proxy) SocksProxySOCKS_PROXY_TYPESrrrusernamepasswordSOCKS_PROXY_RDNSr-rmrr)ryrr socks_proxyrqs rFrrs ! ell + JJ JJ NN NN U\\ *   J,,,V[[&++PPP PP   J?@c I Js<AB6+B B B B6BB3" B..B33B6c Ktdw)Nz-python-socks is required to use a SOCKS proxy) ImportError)ryrrs rFrrs IJJs ct|j|j|jd}t }t|j|j|j|d<|||d<|j 1|j Jt|j |j |d<d|dj|jzS)NT)always_include_portHostrJzProxy-AuthorizationzCONNECT z HTTP/1.1 ) rrrrrrrrencode serialize)ryrrXrrNs rFprepare_connect_requestrs fkk6;; SW XDiG fkk6==IGFO$ 1  ~~!~~))))B NNENN* %&dV= ) 0 0 2W5F5F5H HHrGcJeZdZ d d dZd dZd dZd dZd dZd dZy)HTTPProxyConnectionNcR||_||_||_t|_t j |jj|jj|jjd|_ tj}|j|_y)NF) include_body)rryrXr readerrr read_line read_exact read_to_eofparserrRrrAr[)rCrryrXr@s rFr?zHTTPProxyConnection.__init__s}   !2"n nn KK ! ! KK " " KK # #   '')262D2D2F rGc t|jy#t$rs}|j}d|jcxkrdkrnn|j j |n)|j jt|Yd}~yYd}~yd}~wt$r7}td}||_ |j j|Yd}~yd}~wwxYw)Nrz0did not receive a valid HTTP response from proxy) rr StopIterationrrpr[r] set_exceptionrrrrn)rCrqr[ proxy_excs rF run_parserzHTTPProxyConnection.run_parsers 3   JyyHh**0S0 ((2 ++,>x,HII3 3+BI#&I  MM ' ' 2 2  3s! CA$B C-C  Ccttj|}||_|jj t |j |j|jyr) r rR TransportrwriterryrrX)rCrs rFrz#HTTPProxyConnection.connection_made sG**I6 "  #DJJ T=S=S T rGcZ|jj||jyr)r feed_datar)rCdatas rF data_receivedz!HTTPProxyConnection.data_receiveds d# rGcX|jj|jyr)rfeed_eofrrs rF eof_receivedz HTTPProxyConnection.eof_receiveds  rGct|jj||jj|yyr)rrr[r)rCrqs rFconnection_lostz#HTTPProxyConnection.connection_losts.  ? MM ' ' , rGr)rr%ryr$rXrf)rcrd)rzasyncio.BaseTransportrcrd)r bytesrcrd)rqException | Nonercrd) rgrhrir?rrr rrrrGrFrrsE )- GGG& G*3  -rGrcKtjjfdjjfi|d{\}} |j d{|S77#t $r|jwxYww)NctSr)r)ryrXrsrFz$connect_http_proxy..'s#FE3DErG)rRrr}rrr[rr)ryrrXrrrDs``` rFrr s !M 8 8 : L LE  !  !Ix   s<AB  A( B A,!A*"A,&B *A,,BB )rqrrcr)NN)rrfrrfrrrcr-)ryr$rr%rrrcz socket.socketr)ryr$rr%rXrfrcr) ryr$rr%rXrfrrrczasyncio.Transport)X __future__rrRrossocketrrr urllib.parsercollections.abcrrrtypesrtypingrr r r clientr rdatastructuresrr exceptionsrrrrrrextensions.baserextensions.permessage_deflaterrNrrrhttp11rrrDrrstreamsr r!r"r#rr$r%r&r'r( compatibilityr*r+rr,__all__intenvironrrr/rrr-r. python_socksrpython_socks.async_.asynciorSOCKS5SOCKS4rrrrrProtocolrrrrGrFr/s" >>//,15LRR)("44HH8" :BJJNN#=tDE W)zW)t*\MMb< < << <:1K&?##""##""  JJJJ  JJ%)I I I"I I&8-'**8-|%)  "   qKKKKK  KKs?AE??FF