
    A>qj?                    ,   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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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'm(Z(m)Z) ddl*m+Z+ ddlm,Z,m-Z-m.Z.m/Z/ ddl0m1Z1 ddl2m3Z3m4Z4 g dZ5 G d de3      Z6 G d d      Z7	 	 d#ddddddde#dddddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d$dZ8	 d%	 	 	 	 	 	 	 d&d Z9d'd!Z:	 	 	 d(	 	 	 	 	 	 	 d)d"Z;y)*    )annotationsN)	Awaitable	Coroutine	GeneratorIterableSequence)TracebackType)AnyCallableMappingSelfcast   )InvalidHeader)ServerExtensionFactory) enable_server_permessage_deflate)	CloseCode)build_www_authenticate_basicparse_authorization_basicvalidate_subprotocols)SERVERRequestResponse)
CONNECTINGOPENEventServerProtocol)
LoggerLikeOrigin
StatusLikeSubprotocol)get_socket_name   )
Connection	broadcast)r&   serve
unix_serveServerConnectionServer
basic_authc                       e Zd ZdZdddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZddZd	d	ef	 	 	 	 	 	 	 dd
Zd fdZd fdZ	 xZ
S )r)   aN  
    :mod:`asyncio` 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 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:`serve`.

    Args:
        protocol: Sans-I/O connection.
        server: Server that manages this connection.

       
         ping_intervalping_timeoutclose_timeout	max_queuewrite_limitc                   |  t         |   ||||||       || _        | j                  j	                         | _        |  |  |  y )Nr1   )super__init__serverloopcreate_futurerequest_rcvd)	selfprotocolr:   r2   r3   r4   r5   r6   	__class__s	           X/opt/rentech/trading_bot/.venv/lib/python3.12/site-packages/websockets/asyncio/server.pyr9   zServerConnection.__init__B   sS     	'%'# 	 	
 26))2I2I2K    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.

        )r?   reject)r>   statustexts      rA   respondzServerConnection.respond\   s    & }}##FD11rB   Nc                  K   t        j                  | j                  | j                  gt         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(  rS| j.                  j1                         s9| j                  j                  t        j                  j2                  d	      | _        | j4                  t6        u rU| j9                  t6        
      4 d{    | j                  j;                  | 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.

        )return_whenNz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)asynciowaitr=   connection_lost_waiterFIRST_COMPLETEDrequest
isinstancer   	Exceptionr?   handshake_excloggererrorrD   http
HTTPStatusINTERNAL_SERVER_ERRORacceptresponser   headersstatus_codeSWITCHING_PROTOCOLSr:   
is_servingSERVICE_UNAVAILABLEstater   send_contextsend_response)r>   process_requestprocess_responseserver_headerr[   excs         rA   	handshakezServerConnection.handshakeq   s    , ll ; ;<//
 	
 	

 <<#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..0 $ 4 4OO770! zzZ',,J,G ? ?MM//>? ? ? ( $	
 $2  	25DMM/KK%%&>%N#}}33==E H	4 $2  	25DMM/KK%%&?$%O#}}33==E H	:? ? ? ? ?s   ?MH+M(H1  H.H1 A%M+3J- J*J- #CM.L&/M2&L,M#L)$M.H1 1	J':A"J"M"J''M*J- -	L#6A"LML##M)M,L>2L53L>:Mc                    | j                   5t        |t              sJ || _         | j                  j	                  d       yt
        |   |       y)z.
        Process one incoming event.

        N)rQ   rR   r   r=   
