
    !ni                         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 ddlmZ dd	lmZ  G d
 de      Zy# e$ r 	 d dlZd dlmZ n# e$ r dZdZY nw xY wY Mw xY w# e$ r dZ
dZY Ow xY w)    N)urlparse)asyncio)
RedisError)ValkeyError)json   )AsyncPubSubManager)parse_redis_sentinel_urlc                   J     e Zd ZdZdZ	 	 d	 fd	Zd Zd Zd Zd Z	d Z
 xZS )
AsyncRedisManagera%  Redis based client manager for asyncio servers.

    This class implements a Redis backend for event sharing across multiple
    processes.

    To use a Redis backend, initialize the :class:`AsyncServer` instance as
    follows::

        url = 'redis://hostname:port/0'
        server = socketio.AsyncServer(
            client_manager=socketio.AsyncRedisManager(url))

    :param url: The connection URL for the Redis server. For a default Redis
                store running on the same host, use ``redis://``.  To use a
                TLS connection, use ``rediss://``. To use Redis Sentinel, use
                ``redis+sentinel://`` with a comma-separated list of hosts
                and the service name after the db in the URL path. Example:
                ``redis+sentinel://user:pw@host1:1234,host2:2345/0/myredis``.
    :param channel: The channel name on which the server sends and receives
                    notifications. Must be the same in all the servers.
    :param write_only: If set to ``True``, only initialize to emit events. The
                       default of ``False`` initializes the class for emitting
                       and receiving.
    :param redis_options: additional keyword arguments to be passed to
                          ``Redis.from_url()`` or ``Sentinel()``.
    aioredisc                     t         r%t        t         j                  d      st        d      t        |   |||       || _        |xs i | _        d| _        d | _	        d | _
        y )Nfrom_urlz*Version 2 of aioredis package is required.)channel
write_onlyloggerF)r   hasattrRedisRuntimeErrorsuper__init__	redis_urlredis_options	connectedredispubsub)selfurlr   r   r   r   	__class__s         \/home/homepc/tiktok-worker/venv/lib/python3.12/site-packages/socketio/async_redis_manager.pyr   zAsyncRedisManager.__init__8   s]    HNNJ7KLLZO*0b
    c                    t        | j                        }|j                  j                  dd      d   j	                         }|dv r#t
        t        t        d      t
        t        fS |dv r#t        t        t        d      t        t        fS |dk(  r;t
        t        #t        t        t        d	      t        t        fS t
        t        fS d
| }t        |      )N+r   r   )r   redisszLRedis package is not installed (Run "pip install redis" in your virtualenv).)valkeyvalkeyszNValkey package is not installed (Run "pip install valkey" in your virtualenv).unixzdRedis package is not installed (Run "pip install redis" or "pip install valkey" in your virtualenv).zUnsupported Redis URL scheme: )r   r   schemesplitlowerr   r   r   	aiovalkeyr   
ValueError)r   
parsed_urlr(   	error_msgs       r    _get_redis_module_and_errorz-AsyncRedisManager._get_redis_module_and_errorD   s    dnn-
""((a0399;((:#5" $: ; ; Z''** K$7" $: ; ; k))V:#5$(;& (> ? ?
 %k11++4VH=	##r!   c                    | j                         \  }}t        | j                        }|j                  dv rxt	        | j                        \  }}}| j
                  }|j                  |        |j                  j                  |fi |}|j                  |xs | j                        | _        n6 |j                  j                  | j                  fi | j
                  | _        | j                  j                  d      | _        d| _        y )N>   redis+sentinelvalkey+sentinelT)ignore_subscribe_messages)r/   r   r   r(   r
   r   updatesentinelSentinel
master_forr   r   r   r   r   r   )	r   module_r-   	sentinelsservice_nameconnection_kwargskwargsr5   s	            r    _redis_connectz AsyncRedisManager._redis_connecta   s    446	dnn-
 EE(8 7I|%6''FMM+,/v//	DVDH!,,\-IT\\JDJ...t~~ E151C1CEDJjj''$'Gr!   c           	        K   | j                         \  }}t        ddd      D ]a  }	 | j                  s| j                          | j                  j                  | j                  t        j                  |             d {   c S  y 7 # |$ ru}|dkD  r4| j                         j                  ddt        |      i       d| _        n2| j                         j                  ddt        |      i       Y d }~ y Y d }~d }~ww xY ww)	Nr   r   z#Cannot publish to redis... retryingredis_exceptionextraFz$Cannot publish to redis... giving up)r/   ranger   r>   r   publishr   r   dumps_get_loggererrorstr)r   datar9   rH   retries_leftexcs         r    _publishzAsyncRedisManager._publishq   s     3355!!R, 	L~~'')!ZZ//LL$**T"24 4 4		4 !#$$&,,#0#c(; - = &+DN$$&,,$0#c(; - =
  #sB   $DAB
?B B
DB

DA%C?4D?DDc                  K   | j                         \  }}d}d}	 	 |s?| j                          | j                  j                  | j                         d {    d}| j                  j                         2 3 d {   }| 7 /7 6 nn# |$ rf}| j                         j                  d| ddt        |      i       d}t        j                  |       d {  7   |dz  }|dkD  rd}Y d }~nd }~ww xY ww)	Nr   Fz)Cannot receive from redis... retrying in z secsrA   rB      <   )r/   r>   r   	subscriber   listenrG   rH   rI   r   sleep)r   r9   rH   retry_sleep
subscribedmessagerL   s          r    _redis_listen_with_retriesz,AsyncRedisManager._redis_listen_with_retries   s    3355
%!'')++//==="#K%)[[%7%7%9 " "'!M >"%9 	%  "(( *8,7=*? 1B3s8/L ) N #
mmK000q #"$K	% sk   C;:B B B 7B
;B<B
?B B

B C;C7A
C2CC2-C;2C77C;c                  K   | j                   j                  d      }| j                         2 3 d {   }|d   |k(  s|d   dk(  sd|v s |d    )7 $6 | j                  j	                  | j                          d {  7   y w)Nzutf-8r   typerV   rJ   )r   encoderW   r   unsubscribe)r   r   rV   s      r    _listenzAsyncRedisManager._listen   s     ,,%%g.!<<> 	& 	&'y!W,FOy0Vw5Ffo%	&> kk%%dll333sC   ,B	AAA	B	 B		B		B	A)B	BB	)zredis://localhost:6379/0socketioFNN)__name__
__module____qualname____doc__namer   r/   r>   rM   rW   r\   __classcell__)r   s   @r    r   r      s3    4 D?I>B
$: .%.4r!   r   )r   urllib.parser   r   r   redis.exceptionsr   ImportErroraioredis.exceptionsr%   r+   valkey.exceptionsr   engineior   async_pubsub_managerr	   redis_managerr
   r    r!   r    <module>rm      s     !	)++-
  4 3J4* J4)  2 
	  IKsF   A A) A&	
AA&	A A&A  A&%A&)	A54A5