
    A>qjd                    8   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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Zd dlZddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlm Z m!Z!m"Z" ddl#m$Z$m%Z%m&Z& ddl'm(Z( ddlm)Z)m*Z*m+Z+m,Z, ddl-m.Z. ddl/m0Z0m1Z1 ddl-m2Z2 g dZ3 G d de0      Z4 G d dejj                  jl                        Z7	 d ddddddddddde ddddddddejp                  d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d!dZ9y)"    )annotationsN)	AwaitableMappingSequence)TracebackType)AnyCallable	CoroutineSelf   )
basic_auth)ServerExtensionFactory) enable_server_permessage_deflate)	CloseCode)validate_subprotocols)SERVERRequestResponse)
CONNECTINGOPENEvent)ServerProtocol)
LoggerLikeOrigin
StatusLikeSubprotocol)get_socket_name   )
Connection	broadcast)race_events)r    serveServerConnectionServerr   c                       e Zd ZdZddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZddZddef	 	 	 	 	 	 	 dd	Zd fd
Z xZ	S )r#   a  
    :mod:`trio` implementation of a WebSocket server connection.

    :class:`ServerConnection` provides :meth:`recv` and :meth:`send` methods 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``, and
    ``max_queue`` arguments have the same meaning as in :func:`serve`.

    Args:
        nursery: Trio nursery.
        stream: Trio stream connected to a WebSocket client.
        protocol: Sans-I/O connection.
        server: Server that manages this connection.

       
      ping_intervalping_timeoutclose_timeout	max_queuec          	         |  t         	|   |||||||       || _        t        j                         | _        |  |  |  y )Nr)   )super__init__servertrior   request_rcvd)
selfnurserystreamprotocolr1   r*   r+   r,   r-   	__class__s
            U/opt/rentech/trading_bot/.venv/lib/python3.12/site-packages/websockets/trio/server.pyr0   zServerConnection.__init__B   sO     	'%' 	 	
 (,

    c                :    | j                   j                  ||      S )a  
        Create a plain text HTTP response.

        ``process_request`` and ``process_response`` may call this method to
        return an HTTP response instead of performing the WebSocket opening
        handshake.

        You can modify the response before returning it, for example by changing
        HTTP headers.

        Args:
            status: HTTP status code.
            text: HTTP response body; it will be encoded to UTF-8.

        Returns:
            HTTP response to send to the client.

        )r7   reject)r4   statustexts      r9   respondzServerConnection.respond^   s    & }}##FD11r:   Nc                H  K   t        | j                  | j                         d{    | j                  d}|.	  || | j                        }t	        |t
              r
| d{   }|+| j                  j                  | j                        | _        nt	        |t"              sJ || _        ||| j                   j$                  d<   d}|9	  || | j                  | j                         }t	        |t
              r
| d{   }|t	        |t"              sJ || _        | j                   j&                  t        j                  j(                  k(  rO| j*                  j,                  r9| j                  j                  t        j                  j.                  d      | _        | j0                  t2        u rU| j5                  t2        	      4 d{    | j                  j7                  | j                          ddd      d{    yyy7 7 # t        $ rm}|| j                  _        | j                  j                  dd       | j                  j                  t        j                  j                  d      }Y d}~d}~ww xY w7 # t        $ rm}|| j                  _        | j                  j                  dd       | j                  j                  t        j                  j                  d      }Y d}~d}~ww xY w7 87 # 1 d{  7  sw Y   yxY ww)
z1
        Perform the opening handshake.

        Nzprocess_request failedTexc_infozLFailed to open a WebSocket connection.
