
    2Bf                         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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  ej                  d      Z G d d	e      Zy)
    N   )
exceptions)packet)payload)socketzengineio.serverc                      e Zd ZdZddgZg dZdZdZ	 	 	 	 	 	 d(dZd	 Z	d
 Z
d)dZd Zd Zd Zd Zd)dZd Zd Zd Zd*dZd Zd Zd Zd Zd Z	 d)dZd Zd Zd Zd+dZd)dZd  Z d)d!Z!d" Z"d# Z#d$ Z$d% Z%d& Z&d' Z'y),Servera  An Engine.IO server.

    This class implements a fully compliant Engine.IO web server with support
    for websocket and long-polling transports.

    :param async_mode: The asynchronous model to use. See the Deployment
                       section in the documentation for a description of the
                       available options. Valid async modes are "threading",
                       "eventlet", "gevent" and "gevent_uwsgi". If this
                       argument is not given, "eventlet" is tried first, then
                       "gevent_uwsgi", then "gevent", and finally "threading".
                       The first async mode that has all its dependencies
                       installed is the one that is chosen.
    :param ping_interval: The interval in seconds at which the server pings
                          the client. The default is 25 seconds. For advanced
                          control, a two element tuple can be given, where
                          the first number is the ping interval and the second
                          is a grace period added by the server.
    :param ping_timeout: The time in seconds that the client waits for the
                         server to respond before disconnecting. The default
                         is 20 seconds.
    :param max_http_buffer_size: The maximum size of a message when using the
                                 polling transport. The default is 1,000,000
                                 bytes.
    :param allow_upgrades: Whether to allow transport upgrades or not. The
                           default is ``True``.
    :param http_compression: Whether to compress packages when using the
                             polling transport. The default is ``True``.
    :param compression_threshold: Only compress messages when their byte size
                                  is greater than this value. The default is
                                  1024 bytes.
    :param cookie: If set to a string, it is the name of the HTTP cookie the
                   server sends back tot he client containing the client
                   session id. If set to a dictionary, the ``'name'`` key
                   contains the cookie name and other keys define cookie
                   attributes, where the value of each attribute can be a
                   string, a callable with no arguments, or a boolean. If set
                   to ``None`` (the default), a cookie is not sent to the
                   client.
    :param cors_allowed_origins: Origin or list of origins that are allowed to
                                 connect to this server. Only the same origin
                                 is allowed by default. Set this argument to
                                 ``'*'`` to allow all origins, or to ``[]`` to
                                 disable CORS handling.
    :param cors_credentials: Whether credentials (cookies, authentication) are
                             allowed in requests to this server. The default
                             is ``True``.
    :param logger: To enable logging set to ``True`` or pass a logger object to
                   use. To disable logging set to ``False``. The default is
                   ``False``. Note that fatal errors are logged even when
                   ``logger`` is ``False``.
    :param json: An alternative json module to use for encoding and decoding
                 packets. Custom json modules must have ``dumps`` and ``loads``
                 functions that are compatible with the standard library
                 versions.
    :param async_handlers: If set to ``True``, run message event handlers in
                           non-blocking threads. To run handlers synchronously,
                           set to ``False``. The default is ``True``.
    :param monitor_clients: If set to ``True``, a background task will ensure
                            inactive clients are closed. Set to ``False`` to
                            disable the monitoring task (not recommended). The
                            default is ``True``.
    :param kwargs: Reserved for future extensions, any additional parameters
                   given as keyword arguments will be silently ignored.
    gzipdeflate)connect
disconnectmessageTr   Nc                    || _         t        |t              r|d   | _        |d   | _        n|| _        d| _        || _        || _        || _        || _        || _	        |	| _
        |