set_resultr8   process_event)r>   eventr@   s     rA   rk   zServerConnection.process_event   sI     <<eW--- DL((. G!%(rB   c                    t         |   |       | j                  j                  | j                  j                  |             }| j                  j                  j                  |       y N)r8   connection_mader;   create_taskr:   handlerhandler_tasksadd)r>   	transporthandler_taskr@   s      rA   ro   z ServerConnection.connection_made   sM    	* yy,,T[[-@-@-FG!!%%l3rB   )r?   r   r:   r*   r2   float | Noner3   rv   r4   rv   r5   *int | None | tuple[int | None, int | None]r6   int | tuple[int, int | None]returnNone)rE   r!   rF   strry   r   )rd   ZCallable[[ServerConnection, Request], Awaitable[Response | None] | Response | None] | Nonere   dCallable[[ServerConnection, Request, Response], Awaitable[Response | None] | Response | None] | Nonerf   
str | Nonery   rz   )rl   r   ry   rz   )rt   zasyncio.BaseTransportry   rz   )__name__
__module____qualname____doc__r9   rG   r   rh   rk   ro   __classcell__)r@   s   @rA   r)   r)   (   s    < ')%'&(@B49/ / /
 $/ #/ $/ >/ 2/ 
/42:  $*!\?\?\?  "!\?" 
#\?|)4 4rB   r)   c                  
   e Zd ZdZ	 d	 	 	 	 	 	 	 ddZedd       Zdej                  df	 	 	 	 	 	 	 ddZ	dej                  df	 	 	 	 	 	 	 ddZ
dd	Zdd
ZddZddZddZedd       ZddZddZddZ	 	 	 	 	 	 	 	 ddZy)r*   a  
    WebSocket server returned by :func:`serve`.

    This class mirrors most of the API of :class:`asyncio.Server`, with the
    following differences:

    * You can invoke :func:`serve` as ``async with serve(...) as server: ...``
      in addition to ``server = await serve(...)`` to start the server.

    * It doesn't provide ``close_clients`` or ``abort_clients``; by default,
      :meth:`close` closes existing connections with code 1001 (going away).

    Args:
        handler: Handler for one connection. It receives an asyncio protocol.
        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               | _        d | _        t        j                         }|j                         | _        y )Nzwebsockets.server)create_serverrq   logging	getLoggerrU   setall_connectionsrr   
close_taskrM   get_running_loopr<   handlers_waiter)r>   r   rq   rU   r;   s        rA   r9   zServer.__init__   sp     +>&&':;F 7:e69e 6: '')595G5G5IrB   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`.

        )r   r?   ra   r   )r>   