See server log for more information.
r$   zprocess_response failedzServer is shutting down.
)expected_state)r!   r3   stream_closedrequest
isinstancer   	Exceptionr7   handshake_excloggererrorr<   http
HTTPStatusINTERNAL_SERVER_ERRORacceptresponser   headersstatus_codeSWITCHING_PROTOCOLSr1   closingSERVICE_UNAVAILABLEstater   send_contextsend_response)r4   process_requestprocess_responseserver_headerrO   excs         r9   	handshakezServerConnection.handshakes   s    , $++T-?-?@@@<<#H*.tT\\BH!(I6)1>  $ 4 4T\\ B!(H555 ((2?%%h/H+/dllDMMRH!(I6)1> #!(H555 ( ))T__-P-PPKK'' $ 4 4OO770! zzZ',,J,G ? ?MM//>? ? ? ( $ 	A $2  	25DMM/KK%%&>%N#}}33==E H	4 $2  	25DMM/KK%%&?$%O#}}33==E H	:? ? ? ? ?s   $L"HL"(H %H&H *A%L"3J JJ CL"LL"&L9L"L
L"H 	JA"J=L"JL"J 	LA"K?9L"?LL"
L"LLLL"c                    | j                   4t        |t              sJ || _         | j                  j	                          yt
        |   |       y)z.
        Process one incoming event.

        N)rE   rF   r   r3   setr/   process_event)r4   eventr8   s     r9   r_   zServerConnection.process_event   sG     <<eW--- DL!!# G!%(r:   )r5   ztrio.Nurseryr6   trio.abc.Streamr7   r   r1   r$   r*   float | Noner+   rb   r,   rb   r-   *int | None | tuple[int | None, int | None]returnNone)r=   r   r>   strrd   r   )rX   ZCallable[[ServerConnection, Request], Awaitable[Response | None] | Response | None] | NonerY   dCallable[[ServerConnection, Request, Response], Awaitable[Response | None] | Response | None] | NonerZ   
str | Nonerd   re   )r`   r   rd   re   )
__name__
__module____qualname____doc__r0   r?   r   r\   r_   __classcell__)r8   s   @r9   r#   r#   &   s    D ')%'&(@B//  / !	/
 / $/ #/ $/ >/ 
/82:  $*!Y?Y?Y?  "!Y?" 
#Y?v) )r:   r#   c                      e Zd ZdZ	 d	 	 	 	 	 	 	 ddZedd       Zej                  f	 	 	 ddZ	de
j                  df	 	 	 	 	 	 	 ddZdd	Z	 	 	 	 	 	 	 	 dd
Zy)r$   a  
    WebSocket server returned by :func:`serve`.

    Args:
        listeners: List of Trio listeners accepting new connections.
        handler: Handler for one connection. It receives a Trio stream.
        logger: Logger for this server.
            It defaults to ``logging.getLogger("websockets.server")``.
            See the :doc:`logging guide <../../topics/logging>` for details.

    Nc                    || _         || _        |t        j                  d      }|| _        t               | _        t        j                         | _	        d| _
        y )Nzwebsockets.serverF)	listenershandlerlogging	getLoggerrI   r^   all_connectionsr2   r   handlers_waiterrS   )r4   rq   rr   rI   s       r9   r0   zServer.__init__   sR     #>&&':;F 7:e  $zz|r:   c                x    | j                   D ch c]   }|j                  j                  t        u r|" c}S c c}w )a  
        Set of active connections.

        This property contains all connections that completed the opening
        handshake successfully and didn't start the closing handshake yet.
        It can be useful in combination with :func:`~broadcast`.

        )ru   r7   rU   r   )r4   
connections     r9   connectionszServer.connections   s>     #22
""((D0 
 	
 
s   %7c           
       K   t        j                         4 d {   | _        t        j                         4 d {   | _        | j                  j	                  t        j                  t         j                  | j                  | j                  | j                               d {    | j                  D ]1  }| j                  j                  dt        |j                               3 |j                  |        d d d       d {    d d d       d {    | j                  j!                          y 7 7 7 7 6# 1 d {  7  sw Y   FxY w7 =# 1 d {  7  sw Y   MxY ww)N)handler_nurseryzserver listening on %s)r2   open_nurseryr{   serve_nurserystart	functoolspartialserve_listenersrr   rq   rI   infor   socketstartedrv   r^   )r4   task_statuslisteners      r9   serve_foreverzServer.serve_forever  s9     $$& 	* 	*$*> ((* * *d.@((..%%,,(,(<(<	   !% HKK$$0 (8	 ##D)!* *	* 	** 	  "+	*** * * *	* 	* 	* 	*s   E.D9E.ED<EA'E(D>)AE>E	E 
EE.E E.<E>E EE	E	E	EE.E+E" E+'E.T c                  K   | j                   j                  d       | j                  j                  j	                          d| _        |rU| j                  D ]F  }|j                  j                  t        u s | j                  j                  |j                  ||       H | j                  j                          d{    | j                   j                  d       y7  w)a  
        Close the server.

        * Close the TCP listeners.
        * When ``close_connections`` is :obj:`True`, which is the default,
          close existing connections. Specifically:

          * Reject opening WebSocket connections with an HTTP 503 (service
            unavailable) error. This happens when the server accepted the TCP
            connection but didn't complete the opening handshake before closing.
          * Close open WebSocket connections with close code 1001 (going away).
            ``code`` and ``reason`` can be customized, for example to use code
            1012 (service restart).

        * Wait until all connection handlers have returned.

        :meth:`aclose` is idempotent.

        zserver closingTNzserver closed)rI   r   r}   cancel_scopecancelrS   ru   r7   rU   r   r{   
start_soonacloserv   wait)r4   close_connectionscodereasonrx   s        r9   r   zServer.aclose1  s     2 	)* 	''..0  "22 U
&&,,4((33J4E4EtVTU
 ""'')))) 	*s   A4C 7AC =C>!C c                   K   | S wN )r4   s    r9   
__aenter__zServer.__aenter__]  s     s   c                @   K   | j                          d {    y 7 wr   )r   )r4   exc_type	exc_value	tracebacks       r9   	__aexit__zServer.__aexit__`  s      kkms   r   )rq   zlist[trio.SocketListener]rr   z6Callable[[trio.abc.Stream], Coroutine[Any, Any, None]]rI   LoggerLike | Nonerd   re   )rd   zset[ServerConnection])r   trio.TaskStatus[Server]rd   re   )r   boolr   zCloseCode | intr   rf   rd   re   )rd   r   )r   ztype[BaseException] | Noner   zBaseException | Noner   zTracebackType | Nonerd   re   )rj   rk   rl   rm   r0   propertyry   r2   TASK_STATUS_IGNOREDr   r   
GOING_AWAYr   r   r   r   r:   r9   r$   r$      s    
  %)	, H "	
 