| _        || _        i | _        i | _        t               | _        ||n| j"                  | _        ||t&        j(                  _        t        |t,              s|| _        nt0        | _        | j.                  j2                  t4        j6                  k(  r|r*| j.                  j9                  t4        j:                         n)| j.                  j9                  t4        j<                         | j.                  j?                  t5        j@                                | jC                         }|	||v r|gng }d | _"        d | _#        |D ]e  }	 tI        jJ                  d|z         jD                  | _"        d| jD                  v r| jD                  d   nd}|| jM                         k7  r^|| _#         n | jF                  tQ        d      | jM                         r(d| jD                  vs| jD                  d   stQ        d      | jM                         s(d| jD                  v r| jD                  d   rtQ        d      | j.                  jS                  d	| jF                         y # tN        $ r Y "w xY w)
Nr   r   zengineio.async_drivers.asyncioFzInvalid async_mode specifiedz1The selected async_mode is not asyncio compatiblezKThe selected async_mode requires asyncio and must use the AsyncServer classzServer initialized for %s.)*ping_timeout
isinstancetupleping_intervalping_interval_grace_periodmax_http_buffer_sizeallow_upgradeshttp_compressioncompression_thresholdcookiecors_allowed_originscors_credentialsasync_handlerssocketshandlerssetlog_message_keys_default_monitor_clientsstart_service_taskr   Packetjsonboolloggerdefault_loggerlevelloggingNOTSETsetLevelINFOERROR
addHandlerStreamHandlerasync_modes_async
async_mode	importlibimport_moduleis_asyncio_basedImportError
ValueErrorinfo)selfr3   r   r   r   r   r   r   r   r   r   r'   r%   r   monitor_clientskwargsmodesmodeasyncio_baseds                      O/var/www/highfloat_scraper/venv/lib/python3.12/site-packages/engineio/server.py__init__zServer.__init__Y   s    )mU+!.q!1D.;A.>D+!.D./D+$8!, 0%:"$8! 0, #* #2040M0M 	!%FMM&$' DK(DK{{  GNN2KK((6KK((7&&w'<'<'>?  "!$.%$7ZLRE 	D
'55-466<f  !DKK/ !%I 65:  D$9$9$;;"&	 ??";<<  "$++-Y' * + +$$&9+CI& > ? ?5tG  s   7AK	K			KKc                      y)NF r:   s    r@   r6   zServer.is_asyncio_based   s        c                 
    g dS )N)eventletgevent_uwsgigevent	threadingrC   rD   s    r@   r1   zServer.async_modes   s    BBrE   c                 ^      j                   vrt        d       fd}||S  ||       y)a  Register an event handler.

        :param event: The event name. Can be ``'connect'``, ``'message'`` or
                      ``'disconnect'``.
        :param handler: The function that should be invoked to handle the
                        event. When this parameter is not given, the method
                        acts as a decorator for the handler function.

        Example usage::

            # as a decorator:
            @eio.on('connect')
            def connect_handler(sid, environ):
                print('Connection request')
                if environ['REMOTE_ADDR'] in blacklisted:
                    return False  # reject

            # as a method:
            def message_handler(sid, msg):
                print('Received message: ', msg)
                eio.send(sid, 'response')
            eio.on('message', message_handler)

        The handler function receives the ``sid`` (session ID) for the
        client as first argument. The ``'connect'`` event handler receives the
        WSGI environment as a second argument, and can return ``False`` to
        reject the connection. The ``'message'`` handler receives the message
        payload as a second argument. The ``'disconnect'`` handler does not
        take a second argument.
        zInvalid eventc                 &    | j                   <   | S N)r   )handlereventr:   s    r@   set_handlerzServer.on.<locals>.set_handler   s    #*DMM% NrE   N)event_namesr8   )r:   rO   rN   rP   s   ``  r@   onz	Server.on   s8    > (((_--	 ?GrE   c                     	 | j                  |      } |j                  t        j                  t
        j                  |             y# t        $ r | j                  j                  d|       Y yw xY w)a>  Send a message to a client.

        :param sid: The session id of the recipient client.
        :param data: The data to send to the client. Data can be of type
                     ``str``, ``bytes``, ``list`` or ``dict``. If a ``list``
                     or ``dict``, the data will be serialized as JSON.
        zCannot send to sid %sN)data)_get_socketKeyErrorr'   warningsendr   r$   MESSAGE)r:   sidrT   r   s       r@   rX   zServer.send   s_    	%%c*F
 	FMM&..t<=	  	KK 7=	s   A	 	%A10A1c                 <    | j                  |      }|j                  S )aC  Return the user session for a client.

        :param sid: The session id of the client.

        The return value is a dictionary. Modifications made to this
        dictionary are not guaranteed to be preserved unless
        ``save_session()`` is called, or when the ``session`` context manager
        is used.
        rU   session)r:   rZ   r   s      r@   get_sessionzServer.get_session   s     !!#&~~rE   c                 4    | j                  |      }||_        y)zStore the user session for a client.

        :param sid: The session id of the client.
        :param session: The session dictionary.
        Nr\   )r:   rZ   r]   r   s       r@   save_sessionzServer.save_session   s     !!#& rE   c                 8     G fddt               } ||       S )aN  Return the user session for a client with context manager syntax.

        :param sid: The session id of the client.

        This is a context manager that returns the user session dictionary for
        the client. Any changes that are made to this dictionary inside the
        context manager block are saved back to the session. Example usage::

            @eio.on('connect')
            def on_connect(sid, environ):
                username = authenticate_user(environ)
                if not username:
                    return False
                with eio.session(sid) as session:
                    session['username'] = username

            @eio.on('message')
            def on_message(sid, msg):
                with eio.session(sid) as session:
                    print('received message from ', session['username'])
        c                   (    e Zd Zd Z fdZ fdZy)0Server.session.<locals>._session_context_managerc                 .    || _         || _        d | _        y rM   )serverrZ   r]   )r:   re   rZ   s      r@   rA   z9Server.session.<locals>._session_context_manager.__init__
  s    $#rE   c                 \    | j                   j                        | _        | j                  S rM   )re   r^   r]   r:   rZ   s    r@   	__enter__z:Server.session.<locals>._session_context_manager.__enter__  s#    #{{66s;||#rE   c                 R    | j                   j                  | j                         y rM   )re   r`   r]   )r:   argsrZ   s     r@   __exit__z9Server.session.<locals>._session_context_manager.__exit__  s    ((dll;rE   N)__name__