connections     rA   connectionszServer.connections  s>     #22
""((D0 
 	
 
s   %7T c                    | j                   6| j                         j                  | j                  |||            | _         yy)a  
        Close the server.

        * Close the underlying :class:`asyncio.Server`.
        * 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 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:`close` is idempotent.

        N)r   get_looprp   _close)r>   close_connectionscodereasons       rA   closezServer.close"  s<    2 ??""mmo99-tV<DO #rB   c           	       K   | j                   j                  d       | j                  j                          |rw| j                  D cg c]C  }|j
                  j                  t        u r%t        j                  |j                  ||            E }}|rt        j                  |       d{    | j                  j                          d{    | j                  r't        j                  | j                         d{    | j                  j                  d       | j                   j                  d       yc c}w 7 7 u7 Dw)z
        Implementation of :meth:`close`.

        This calls :meth:`~asyncio.Server.close` on the underlying
        :class:`asyncio.Server` object to stop accepting new connections and
        then closes open connections.

        zserver closingNzserver closed)rU   infor:   r   r   r?   ra   r   rM   rp   rN   wait_closedrr   r   rj   )r>   r   r   r   r   close_taskss         rA   r   zServer._close@  s     	)* 	  #'"6"6&&,,4 ##J$4$4T6$BCK  ll;/// kk%%''' ,,t11222 	''-)) 0 	(
 3sD   AEAD=E,E-!EE2EEAEEEc                6    | j                   j                         S )z7
        See :meth:`asyncio.Server.get_loop`.

        )r:   r   r>   s    rA   r   zServer.get_loopl  s    
 {{##%%rB   c                T   K   | j                   j                          d{    y7 w)a  
        See :meth:`asyncio.Server.start_serving`.

        Typical use::

            server = await serve(..., start_serving=False)
            # perform additional setup here...
            # ... then start the server
            await server.start_serving()

        N)r:   start_servingr   s    rA   r   zServer.start_servings  s      kk'')))s   (&(c                $  K   	 | j                         s| j                          d{    | j                          d{    y7 7 # t        j                  $ r1 	 | j                          | j                          d{  7    #  xY ww xY ww)a  
        See :meth:`asyncio.Server.serve_forever`.

        Typical use::

            server = await serve(...)
            # this coroutine doesn't return
            # canceling it stops the server
            await server.serve_forever()

        This is an alternative to using :func:`serve` as an asynchronous context
        manager. Shutdown is triggered by canceling :meth:`serve_forever` or by
        calling :meth:`~Server.close` from another task.

        N)r_   r   r   rM   CancelledErrorr   r   s    rA   serve_foreverzServer.serve_forever  s}      
	??$((***""$$$ +$%% 	

&&(((	sa   B#A	 AA	 A A	 BA	 A	 	B#B BBBB		BBc                6    | j                   j                         S )z9
        See :meth:`asyncio.Server.is_serving`.

        )r:   r_   r   s    rA   r_   zServer.is_serving  s    
 {{%%''rB   c                ^   K   t        j                  | j                         d{    y7 w)a  
        Wait until the server is closed.

        When :meth:`wait_closed` returns, all TCP connections are closed and
        all connection handlers have returned.

        To ensure a fast shutdown, a connection handler should always be
        awaiting at least one of:

        * :meth:`~ServerConnection.recv`: when the connection is closed,
          it raises :exc:`~websockets.exceptions.ConnectionClosedOK`;
        * :meth:`~ServerConnection.wait_closed`: when the connection is
          closed, it returns.

        Then the connection handler is immediately notified of the shutdown;
        it can clean up and exit.

        N)rM   shieldr   r   s    rA   r   zServer.wait_closed  s      & nnT11222s   #-+-c                .    | j                   j                  S )z6
        See :attr:`asyncio.Server.sockets`.

        )r:   socketsr   s    rA   r   zServer.sockets  s     {{"""rB   c                  K   t        | d      sw| j                          d {   | _        | j                  j                         r@| j                  j                  D ]'  }| j
                  j                  dt        |             ) | S 7 ew)Nr:   zserver listening on %s)hasattrr   r:   r_   r   rU   r   r#   )r>   socks     rA   _awaitzServer._await  sr     tX& $ 2 2 44DK{{%%' KK// VDKK$$%=t?TUV	 5s    B
BA&B
c                >    | j                         j                         S rn   )r   	__await__r   s    rA   r   zServer.__await__  s    {{}&&((rB   c                "   K   |  d {   S 7 wrn    r   s    rA   
__aenter__zServer.__aenter__  s     zzs   c                `   K   | j                          | j                          d {    y 7 wrn   )r   r   )r>   exc_type	exc_value	tracebacks       rA   	__aexit__zServer.__aexit__  s#      	

   s   $.,.rn   )r   z1Callable[[], Coroutine[Any, Any, asyncio.Server]]rq   z7Callable[[ServerConnection], Coroutine[Any, Any, None]]rU   LoggerLike | Nonery   rz   )ry   zset[ServerConnection])r   boolr   zCloseCode | intr   r{   ry   rz   )ry   zasyncio.AbstractEventLoop)ry   rz   )ry   r   )ry   ztuple[socket.socket, ...])ry   r   )ry   zGenerator[Any, None, Self])r   ztype[BaseException] | Noner   zBaseException | Noner   zTracebackType | Nonery   rz   )r   r   r   r   r9   propertyr   r   
GOING_AWAYr   r   r   r   r   r_   r   r   r   r   r   r   r   rB   rA   r*   r*      s2   0 %)	JHJ IJ "	J
 
J. 
 
" #' ) 4 4	  	
 
@ #' ) 4 4	**** ** 	**
 
**X&*8(3* # #)!,! (! (	!
 
!rB   r*   deflater.   r-   i   r/   r0   )origins
extensionssubprotocolsselect_subprotocolcompressionrd   re   rf   open_timeoutr2   r3   r4   max_sizer5   r6   rU   create_connectionc               n   	
 t               |dk(  rt              n|t        d|       t        j	                  d      $j                  d       j                  d       d	fd}d
fdd 	
fd}t        ||      S )u  
    Create a WebSocket server listening on ``host`` and ``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.

    This function returns a :class:`Server` object whose API mirrors
    :class:`asyncio.Server`. Treat it as an asynchronous context manager to
    serve requests and ensure that the server will be closed gracefully::

        from websockets.asyncio.server import serve

        async def handler(websocket):
            ...

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

        async with serve(handler, host, port):
            await stop.wait()

    Alternatively, await it and call :meth:`~Server.serve_forever` to serve
    requests, then cancel it or call :meth:`~Server.close` to stop the server::

        server = await serve(handler, host, port)
        await server.serve_forever()

    The following pattern is functional but redundant: by the time the context
    manager exits, :meth:`~Server.serve_forever` has already closed the server::

        async with serve(handler, host, port) as server:
            await server.serve_forever()

    Args:
        handler: Connection handler. It receives the WebSocket connection,
            which is a :class:`ServerConnection`, in argument.
        host: Network interfaces the server binds to.
            See :meth:`~asyncio.loop.create_server` for details.
        port: TCP port the server listens on.
            See :meth:`~asyncio.loop.create_server` for details.
        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.
        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 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.

    Any other keyword arguments are passed to the event loop's
    :meth:`~asyncio.loop.create_server` method.

    For example:

    * You can set ``ssl`` to a :class:`~ssl.SSLContext` to enable TLS.

    * You can set ``sock`` to provide a preexisting TCP socket. You may call
      :func:`socket.create_server` (not to be confused with the event loop's
      :meth:`~asyncio.loop.create_server` method) to create a suitable server
      socket and customize it.

    * You can set ``start_serving`` to ``False`` to start accepting connections
      only after you call :meth:`~Server.start_serving()` or
      :meth:`~Server.serve_forever()`.

    r   zunsupported compression: sslssl_handshake_timeoutssl_shutdown_timeoutc                    K   t        j                         } j                  dd      r | j                  fi  d {   S  | j                  fi  d {   S 7 !7 w)NunixF)rM   r   popcreate_unix_serverr   )r;   hostkwargsportprotocol_factorys    rA   r   zserve.<locals>.create_server  sn     '')::fe$0001ALVLLL ,++,<dDSFSSS M Ts#   =A& A"A&A$A&$A&c            	     l    d} 	 	 	 	 	 	 dfd} t        	|       } |
      S )zR
        Create an asyncio protocol for managing a WebSocket connection.

        Nc                >    J | j                   u sJ  |      S rn   )r?   )r?   r   r   r   s     rA   protocol_select_subprotocolzDserve.<locals>.protocol_factory.<locals>.protocol_select_subprotocol  s2    
 *555:#6#6666)*lCCrB   )r   r   r   r   r   rU   r1   )r?   r   r   zSequence[Subprotocol]ry   zSubprotocol | Noner   )r   r?   r   r4   r   r   rU   r5   r   r   r2   r3   r   r:   r   r6   s     @rA   r   zserve.<locals>.protocol_factory  s      	$ )D(D3D $D "!%:
 ''%'#

 rB   c                  K   	 t        j                        4 d{    | j                         d{    ddd      d{    | j                  j                  t
        urI| j                  j                          	 j                  j                  t        j                                yj                  j                  |        | j                          	  |        d{    | j                          d{    j                  j                  |        	 j                  j                  t        j                                y7 37 7 # 1 d{  7  sw Y   xY w7 7 o# t        $ rH | j                   j#                  dd       | j                  t$        j&                         d{  7   Y w xY w# j                  j                  |        w xY w# t        $ r | j                  j                          Y w xY w# j                  j                  t        j                                w 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.

        Nzconnection handler failedTrJ   )rM   timeoutrh   r?   ra   r   rt   abortrr   discardcurrent_taskr   rs   start_keepaliver   rS   rU   rV   r   INTERNAL_ERROR)r   rq   r   rd   re   r:   rf   s    rA   protocol_handlerzserve.<locals>.protocol_handler  s     	A |4   **#$!    ""((4$$**,(   (()=)=)?@% ""&&z2&&(;j)))
 !&&(((&&..z:   (()=)=)?@;    *
 )	  A!!''(Cd'S &&y'?'?@@@A &&..z: 	)   &&(	)   (()=)=)?@s  IG( EG( EEEG( 	E
:G( .I3+G( E4 *E0+E4 /G E2G G( "H #.IG( EG( E- E#!E-(G( 0E4 2G 4AG<F?=GG GG G%%G( (#HH HH /I  I)ry   zasyncio.Server)ry   r)   )r   r)   ry   rz   )r   r   
ValueErrorr)   get
setdefaultr*   )rq   r   r   r   r   r   r   r   rd   re   rf   r   r2   r3   r4   r   r5   r6   rU   r   r   r   r   r   r:   s   ``````` `````````````  @@rA   r'   r'     s    Z l+i5jA
		 4[MBCC ,zz%$1<@0-@T T, , ,\*A *A\ M#3V<FMrB   c                     t        | fd|d|S )a  
    Create a WebSocket server listening on a Unix socket.

    This function is identical to :func:`serve`, except the ``host`` and
    ``port`` arguments are replaced by ``path``. It's only available on Unix.

    It's useful for deploying a server behind a reverse proxy such as nginx.

    Args:
        handler: Connection handler. It receives the WebSocket connection,
            which is a :class:`ServerConnection`, in argument.
        path: File system path to the Unix socket.

    T)r   path)r'   )rq   r   r   s      rA   r(   r(     s    & 9t$9&99rB   c                |    	 | \  }}t        |t              xr t        |t              S # t        t        f$ r Y yw xY wNF)rR   r{   	TypeErrorr   )credentialsusernamepasswords      rA   is_credentialsr     sF    G(( (C(FZ#-FF z" s   ) ;;c                    |du du k(  rt        d      |t        |      rt        t        t        t        f   |      g}nkt        |t              rMt        t        t        t        t        t        f      |            }t        d |D              st        d|       t        d|       t        |      dfdJ 	 	 	 	 	 	 d fd}|S )	a~  
    Factory for ``process_request`` to enforce HTTP Basic Authentication.

    :func:`basic_auth` is designed to integrate with :func:`serve` as follows::

        from websockets.asyncio.server import basic_auth, serve

        async with serve(
            ...,
            process_request=basic_auth(
                realm="my dev server",
                credentials=("hello", "iloveyou"),
            ),
        ):

    If authentication succeeds, the connection's ``username`` attribute is set.
    If it fails, the server responds with an HTTP 401 Unauthorized status.

    One of ``credentials`` or ``check_credentials`` must be provided; not both.

    Args:
        realm: Scope of protection. It should contain only ASCII characters
            because the encoding of non-ASCII characters is undefined. Refer to
            section 2.2 of :rfc:`7235` for details.
        credentials: Hard coded authorized credentials. It can be a
            ``(username, password)`` pair or a list of such pairs.
        check_credentials: Function or coroutine that verifies credentials.
            It receives ``username`` and ``password`` arguments and returns
            whether they're valid.
    Raises:
        TypeError: If ``credentials`` or ``check_credentials`` is wrong.
        ValueError: If ``credentials`` and ``check_credentials`` are both
            provided or both not provided.

    Nz/provide either credentials or check_credentialsc              3  2   K   | ]  }t        |        y wrn   )r   ).0items     rA   	<genexpr>zbasic_auth.<locals>.<genexpr>Q  s     I~d+Is   zinvalid credentials argument: c                Z    	 |    }t        j                  ||      S # t         $ r Y yw xY wr   )KeyErrorhmaccompare_digest)r   r   expected_passwordcredentials_dicts      rA   check_credentialsz%basic_auth.<locals>.check_credentialsX  s=    $4X$>! &&'8(CC  s    	**c                |  K   	 |j                   d   }	 t        |      \  }} ||      }t        |t              r
| d{   }|sD| j                  t        j                  j
                  d      }t              |j                   d<   |S || _        y# t        $ rG | j                  t        j                  j
                  d      }t              |j                   d<   |cY S w xY w# t        $ rG | j                  t        j                  j
                  d      }t              |j                   d<   |cY S w xY w7 w)z
        Perform HTTP Basic Authentication.

        If it succeeds, set the connection's ``username`` attribute and return
        :obj:`None`. If it fails, return an HTTP 401 Unauthorized responss.

        AuthorizationzMissing credentials
zWWW-AuthenticatezUnsupported credentials
NzInvalid credentials
)r\   r   rG   rW   rX   UNAUTHORIZEDr   r   r   rR   r   r   )	r   rQ   authorizationr[   r   r   valid_credentialsr   realms	          rA   rd   z#basic_auth.<locals>.process_requesta  sB    	#OOO<M	!:=!IHh .hA'3&7 7 !)),,'H 4PPU3VH/0O&
?  	!)),,'H 4PPU3VH/0O	  	!)),,+H 4PPU3VH/0O	 !8sS   D<B C' D<D:AD<AC$!D<#C$$D<'AD74D<6D77D<)r   r{   r   r{   ry   r   )r   r)   rQ   r   ry   zResponse | None)r   r   r   tupler{   rR   r   listallr   dict)r   r   r   credentials_listrd   r   s   ` `  @rA   r+   r+   !  s    P 	t!2d!:;JKK+& $U38_k BCX.#D%S/)BK$PQI8HII"@ NOO<[MJKK 01	D (((,$,, 
,\ rB   )NN),rq   -Callable[[ServerConnection], Awaitable[None]]r   r~   r   z
int | Noner   z0Sequence[Origin | re.Pattern[str] | None] | Noner   z'Sequence[ServerExtensionFactory] | Noner   zSequence[Subprotocol] | Noner   zNCallable[[ServerConnection, Sequence[Subprotocol]], Subprotocol | None] | Noner   r~   rd   r|   re   r}   rf   r~   r   rv   r2   rv   r3   rv   r4   rv   r   rw   r5   rw   r6   rx   rU   r   r   ztype[ServerConnection] | Noner   r
   ry   r*   rn   )rq   r   r   r~   r   r
   ry   r*   )r   r
   ry   r   )r   NN)r   r{   r   z2tuple[str, str] | Iterable[tuple[str, str]] | Noner   z3Callable[[str, str], Awaitable[bool] | bool] | Nonery   zACallable[[ServerConnection, Request], Awaitable[Response | None]])<
__future__r   rM   r   rW   r   resocketcollections.abcr   r   r   r   r   typesr	   typingr
   r   r   r   r   
exceptionsr   extensions.baser   extensions.permessage_deflater   framesr   r\   r   r   r   http11r   r   r   r?   r   r   r   r:   r   r   r    r!   r"   utilsr#   r   r%   r&   __all__r)   r*   r'   r(   r   r+   r   rB   rA   <module>r     sG   "     	  O O  5 5 & 4 L  
 / . . . # @ @ # -{4z {4|q! q!t a AE:>15 	' 	 	 &!#"$!#"$;@<>05 $7;[a:a
a a >a 8a /a	a  !a&	'a4	5a@ AaD EaF  GaH IaJ  KaN 9OaP :QaR .SaV WaZ 5[a^ _a` aaL	 :::
: : 	:,G FJMQnnCn Kn G	nrB   