* 
 
" 04/G/G#,# 
#H #' ) 4 4	**** ** 	**
 
**X, ( (	
 
r:   r$   deflater'   r&   i   r(   )hostbacklogrq   sslorigins
extensionssubprotocolsselect_subprotocolcompressionrX   rY   rZ   open_timeoutr*   r+   r,   max_sizer-   rI   create_connectionr   c                  	K   t               |
dk(  rt              n|
t        d|
       t        |.|t        d      t	        j
                  |||       d{   }n'|t        d      |t        d      |t        d      d 	fd	}t        ||      j                  |
       d{    y7 k7 w)a9  
    Create a WebSocket server listening on ``port``.

    Whenever a client connects, the server creates a :class:`ServerConnection`,
    performs the opening handshake, and delegates to the ``handler`` coroutine.

    The handler receives the :class:`ServerConnection` instance, which you can
    use to send and receive messages.

    Once the handler completes, either normally or with an exception, the server
    performs the closing handshake and closes the connection.

    When using :func:`serve` with :meth:`nursery.start <trio.Nursery.start>`,
    you get back a :class:`Server` object. Treat it as an asynchronous context
    manager to ensure that the server will be closed gracefully::

        from websockets.trio.server import serve

        async def handler(websocket):
            ...

        # set this event to exit the server
        stop = trio.Event()

        with trio.open_nursery() as nursery:
            server = await nursery.start(serve, handler, port)
            async with server:
                await stop.wait()

    Alternatively, to stop the server gracefully, call its
    :meth:`~Server.aclose` method::

        with trio.open_nursery() as nursery:
            server = await nursery.start(serve, handler, port)
            try:
                await stop.wait()
            finally:
                await server.aclose()

    Args:
        handler: Connection handler. It receives the WebSocket connection,
            which is a :class:`ServerConnection`, in argument.
        port: TCP port the server listens on.
            See :func:`~trio.open_tcp_listeners` for details.
        host: Network interfaces the server binds to.
            See :func:`~trio.open_tcp_listeners` for details.
        backlog: Listen backlog. See :func:`~trio.open_tcp_listeners` for
            details.
        listeners: Preexisting TCP listeners. ``listeners`` replaces ``port``,
            ``host``, and ``backlog``. See :func:`trio.serve_listeners` for
            details.
        ssl: Configuration for enabling TLS on the connection.
        origins: Acceptable values of the ``Origin`` header, for defending
            against Cross-Site WebSocket Hijacking attacks. Values can be
            :class:`str` to test for an exact match or regular expressions
            compiled by :func:`re.compile` to test against a pattern. Include
            :obj:`None` in the list if the lack of an origin is acceptable.
        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.
        select_subprotocol: Callback for selecting a subprotocol among
            those supported by the client and the server. It receives a
            :class:`ServerConnection` (not a
            :class:`~websockets.server.ServerProtocol`!) instance and a list of
            subprotocols offered by the client. Other than the first argument,
            it has the same behavior as the
            :meth:`ServerProtocol.select_subprotocol
            <websockets.server.ServerProtocol.select_subprotocol>` method.
        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.
        process_request: Intercept the request during the opening handshake.
            Return an HTTP response to force the response or :obj:`None` to
            continue normally. When you force an HTTP 101 Continue response, the
            handshake is successful. Else, the connection is aborted.
            ``process_request`` may be a function or a coroutine.
        process_response: Intercept the response during the opening handshake.
            Return an HTTP response to force the response or :obj:`None` to
            continue normally. When you force an HTTP 101 Continue response, the
            handshake is successful. Else, the connection is aborted.
            ``process_response`` may be a function or a coroutine.
        server_header: Value of  the ``Server`` response header.
            It defaults to ``"Python/x.y.z websockets/X.Y"``. Setting it to
            :obj:`None` removes the header.
        open_timeout: Timeout for opening connections 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 connections in seconds.
            :obj:`None` disables the timeout.
        max_size: Maximum size of incoming messages in bytes.
            :obj:`None` disables the limit. You may pass a ``(max_message_size,
            max_fragment_size)`` tuple to set different limits for messages and
            fragments when you expect long messages sent in short fragments.
        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.
        logger: Logger for this server.
            It defaults to ``logging.getLogger("websockets.server")``.
            See the :doc:`logging guide <../../topics/logging>` for details.
        create_connection: Factory for the :class:`ServerConnection` managing
            the connection. Set it to a wrapper or a subclass to customize
            connection handling.
        task_status: For compatibility with :meth:`nursery.start
            <trio.Nursery.start>`.

    Nr   zunsupported compression: z/port is required when listeners is not provided)r   r   z#port is incompatible with listenersz#host is incompatible with listenersz&backlog is incompatible with listenersc                  K   t        j                         4 d{   }	 t        j                         nt        j                        5  Nt        j                  | dd      } t        | t         j                        sJ 	 | j                          d{    d}	 	 	 	 	 	 d	fd}t        |	      } || |
      j                         d{    ddd       j                  j                  t        ur*j                          d{    	 ddd      d{    yj                  j                         j!                          	         d{    j#                          d{    j                  j/                         	 ddd      d{    y7 7 $# t         j                  $ r Y ddd       ddd      d{  7   yw xY w7 # 1 sw Y   xY w7 7 7 7 # t$        $ rH j&                  j)                  dd       j#                  t*        j,                         d{  7   Y w xY w# j                  j/                         w xY w# t$        $ r! t        j0                  |        d{  7   Y w xY w7 # 1 d{  7  sw Y   yxY ww)
a  
        Handle the lifecycle of a WebSocket connection.

        Since this coroutine doesn't have a caller that can handle
        exceptions, it attempts to log relevant ones.

        It guarantees that the TCP connection is closed before exiting.

        NT)server_sidehttps_compatiblec                >    J | j                   u sJ  |      S r   )r7   )r7   r   rx   r   s     r9   protocol_select_subprotocolzBserve.<locals>.stream_handler.<locals>.protocol_select_subprotocolU  s2    
 $6#AA#A#+z/B/B#BB#B#5j,#OOr:   )r   r   r   r   r   rI   r)   zconnection handler failedrA   )r7   r   r   zSequence[Subprotocol]rd   zSubprotocol | None)r2   r|   CancelScope
fail_after	SSLStreamrF   do_handshakeBrokenResourceErrorr   r\   r7   rU   r   close_streamru   addstart_keepaliver   rG   rI   rJ   r   INTERNAL_ERRORdiscardaclose_forcefully)r6   r5   r   r7   rx   r,   r   r   rr   rI   r-   r   r   r   r*   r+   rX   rY   r   r1   rZ   r   r   s       @r9   stream_handlerzserve.<locals>.stream_handler)  s     $$& [	5 [	5'Z5 $+ $$&6C  "&"(,-1	"  *&$..AAA#"("5"5"777  0 *5P&4P*?P 0P  . '#-%1+F!)% H "3 &3%1&3"+	"J %..'(%  CJ &&,,D8$11333U[	5 [	5 [	5X &&**:6**,?!*---
 %++---**22:>m[	5 [	5 [	5( 8#77 #"'C[	5 [	5 [	5*#ZC CL 4S[	5^ .
 .	 ! F%%++,GRV+W$++I,D,DEEEF **22:> 5 ,,V4445q[	5 [	5 [	5 [	5sw  KF;KJ.+I?8G6GF>GAG6'G3(G6,7I?#H$I?)K4H5K:+I?&H1H2H6I	H	
II?)J.*K5J,6K>GG0G6I?K(G+)K/G00G66H 	;	I?KH	IAIIIIIII<<I??!J) J#!J)&J.(J))J.,K.K 4J75K <K)r   )r6   ra   rd   re   )r   r   
ValueErrorr#   r2   open_tcp_listenersr$   r   )rr   portr   r   rq   r   r   r   r   r   r   rX   rY   rZ   r   r*   r+   r,   r   r-   rI   r   r   r   r1   s   `    ````` ```````````  @r9   r"   r"   i  s     N l+i5jA
		 4[MBCC , <NOO11$T7SS	BCCBCCEFFe5 e5 e5P I~v6F


;

777e Td 8s%   A!C%5C!6A%C%C#C%#C%r   )0rr   z-Callable[[ServerConnection], Awaitable[None]]r   
int | Noner   zstr | bytes | Noner   r   rq   z list[trio.SocketListener] | Noner   zssl_module.SSLContext | Noner   z0Sequence[Origin | re.Pattern[str] | None] | Noner   z'Sequence[ServerExtensionFactory] | Noner   zSequence[Subprotocol] | Noner   zNCallable[[ServerConnection, Sequence[Subprotocol]], Subprotocol | None] | Noner   ri   rX   rg   rY   rh   rZ   ri   r   rb   r*   rb   r+   rb   r,   rb   r   rc   r-   rc   rI   r   r   ztype[ServerConnection] | Noner   r   rd   re   ):
__future__r   r   rK   rs   rer   
ssl_modulecollections.abcr   r   r   typesr   typingr   r	   r
   r   r2   trio.abcasyncio.serverr   extensions.baser   extensions.permessage_deflater   framesr   rP   r   http11r   r   r   r7   r   r   r   r1   r   r   r   r   r   utilsr   rx   r   r    r!   __all__r#   abcAsyncResourcer$   r   r"   r   r:   r9   <module>r      s   "    	  8 8  1 1   ' 4 L  + . . . . # @ @ # - t)z t)nITXX## I\ i8
  $26(,@D:>15 	' 	 	 &!#"$!#"$;@<> $7;+/+C+Cei8:i8
i8
 i8 i8 0i8 
&i8 >i8 8i8 /i8	i8( )i8.	/i8<	=i8H Ii8L Mi8N  Oi8P Qi8R  Si8V 9Wi8X :Yi8\ ]i8` 5ai8d )ei8f 
gi8r:   