__module____qualname__rA   rh   rk   )rZ   s   r@   _session_context_managerrc   	  s    $
$<rE   ro   )object)r:   rZ   ro   s    ` r@   r]   zServer.session   s    ,	<v 	< (c22rE   c                    |@	 | j                  |      } |j                          || j                  v r| j                  |= yy| j                  j	                         D ]  }|j                           i | _        y# t        $ r Y yw xY w)zDisconnect a client.

        :param sid: The session id of the client to close. If this parameter
                    is not given, then all clients are closed.
        N)rU   closer   rV   values)r:   rZ   r   clients       r@   r   zServer.disconnect  s     ?*))#.
 $,,&S) ' ,,--/ DL  s   A: :	BBc                 @    | j                  |      j                  rdS dS )zReturn the name of the transport used by the client.

        The two possible values returned by this function are ``'polling'``
        and ``'websocket'``.

        :param sid: The session of the client.
        	websocketpolling)rU   upgradedrg   s     r@   	transportzServer.transport-  s"     #..s3<<{K)KrE   c                 l
   | j                   g k7  rh|j                  d      }|rU| j                  |      }|B||vr>| j                  |dz   d       | j	                  |dz         } ||d   |d          |d   gS |d   }t
        j                  j                  |j                  d	d
            }d}d}	d|v r|d   d   nd}
|
M|j                  d      dgk7  r8| j                  dd       | j	                  d      } ||d   |d          |d   gS d|v rd}	 t        |d   d         }	|r'|	%| j                  dd       | j	                  d      }n|dk(  rJ|
|j                  ddg      d   }d|v r|j                  d      j                         nd}|dk(  s||cxk(  rdk(  rn n| j                  ||||	      }n| j                  d|z   d       | j	                  d|z         }ny|
| j                  vr+| j                  d|
z   d       | j	                  d|
z         }n@| j                  |
      }	  |j                   ||      }t#        |t$              r| j'                  ||	      }n|}|
| j                  v r| j                  |
   j.                  r| j                  |
= n|d k(  ry|
|
| j                  vr2| j                  d|
xs d!z   d       | j	                  d|
xs d!z         }ny| j                  |
      }	  |j0                  |       | j'                  |	      }nB|d#k(  r| j'                         }n,| j2                  j7                  d$|       | j9                         }t#        |t:              s|xs g S | j<                  rt?        |d         | j@                  k\  r|j                  d%d
      jC                  d&      D cg c]$  }|jC                  d'      d   jE                         & }}|D ]=  }|| jF                  v s tI        | d(|z         |d         |d<   |dxx   d)|fgz  cc<    n | jK                  |      } ||d   |d   |z          |d   gS # t        t        t        f$ r Y Fw xY w# t(        j*                  $ r3 |
| j                  v r| j-                  |
       | j	                         }Y Kw xY w# t(        j*                  $ r3 |
| j                  v r| j-                  |
       | j	                         }Y  | j2                  j5                  d"       | j'                  |	      }Y xY wc c}w )*a+  Handle an HTTP request from the client.

        This is the entry point of the Engine.IO application, using the same
        interface as a WSGI application. For the typical usage, this function
        is invoked by the :class:`Middleware` instance, but it can be invoked
        directly when the middleware is not used.

        :param environ: The WSGI environment.
        :param start_response: The WSGI ``start_response`` function.

        This function returns the HTTP response body to deliver to the client
        as a byte sequence.
        HTTP_ORIGINNz is not an accepted origin.z
bad-originstatusheadersresponseREQUEST_METHODQUERY_STRING FrZ   r   EIO4zRThe client is using an unsupported version of the Socket.IO or Engine.IO protocolszbad-versionjTzInvalid JSONP index numberzbad-jsonp-indexGETry   rw   HTTP_UPGRADErv   zInvalid transport zbad-transportzInvalid session zbad-sidjsonp_indexPOSTNonezpost request handler errorOPTIONSzMethod %s not supportedHTTP_ACCEPT_ENCODING,;_zContent-Encoding)&r   get_cors_allowed_origins_log_error_once_bad_requesturllibparseparse_qsintr8   rV   
IndexErrorlower_handle_connectr   rU   handle_get_requestr   list_okr   EngineIOErrorr   closedhandle_post_requestr'   	exceptionrW   _method_not_founddictr   lenr   splitstripcompression_methodsgetattr_cors_headers)r:   environstart_responseoriginallowed_originsrmethodqueryjsonpr   rZ   ry   upgrade_headerr   packetse	encodingsencodingcors_headerss                      r@   handle_requestzServer.handle_request7  sx    $$* [[/F"&"<"<W"E".6'4(((!>>N))!>>@A"1X;)=jM?*)*%%gkk."&EF "'%eEl1oT;599U+u4  )*79 !!)*A 1X;)5jM?"%<E!%*Q-0
 [(  !=!24!!">?Au_{!IIkI;?B	 &0 ")^!<!B!B!D6: 	)$E+E,,Wn-6EA (()=	)I)8:))*>*JKAdll*(();c)A9M))*<s*BCA!--c2F
0";&";";#^#5%gt4 $k JA 'A
 dll*t||C/@/G/G LL-v{c5$$&#-8)E%%&8CM6&JK))#.:.F..w7[9A y 
AKK 96B&&(A!T"7N  AjM"d&@&@@ %;R@FFsKMQa..0 MI M% t7775cHn5a
mD jMiL&8(%C$DDL ))'2q{AiL<$?@*c *5 H &33 0$,,. OOC0 --/0  "// ,dll*,))+A: KK))*FG[9AMs>   Q 09Q/ 7$R8 >)T1Q,+Q,/AR54R58AT.=.T.c                 V     | j                   d   |||      }|j                          |S )ad  Start a background task using the appropriate async model.

        This is a utility function that applications can use to start a
        background task using the method that is compatible with the
        selected async mode.

        :param target: the target function to execute.
        :param args: arguments to pass to the function.
        :param kwargs: keyword arguments to pass to the function.

        This function returns an object compatible with the `Thread` class in
        the Python standard library. The `start()` method on this object is
        already called by this function.
        thread)targetrj   r<   )r2   start)r:   r   rj   r<   ths        r@   start_background_taskzServer.start_background_task  s+     #T[["&tFK

	rE   c                 ,     | j                   d   |      S )a  Sleep for the requested amount of time using the appropriate async
        model.

        This is a utility function that applications can use to put a task to
        sleep without having to worry about using the correct call for the
        selected async mode.
        sleepr2   )r:   secondss     r@   r   zServer.sleep  s     $t{{7#G,,rE   c                 ,     | j                   d   |i |S )zCreate a queue object using the appropriate async model.

        This is a utility function that applications can use to create a queue
        without having to worry about using the correct call for the selected
        async mode.
        queuer   r:   rj   r<   s      r@   create_queuezServer.create_queue       $t{{7#T4V44rE   c                      | j                   d   S )zReturn the queue empty exception for the appropriate async model.

        This is a utility function that applications can use to work with a
        queue without having to worry about using the correct call for the
        selected async mode.
        queue_emptyr   rD   s    r@   get_queue_empty_exceptionz Server.get_queue_empty_exception  s     {{=))rE   c                 ,     | j                   d   |i |S )zCreate an event object using the appropriate async model.

        This is a utility function that applications can use to create an
        event without having to worry about using the correct call for the
        selected async mode.
        rO   r   r   s      r@   create_eventzServer.create_event  r   rE   c                    t        j                  t        j                  d      | j                  j                  dd      z         }| j                  dz   dz  | _        |j                  d      j                  dd      j                  d	d
      S )zGenerate a unique session id.      bigr   i utf-8/r   +-)base64	b64encodesecretstoken_bytessequence_numberto_bytesdecodereplace)r:   ids     r@   generate_idzServer.generate_id  sz    #d&:&:&C&CAu&MMO $ 4 4q 8HDyy!))#s3;;CEErE   c                     |j                  dd      dz   |z   }|j                         D ]8  \  }}|dk(  rt        |      r |       }|du r	|d|z   z  }+|d|z   dz   |z   z  }: |S )zGenerate the sid cookie.nameio=Tz; )r   itemscallable)r:   rZ   
attributesr   	attributevalues         r@   _generate_sid_cookiezServer._generate_sid_cookie  s    -3c9 * 0 0 2 	9IuF"}$**$*S0588	9 rE   c           
         | j                   r"d| _         | j                  | j                         | j                         }t	        j
                  | |      }|| j                  |<   t        j                  t        j                  || j                  ||      t        | j                  dz        t        | j                  | j                  z         dz  d      }|j                  |       |j!                          | j#                  d||d      }|A|dur=| j                  |= | j$                  j'                  d       | j)                  |xs d      S |d	k(  r;|j+                  ||      }|j,                  r|| j                  v r| j                  |= |S d|_        d}	| j0                  r]t3        | j0                  t4              r d
| j7                  || j0                        fg}	n#d
| j7                  || j0                  ddd      fg}		 | j9                  |j;                         |	|      S # t<        j>                  $ r | jA                         cY S w xY w)z#Handle a client connection request.Fi  )rZ   upgradespingTimeoutpingIntervalr   )	run_asyncNTzApplication rejected connectionrv   z
Set-Cookier   Lax)r   pathSameSite)r}   r   )!r#   r   _service_taskr   r   Socketr   r   r$   OPEN	_upgradesr   r   r   r   rX   schedule_ping_trigger_eventr'   rW   _unauthorizedr   r   	connectedr   r   r   r   r   pollr   
QueueEmptyr   )
r:   r   r   ry   r   rZ   spktretr}   s
             r@   r   zServer._handle_connect
  s)    ""&+D#&&t'9'9: MM$$SmmFKKsI6t00478""T%D%DDFHLM	*N O 	
s	 !!)S'U!K?s$S!KK AB%%ckT22#&&w?CxxC4<</LL%JAKG{{dkk40$11#t{{C  G %11#$(KK%8   G+xx',7   9 9(( +((**+s   !H$ $#I
	I
c                     | j                   r | j                  |      j                  s|dk(  rg S | j                  d   | j	                  dd       g S dgS )z=Return the list of possible upgrades for a client connection.rv   zThe WebSocket transport is not available, you must install a WebSocket server that is compatible with your async mode to enable it. See the documentation for details.zno-websocket)r   rU   rx   r2   r   )r:   rZ   ry   s      r@   r   zServer._upgradesE  sb    ""d&6&6s&;&D&D[(I;;{#+  @ 	 
 I}rE   c                    |j                  dd      }|| j                  v r5|r  | j                  | j                  |   g| S 	  | j                  |   | S y#  | j                  j	                  |dz          |dk(  rY yY yxY w)zInvoke an event handler.r   Fz handler errorr   N)popr   r   r'   r   )r:   rO   rj   r<   r   s        r@   r   zServer._trigger_eventS  s    JJ{E2	DMM!1t11$--2FNNN%/4==/66 "%KK))%2B*BC	)  % *s   A %B c                     	 | j                   |   }|j                  r| j                   |= t        d      |S # t        $ r t        d      w xY w)z-Return the socket object for a given session.zSession not foundzSession is disconnected)r   rV   r   )r:   rZ   r   s      r@   rU   zServer._get_socketc  sX    	0S!A 88S!455  	0.//	0s	   7 Ac                     |C|g }|dgz  }d|t        j                  |      j                  |      j                  d      dS ddgddS )	z$Generate a successful HTTP response.)Content-Typeztext/plain; charset=UTF-8z200 OK)r   r   r   r|   r}   r~   r  z
text/plains   OK)r   Payloadencode)r:   r   r}   r   s       r@   r   z
Server._okn  ss    EFFG&& ' @ G G$/ !H !117B B
 ' >? %' 'rE   c                     |d}t         j                  j                  j                  |      }ddg|j	                  d      dS )z+Generate a bad request HTTP error response.zBad Requestz400 BAD REQUESTr  r   r  r   r$   r%   dumpsr  r:   r   s     r@   r   zServer._bad_request}  sE    ?#G--$$**73+:;#NN735 	5rE   c                     ddgddS )z0Generate a method not found HTTP error response.z405 METHOD NOT FOUNDr  s   Method Not Foundr  rC   rD   s    r@   r   zServer._method_not_found  s    0:;/1 	1rE   c                     |d}t         j                  j                  j                  |      }ddg|j	                  d      dS )z,Generate a unauthorized HTTP error response.Unauthorizedz401 UNAUTHORIZED)r  zapplication/jsonr   r  r	  r  s     r@   r   zServer._unauthorized  sE    ?$G--$$**73,@A#NN735 	5rE   c           
      >   g }d|v rd|v r|j                  dj                  |d   |d                d|v sd|v r|j                  d|d         j                  d      d   j	                         }|j                  dj                  ||j                  d|d         j                  d      d   j	                                      | j
                  |}|S | j
                  d	k(  rd }|S t        | j
                  t              r| j
                  g}|S | j
                  }|S )
Nzwsgi.url_scheme	HTTP_HOSTz{scheme}://{host})schemehostHTTP_X_FORWARDED_PROTOHTTP_X_FORWARDED_HOSTr   r   *)appendformatr   r   r   r   r   str)r:   r   default_originsr  r   s        r@   r   zServer._cors_allowed_origins  sZ   'K7,B""#6#=#=018L $> $N O'72+w6 ,-.005c
1>>Ceg   &&':'A'A!/1E)GGLuH!!")$$)EG (B (- . $$,-O  &&#-"O
 	 1137#889O  #77OrE   c                     | j                   g k(  rg S g }| j                  |      }d|v r||d   |v rd|d   fg}|d   dk(  r|dgz  }d|v r|d|d   fgz  }| j                  r|dgz  }|S )	z1Return the cross-origin-resource-sharing headers.r{   zAccess-Control-Allow-Originr   r   )zAccess-Control-Allow-MethodszOPTIONS, GET, POST#HTTP_ACCESS_CONTROL_REQUEST_HEADERSzAccess-Control-Allow-Headers)z Access-Control-Allow-Credentialstrue)r   r   r   )r:   r   r}   r   s       r@   r   zServer._cors_headers  s    $$*I44W=G# (GM,B -!5w}7MNOG#$	1NOOG0G;7 EFH I IG  DEEGrE   c                     t        j                         }t        j                  |d      5 }|j	                  |       ddd       |j                         S # 1 sw Y   |j                         S xY w)z%Apply gzip compression to a response.w)fileobjr>   N)r   BytesIOr
   GzipFilewritegetvalue)r:   r~   bytesiogzs       r@   _gzipzServer._gzip  sW    **,]]75 	HHX	!!	!!s   AA.c                 ,    t        j                  |      S )z(Apply deflate compression to a response.)zlibcompress)r:   r~   s     r@   _deflatezServer._deflate  s    }}X&&rE   c                     || j                   vr:| j                  j                  |dz          | j                   j                  |       y| j                  j	                  |       y)zWLog message with logging.ERROR level the first time, then log
        with given level.zC (further occurrences of this error will be logged with level INFO)N)r!   r'   erroraddr9   )r:   r   message_keys      r@   r   zServer._log_error_once  sY     d333KKg )@ @ A!!%%k2KKW%rE   c                 .   	 t        | j                        dk(  r| j                  | j                         5t	        | j                        t        | j                        z  }	 | j                  j                         j                         D ];  }|j                  s|j                  s|j                          | j                  |       = 	 # t        t        f$ r | j                  j                  d       Y y | j                  j                  d       Y KxY w)z;Monitor connected clients and clean up those that time out.r   zservice task canceledzservice task exceptionN)r   r   r   r   floatcopyrs   closingr   check_ping_timeout
SystemExitKeyboardInterruptr'   r9   r   )r:   sleep_intervalr   s      r@   r   zServer._service_task  s    4<< A%

4,,- #4#4#45DLL8IIN@**,335 /A99QXX,,.JJ~./   12   !89@%%&>?s   "A&C
 
*D6D)N      i@B TTi   NNTFNTNrM   )r   )NNN)(rl   rm   rn   __doc__r   rQ   r"   r   rA   r6   r1   rR   rX   r^   r`   r]   r   ry   r   r   r   r   r   r   r   r   r   r   r   rU   r   r   r   r   r   r   r&  r*  r   r   rC   rE   r@   r	   r	      s    @B "9-6K#OGI>B>B37;?6:BHHC(T> !#3J*LDL&-5*5F %)9+v% 	'5150("'&@rE   r	   )r   r
   r4   r   r*   r   r   r(  r   r   r   r   r   	getLoggerr(   rp   r	   rC   rE   r@   <module>r;     sL       	        """#45Z@V Z@rE   