
    ph                     F   S SK r S SKrS SKrS SKrS SKJr  S SKJrJrJ	r	J
r
JrJrJrJrJrJr  S SKJr  S SKJrJrJrJr  S SKJr  S SKJrJr  S SKJrJrJ r J!r!  S S	K"J#r#  S S
K$J%r%J&r&J'r'J(r(J)r)  S SK*J+r+  S SK,J-r-J.r.J/r/J0r0J1r1  S SK2J3r3J4r4J5r5J6r6J7r7J8r8  S SK9J:r:  S SK;J<r<  S SK=J>r>  S SK?J@r@JArAJBrBJCrCJDrDJErE  \(       a  S SKFrFS SKGrGSrHSrISrJ " S S\K5      rL " S S5      rM " S S\\\ 5      rN\NrO " S S5      rP " S S5      rQ " S S \R                  5      rS " S! S"\N5      rTg)#    N)chain)
TYPE_CHECKINGAnyCallableDictListMappingOptionalSetTypeUnion)Encoder)_RedisCallbacks_RedisCallbacksRESP2_RedisCallbacksRESP3bool_ok)ExponentialWithJitterBackoff)CacheConfigCacheInterface)CoreCommandsRedisModuleCommandsSentinelCommandslist_or_args)Script)AbstractConnection
ConnectionConnectionPoolSSLConnectionUnixDomainSocketConnection)CredentialProvider)(AfterPooledConnectionsInstantiationEvent'AfterPubSubConnectionInstantiationEvent'AfterSingleConnectionInstantiationEvent
ClientTypeEventDispatcher)ConnectionErrorExecAbortErrorPubSubError
RedisErrorResponseError
WatchErrorLock)MaintNotificationsConfig)Retry)_set_info_loggerdeprecated_argsget_lib_versionsafe_strstr_if_bytestruncate_text    EMPTY_RESPONSENEVER_DECODEc                      ^  \ rS rSrSrS\\\4   SS4S jrU 4S jrU 4S jr	U 4S	 jr
SU 4S
 jjrU 4S jrU 4S jrSrU =r$ )CaseInsensitiveDictT   z?Case insensitive dict implementation. Assumes string keys only.datareturnNc                 Z    UR                  5        H  u  p#X0UR                  5       '   M     g N)itemsupper)selfr<   kvs       F/home/james-whalen/.local/lib/python3.13/site-packages/redis/client.py__init__CaseInsensitiveDict.__init__W   s!    JJLDAO !r6   c                 >   > [         TU ]  UR                  5       5      $ r?   )super__contains__rA   rB   rC   	__class__s     rE   rJ    CaseInsensitiveDict.__contains__[   s    w#AGGI..r6   c                 @   > [         TU ]  UR                  5       5        g r?   )rI   __delitem__rA   rK   s     rE   rO   CaseInsensitiveDict.__delitem__^   s    AGGI&r6   c                 >   > [         TU ]  UR                  5       5      $ r?   )rI   __getitem__rA   rK   s     rE   rR   CaseInsensitiveDict.__getitem__a   s    w"1779--r6   c                 @   > [         TU ]  UR                  5       U5      $ r?   )rI   getrA   )rB   rC   defaultrL   s      rE   rU   CaseInsensitiveDict.getd   s    w{1779g..r6   c                 B   > [         TU ]  UR                  5       U5        g r?   )rI   __setitem__rA   )rB   rC   rD   rL   s      rE   rY   CaseInsensitiveDict.__setitem__g   s    AGGIq)r6   c                 :   > [        U5      n[        TU ]	  U5        g r?   )r:   rI   update)rB   r<   rL   s     rE   r\   CaseInsensitiveDict.updatej   s    "4(tr6    r?   )__name__
__module____qualname____firstlineno____doc__r   strrF   rJ   rO   rR   rU   rY   r\   __static_attributes____classcell__rL   s   @rE   r:   r:   T   sD    E T#s(^    /'./* r6   r:   c                       \ rS rSrSrg)AbstractRediso   r^   N)r_   r`   ra   rb   re   r^   r6   rE   ri   ri   o   s    r6   ri   c            b          \ rS rSrSr\S\SS 4S j5       r\S\S    S\	SS 4S j5       r
\" S	/S
SS9SSSSSSSSSSSSSS\" \" SSS9SS9SSSSSSSSSSSSSSSSSSSSSSS\" 5       SSSSSSSS4/S\S\S\S \\   S!\\   S"\\   S#\\   S$\\\\\\4   4      S\\	   S%\\   S&\S'\S(\S	\S)\S*\\\\         S+\S,\\   S-\\   S.\\S/4   S0\\S1      S2\\S1      S3\\   S4\\   S5\\   S6\S7\\   S8\S9\S:\S;   S<\\   S=\S>   S?\\   S@\\   SA\SB\SC\\   SD\\   SE\\   SF\\   SG\\/ S4      SH\\   SI\\   SJ\\   SK\\   SL\\   SM\\   SS4`SN jj5       rS\4SO jrSsSP jr S\!4SQ jr"S\\   4SR jr#S)\SS4SS jr$ST\SU\SS4SV jr%StSW jr&SuSvSY jjr'SZ\SX/S4   S\\\(   \(S4   4S[ jr)       SwS\\S]\\   S^\S_\S`\\   Sa\S\(4   Sb\Sc\4Sd jjr*Se r+Sf r,Sg r-Sh r.Si r/Sj r0StSk jr1Sl r2StSm jr3Sn r4So r5Sp r6S\\   4Sq jr7Srr8g)xRediss   a  
Implementation of the Redis protocol.

This abstract class provides a Python interface to all Redis commands
and an implementation of the Redis protocol.

Pipelines derive from this, implementing how
the commands are sent and received to the Redis server. Based on
configuration, an instance will either use a ConnectionPool, or
Connection object to talk to redis.

It is not safe to pass PubSub or Pipeline objects between threads.
urlr=   c                 t    UR                  SS5      n[        R                  " U40 UD6nU " UUS9nSUl        U$ )a5  
Return a Redis client object configured from the given URL

For example::

    redis://[[username]:[password]]@localhost:6379/0
    rediss://[[username]:[password]]@localhost:6379/0
    unix://[username@]/path/to/socket.sock?db=0[&password=password]

Three URL schemes are supported:

- `redis://` creates a TCP socket connection. See more at:
  <https://www.iana.org/assignments/uri-schemes/prov/redis>
- `rediss://` creates a SSL wrapped TCP socket connection. See more at:
  <https://www.iana.org/assignments/uri-schemes/prov/rediss>
- ``unix://``: creates a Unix Domain Socket connection.

The username, password, hostname, path and all querystring values
are passed through urllib.parse.unquote in order to replace any
percent-encoded values with their corresponding characters.

There are several ways to specify a database number. The first value
found will be used:

    1. A ``db`` querystring option, e.g. redis://localhost?db=0
    2. If using the redis:// or rediss:// schemes, the path argument
       of the url, e.g. redis://localhost/0
    3. A ``db`` keyword argument to this function.

If none of these options are specified, the default db=0 is used.

All querystring options are cast to their appropriate Python types.
Boolean arguments can be specified with string values "True"/"False"
or "Yes"/"No". Values that cannot be properly cast cause a
``ValueError`` to be raised. Once parsed, the querystring arguments
and keyword arguments are passed to the ``ConnectionPool``'s
class initializer. In the case of conflicting arguments, querystring
arguments always win.

single_connection_clientFconnection_poolrp   T)popr   from_urlauto_close_connection_pool)clsrn   kwargsrp   rr   clients         rE   rt   Redis.from_url   sK    T $*::.H%#P (11#@@+%=
 -1)r6   rv   rr   c                      U " US9nSUl         U$ )z
Return a Redis client from the given connection pool.
The Redis client will take ownership of the connection pool and
close it when the Redis client is closed.
)rr   T)ru   )rv   rr   rx   s      rE   	from_poolRedis.from_pool   s      +
 -1)r6   retry_on_timeoutz$TimeoutError is included by default.z6.0.0)args_to_warnreasonversion	localhosti  r   Nzutf-8strictF   
   )basecap   )backoffretriesrequiredTzredis-py   hostportdbpasswordsocket_timeoutsocket_connect_timeoutsocket_keepalivesocket_keepalive_optionsunix_socket_pathencodingencoding_errorsdecode_responsesretryretry_on_errorsslssl_keyfilessl_certfilessl_cert_reqszssl.VerifyModessl_include_verify_flagszssl.VerifyFlagsssl_exclude_verify_flagsssl_ca_certsssl_ca_pathssl_ca_datassl_check_hostnamessl_passwordssl_validate_ocspssl_validate_ocsp_stapledssl_ocsp_contextzOpenSSL.SSL.Contextssl_ocsp_expected_certssl_min_versionzssl.TLSVersionssl_ciphersmax_connectionsrp   health_check_intervalclient_namelib_namelib_versionusernameredis_connect_funccredential_providerprotocolcachecache_configevent_dispatchermaint_notifications_configc0                    U.c  [        5       U l        OU.U l        U	(       Gd  U(       d  / n0 SU_SU(_SU_SU_SU_SU_SU_S	U_S
[        R                  " U5      _SU"_SU$_SU%_SU&_SU'_SU)_SU*_SU+_n0U
b  U0R	                  U
[
        S.5        OU0R	                  UUUUUS.5        U(       aH  U0R	                  0 S[        _SU_SU_SU_SU_SU_SU_SU_SU_SU_SU_S U_S!U_S"U_S#U_S$U _S%U!_5        U-(       d  U,(       a  U+S&;   a  U0R	                  U,U-S'.5        U/=(       a    U/R                  n1U1(       a  U+S&;  a  [        S(5      eU/(       a  U0R	                  S)U/05        [        S.0 U0D6n	U R                  R                  [        U	/[        R                  U*5      5        S*U l        O<S+U l        U R                  R                  [        U	/[        R                  U*5      5        Xl        U-(       d  U,(       a)  U R                  R!                  5       S&;  a  [        S,5      e["        R$                  " 5       U l        SU l        U#U l        U R*                  (       ag  U R                  R-                  5       U l        U R                  R                  [/        U R(                  [        R                  U R&                  5      5        [1        [2        5      U l        U R                  R6                  R9                  S5      S-;   a   U R4                  R	                  [:        5        gU R4                  R	                  [<        5        g)/a  
Initialize a new Redis client.

To specify a retry policy for specific errors, you have two options:

1. Set the `retry_on_error` to a list of the error/s to retry on, and
you can also set `retry` to a valid `Retry` object(in case the default
one is not appropriate) - with this approach the retries will be triggered
on the default errors specified in the Retry object enriched with the
errors specified in `retry_on_error`.

2. Define a `Retry` object with configured 'supported_errors' and set
it to the `retry` parameter - with this approach you completely redefine
the errors on which retries will happen.

`retry_on_timeout` is deprecated - please include the TimeoutError
either in the Retry object or in the `retry_on_error` list.

When 'connection_pool' is provided - the retry configuration of the
provided pool will be used.

Args:

single_connection_client:
    if `True`, connection pool is not used. In that case `Redis`
    instance use is not thread safe.
decode_responses:
    if `True`, the response will be decoded to utf-8.
    Argument is ignored when connection_pool is provided.
maint_notifications_config:
    configuration the pool to support maintenance notifications - see
    `redis.maint_notifications.MaintNotificationsConfig` for details.
    Only supported with RESP3
    If not provided and protocol is RESP3, the maintenance notifications
    will be enabled by default (logic is included in the connection pool
    initialization).
    Argument is ignored when connection_pool is provided.
Nr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )pathconnection_class)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )r   3)r   r   zWMaintenance notifications handlers on connection are only supported with RESP version 3r   TFz4Client caching is only supported with RESP version 3)r   r   r^   )r%   _event_dispatchercopydeepcopyr\   r   r   enabledr)   r   dispatchr!   r$   SYNCru   rr   get_protocol	threadingRLocksingle_connection_lock
connection_single_connection_clientget_connectionr#   r:   r   response_callbacksconnection_kwargsrU   r   r   )2rB   r   r   r   r   r   r   r   r   rr   r   r   r   r   r}   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rp   r   r   r   r   r   r   r   r   r   r   r   r   rw   maint_notifications_enableds2                                                     rE   rF   Redis.__init__   s   ~ #%4%6D"%5D"!!#bH H !.	
 H "? #$4 !. u- "? ()> { H { %&8  &':!" H#F(  + 0,F  $ $2H,<4L MM.); +L ,]	
 78P 78P +L *; 12D +L *; 89R 01B /0@ 56L  .!" *;#* !Ex8/CMM%*,8 /U3M3U3U , /8 D 4 %q  .MM8:T
 -6v6O""++8$%z8K
 /3D+.3D+""++8$%z8K  /Et';';'H'H'J S
 (
 STT&/oo&7#)A&))"22AACDO""++7OOZ__d6Q6Q #6o"F1155jAXM##**+?@##**+?@r6   c                     S[        U 5      R                   S[        U 5      R                   S[        U R                  5       S3$ )N<.(z)>)typer`   r_   reprrr   rB   s    rE   __repr__Redis.__repr__  sD    T
%%&aT
(;(;'<T))*+2/	
r6   c                 6    U R                   R                  5       $ )z!Get the connection pool's encoder)rr   get_encoderr   s    rE   r   Redis.get_encoder  s    ##//11r6   c                 .    U R                   R                  $ )z'Get the connection's key-word arguments)rr   r   r   s    rE   get_connection_kwargsRedis.get_connection_kwargs  s    ##555r6   c                 @    U R                  5       R                  S5      $ Nr   )r   rU   r   s    rE   	get_retryRedis.get_retry  s    ))+//88r6   c                 |    U R                  5       R                  SU05        U R                  R                  U5        g r   )r   r\   rr   	set_retry)rB   r   s     rE   r   Redis.set_retry  s2    ""$++We,<=&&u-r6   commandcallbackc                      X R                   U'   g)zSet a custom Response CallbackN)r   )rB   r   r   s      rE   set_response_callbackRedis.set_response_callback  s    +3(r6   c                     [        XU5        g)a  
This function can be used to add externally defined redis modules,
and their namespaces to the redis client.

funcname - A string containing the name of the function to create
func - The function, being added to this class.

ex: Assume that one has a custom redis module named foomod that
creates command named 'foo.dothing' and 'foo.anotherthing' in redis.
To load function functions into this namespace:

from redis import Redis
from foomodule import F
r = Redis()
r.load_external_module("foo", F)
r.foo().dothing('your', 'arguments')

For a concrete example see the reimport of the redisjson module in
tests/test_connection.py::test_loading_external_modules
N)setattr)rB   funcnamefuncs      rE   load_external_moduleRedis.load_external_module  s    * 	%r6   Pipelinec                 D    [        U R                  U R                  X5      $ )a/  
Return a new pipeline object that can queue multiple commands for
later execution. ``transaction`` indicates whether all commands
should be executed atomically. Apart from making a group of operations
atomic, pipelines are useful for reducing the back-and-forth overhead
between the client and server.
)r   rr   r   )rB   transaction
shard_hints      rE   pipelineRedis.pipeline  s$       $"9"9;
 	
r6   r   c                    UR                  SS5      nUR                  SS5      nUR                  SS5      nU R                  SU5       n  U(       a  UR                  " U6   U" U5      nUR                  5       n	U(       a  UOU	 sSSS5        $ ! [         a#    Ub  US:  a  [
        R                  " U5         Mq  f = f! , (       d  f       g= f)z
Convenience method for executing the callable `func` as a transaction
while watching all keys specified in `watches`. The 'func' callable
should expect a single argument which is a Pipeline object.
r   Nvalue_from_callableFwatch_delayTr   )rs   r   watchexecuter+   timesleep)
rB   r   watchesrw   r   r   r   pipe
func_value
exec_values
             rE   r   Redis.transaction  s     ZZd3
$jj)>Fjj5]]4,	

G,!%dJ!%J)<:*L -, " ".;?

;/ -,s*   	B?8B)B<8B?;B<<B??
Cnametimeoutr   blockingblocking_timeout
lock_classthread_localraise_on_release_errorc	                 .    Uc  [         nU" U UUUUUUUS9$ )a  
Return a new Lock object using key ``name`` that mimics
the behavior of threading.Lock.

If specified, ``timeout`` indicates a maximum life for the lock.
By default, it will remain locked until release() is called.

``sleep`` indicates the amount of time to sleep per loop iteration
when the lock is in blocking mode and another client is currently
holding the lock.

``blocking`` indicates whether calling ``acquire`` should block until
the lock has been acquired or to fail immediately, causing ``acquire``
to return False and the lock not being acquired. Defaults to True.
Note this value can be overridden by passing a ``blocking``
argument to ``acquire``.

``blocking_timeout`` indicates the maximum amount of time in seconds to
spend trying to acquire the lock. A value of ``None`` indicates
continue trying forever. ``blocking_timeout`` can be specified as a
float or integer, both representing the number of seconds to wait.

``lock_class`` forces the specified lock implementation. Note that as
of redis-py 3.0, the only lock class we implement is ``Lock`` (which is
a Lua-based lock). So, it's unlikely you'll need this parameter, unless
you have created your own custom lock class.

``thread_local`` indicates whether the lock token is placed in
thread-local storage. By default, the token is placed in thread local
storage so that a thread only sees its token, not a token set by
another thread. Consider the following timeline:

    time: 0, thread-1 acquires `my-lock`, with a timeout of 5 seconds.
             thread-1 sets the token to "abc"
    time: 1, thread-2 blocks trying to acquire `my-lock` using the
             Lock instance.
    time: 5, thread-1 has not yet completed. redis expires the lock
             key.
    time: 5, thread-2 acquired `my-lock` now that it's available.
             thread-2 sets the token to "xyz"
    time: 6, thread-1 finishes its work and calls release(). if the
             token is *not* stored in thread local storage, then
             thread-1 would see the token value as "xyz" and would be
             able to successfully release the thread-2's lock.

``raise_on_release_error`` indicates whether to raise an exception when
the lock is no longer owned when exiting the context manager. By default,
this is True, meaning an exception will be raised. If False, the warning
will be logged and the exception will be suppressed.

In some use cases it's necessary to disable thread local storage. For
example, if you have code where one thread acquires a lock and passes
that lock instance to a worker thread to release later. If thread
local storage isn't disabled in this case, the worker thread won't see
the token set by the thread that acquired the lock. Our assumption
is that these cases aren't common and as such default to using
thread local storage.)r  r   r  r  r  r  r,   )	rB   r   r  r   r  r  r  r  r  s	            rE   lock
Redis.lock  s5    H J-%#9	
 		
r6   c                 F    [        U R                  4SU R                  0UD6$ )z
Return a Publish/Subscribe object. With this object, you can
subscribe to channels and listen for messages that get published to
them.
r   )PubSubrr   r   )rB   rw   s     rE   pubsubRedis.pubsubM  s0       
373I3I
MS
 	
r6   c                 ,    [        U R                  5      $ r?   )Monitorrr   r   s    rE   monitorRedis.monitorW  s    t++,,r6   c                 6    U R                  U R                  SS9$ )NTrq   )rL   rr   r   s    rE   rx   Redis.clientZ  s$    ~~ 00%)  
 	
r6   c                     U $ r?   r^   r   s    rE   	__enter__Redis.__enter__`      r6   c                 $    U R                  5         g r?   )closerB   exc_type	exc_value	tracebacks       rE   __exit__Redis.__exit__c      

r6   c                 F     U R                  5         g ! [         a     g f = fr?   )r  	Exceptionr   s    rE   __del__Redis.__del__f  "    	JJL 		    
  c                     [        U S5      (       d  g U R                  nU(       a"  S U l        U R                  R                  U5        U R                  (       a  U R                  R                  5         g g )Nr   )hasattrr   rr   releaseru   
disconnectrB   conns     rE   r  Redis.closel  s[     t\**"DO  ((.**  ++- +r6   c                 L    UR                   " U0 UD6  U R                  " X40 UD6$ )z'
Send a command and parse the response
)send_commandparse_response)rB   r,  command_nameargsoptionss        rE   _send_command_parse_response"Redis._send_command_parse_response{  s-     	4+7+""4AAAr6   c                 $    UR                  5         g)a  
Close the connection before retrying.

The supported exceptions are already checked in the
retry object so we don't need to do it here.

After we disconnect the connection, it will try to reconnect and
do a health check as part of the send_command logic(on connection level).
N)r*  r+  s     rE   _close_connectionRedis._close_connection  s     	r6   c                 &    U R                   " U0 UD6$ r?   )_execute_commandrB   r2  r3  s      rE   execute_commandRedis.execute_command  s    $$d6g66r6   c                 T  ^ ^^^^ T R                   nTS   mT R                  =(       d    UR                  5       mT R                  (       a  T R                  R                  5          TR                  R                  UUUUU 4S jUU 4S j5      T(       a6  TR                  5       (       a!  T R                  T5        TR                  5         T R                  (       a  T R                  R                  5         T R                  (       d  UR                  T5        $ $ ! T(       a6  TR                  5       (       a!  T R                  T5        TR                  5         T R                  (       a  T R                  R                  5         T R                  (       d  UR                  T5        f f = f)z.Execute a command and return a parsed responser   c                  2   > TR                   " TT/T Q70 TD6$ r?   r4  r2  r1  r,  r3  rB   s   rE   <lambda>(Redis._execute_command.<locals>.<lambda>  s%    99,)-18r6   c                 &   > TR                  T5      $ r?   )r7  _r,  rB   s    rE   rB  rC    s    $006r6   )rr   r   r   r   r   acquirer   call_with_retryshould_reconnectr7  connectr)  )rB   r2  r3  poolr1  r,  s   ``` @@rE   r:  Redis._execute_command  s+   ##Aw7$"5"5"7))''//1	#::--  7	 --//&&t,--++335??T" # --//&&t,--++335??T" #s   &(D BF'c                 |    [         U;   a%  UR                  SS9nUR                  [         5        OUR                  5       n [        U;   a  UR                  [        5        UR                  SS5        X R
                  ;   a  U R
                  U   " U40 UD6$ U$ ! [         a    [        U;   a  U[           s $ e f = f)z'Parses a response from the Redis serverT)disable_decodingkeysN)r8   read_responsers   r*   r7   r   )rB   r   r1  r3  responses        rE   r0  Redis.parse_response  s    		w&%33T3JL)%335 W$KK' 	FD!222**<8MWMM  	(~..	s   .B B B;9B;c                 .    U R                   R                  $ r?   )rr   r   r   s    rE   	get_cacheRedis.get_cache  s    ##)))r6   )r   r   ru   r   rr   r   r   )r=   r   r=   N)TNr=   r   )Ng?TNNTT)9r_   r`   ra   rb   rc   classmethodrd   rt   r   r   r{   r1   r/   r   r2   intr
   floatboolr	   r   bytesr   r"  r   r    r   r   r%   r.   rF   r   r   r   r   r   r   r   r   r   r   r   r  r  r  rx   r  r  r#  r  r4  r7  r<  r:  r0  rT  re   r^   r6   rE   rl   rl   s   s    03 0W 0 0d ']' 
  ()5  "&*.26+/NR48*.'!&!&0aR@!
 ;?%)&*6@FJFJ&*%)%)#'&*"'*/<@046:%))-).%&%)",%4%6"&;?<@"#*..26:IMe\A\A \A 	\A
 3-\A !\A !)\A #4.\A #+73c5j8I3I+J"K\A ".1\A #3-\A \A \A \A \A  !\A& !d9o!67'\A( )\A* c]+\A, sm-\A. S"223/\A0 #+40A+B"C1\A2 #+40A+B"C3\A4 sm5\A6 c]7\A8 c]9\A: !;\A< sm=\A>  ?\A@ $(A\AB ##89C\AD !)E\AF ""23G\AH c]I\AJ "#K\AL #'M\AN  #O\AP c]Q\AR 3-S\AT c]U\AV 3-W\AX %Xb$h%78Y\AZ &&89[\A\ 3-]\A^ '_\A` {+a\Ab #?3c\Ad %--E$Fe\Af 
g\A
\A|
# 
26t 698E? 9.u . .4S 4H 4 4&.

j\4/0	tCy#t#	$6 $(,0'+!'+O
O
 %O
 	O

 O
 #5/O
 $)$O
 O
 !%O
b
-
.B7#2.*8N3 *r6   rl   c                       \ rS rSrSr\R                  " S5      r\R                  " S5      rS r	S r
S rS rS	 rS
 rSrg)r  i  z
Monitor is useful for handling the MONITOR command to the redis server.
next_command() method returns one command from monitor
listen() method yields commands from monitor.
z\[(\d+) (.*?)\] (.*)z"(.*?)(?<!\\)"c                 N    Xl         U R                   R                  5       U l        g r?   )rr   r   r   )rB   rr   s     rE   rF   Monitor.__init__  s    ...==?r6   c                 &    U R                  5         U $ r?   )_start_monitorr   s    rE   r  Monitor.__enter__  s    r6   c                     U R                   R                  5         U R                  R                  U R                   5        g r?   )r   r*  rr   r)  )rB   r2  s     rE   r  Monitor.__exit__  s*    ""$$$T__5r6   c                 h   U R                   R                  5       nUc  g[        U[        5      (       a$  U R                   R                  R                  USS9nUR                  SS5      u  p#U R                  R                  U5      nUR                  5       u  pVnSR                  U R                  R                  U5      5      nUR                  SS5      nUS:X  a  SnS	n	Sn
O6UR                  S
5      (       a
  S
nUSS n	S
n
OUR                  SS5      u  pSn
[!        U5      [#        U5      UU	U
US.$ )z)Parse the response from a monitor commandNTforce r   z\""lua unix   :tcp)r   r   client_addressclient_portclient_typer   )r   rP  
isinstancer\  encoderdecodesplit
monitor_rematchgroupsjoin
command_refindallreplace
startswithrsplitrZ  rY  )rB   rQ  command_timecommand_datamdb_idclient_infor   rp  rq  rr  s              rE   next_commandMonitor.next_command  s-   ??002h&&..55hd5KH%-^^C%;"OO!!,/&'hhj#G((4??227;< //%-%"NKK##F++#N%ab/K K +6*<*<S!*D'NK,'e*,&&
 	
r6   c              #   4   #     U R                  5       v   M  7f)z)Listen for commands coming to the server.)r  r   s    rE   listenMonitor.listen  s     ##%% s   c                     U R                   R                  S5        U R                   R                  5       n[        U5      (       d  [	        SU 35      eg )NMONITORzMONITOR failed: )r   r/  rP  r   r)   rB   rQ  s     rE   ra  Monitor._start_monitor  sI    $$Y/??002x  /z:;; !r6   )r   rr   N)r_   r`   ra   rb   rc   recompilerw  r{  rF   r  r  r  r  ra  re   r^   r6   rE   r  r    sG     34J-.J@6&
P&
<r6   r  c                      \ rS rSrSrSrSrSr     S2S\S\	S	   S
\
S\\/S4   4   S\	S   4S jjrS3S jrS4S jrS4S jrS4S jrS4S jrS4S jr\S\4S j5       rS rS4S jrS4S jrS rS5S jrS\4S jrS4S jrS\4S jrS rS r S  r!S! r"SS".S# jr#SS".S$ jr$S% r% S6S\S&\&4S' jjr'\'r(S7S(\
\S4   S\4S) jjr)S8S* jr*     S9S+\&S,\S-\	\   S.\SS/4
S0 jjr+S1r,g):r  i  a  
PubSub provides publish, subscribe and listen support to Redis channels.

After subscribing to one or more channels, the listen() method will block
until a message arrives on one of the subscribed channels. That message
will be returned and it's safe to start listening again.
)messagepmessagesmessage)unsubscribepunsubscribesunsubscribezredis-py-health-checkNignore_subscribe_messagesrt  r   push_handler_funcr   r%   c                 f   Xl         X l        X0l        S U l        [        R
                  " 5       U l        X@l        XPl        Uc  [        5       U l
        OX`l
        [        R                  " 5       U l        U R                  c  U R                   R                  5       U l        U R                  R                  U R                  5      U l        U R                  R"                  (       a  SU R                  /U l        OSU R                   /U l        U R                  c
  ['        5         U R)                  5         g )Npong   pong)rr   r   r  r   r   Eventsubscribed_eventrt  r  r%   r   r   _lockr   encodeHEALTH_CHECK_MESSAGEhealth_check_response_br   health_check_responser0   reset)rB   rr   r   r  rt  r  r   s          rE   rF   PubSub.__init__#  s      /$)B& ) 1 !2#%4%6D"%5"__&
<<//;;=DL'+||':':4;T;T'U$<<((*0$2K2K)LD&*143O3O)PD&!!)

r6   r=   c                     U $ r?   r^   r   s    rE   r  PubSub.__enter__F  r  r6   c                 $    U R                  5         g r?   r  r  s       rE   r  PubSub.__exit__I  r   r6   c                 F     U R                  5         g ! [         a     g f = fr?   r  r"  r   s    rE   r#  PubSub.__del__L  s$    	 JJL 		r&  c                    U R                   (       ak  U R                   R                  5         U R                   R                  U R                  5        U R                  R                  U R                   5        S U l         SU l        0 U l        [        5       U l	        0 U l
        [        5       U l        0 U l        [        5       U l        U R                  R                  5         g Nr   )r   r*  deregister_connect_callback
on_connectrr   r)  health_check_response_counterchannelssetpending_unsubscribe_channelsshard_channels"pending_unsubscribe_shard_channelspatternspending_unsubscribe_patternsr  clearr   s    rE   r  PubSub.resetU  s    ??OO&&(OO77H  ((9"DO-.*,/E) 25%/,/E)##%r6   c                 $    U R                  5         g r?   r  r   s    rE   r  PubSub.closed  r   r6   c           	      B   U R                   R                  5         U R                  R                  5         U R                  R                  5         U R                  (       aY  U R                  R                  5        VVs0 s H   u  p#U R                  R                  USS9U_M"     nnnU R                  " S0 UD6  U R                  (       aY  U R                  R                  5        VVs0 s H   u  p#U R                  R                  USS9U_M"     nnnU R                  " S0 UD6  U R                  (       aZ  U R                  R                  5        VVs0 s H   u  p#U R                  R                  USS9U_M"     nnnU R                  " S0 UD6  ggs  snnf s  snnf s  snnf )zBRe-subscribe to any channels and patterns previously subscribed toTrf  Nr^   )r  r  r  r  r  r@   rt  ru  	subscriber  
psubscriber  
ssubscribe)rB   r   rC   rD   r  r  r  s          rE   r  PubSub.on_connectg  sn   
 	))//1))//1//557==BF--BUBUBWBW$!##AT#2A5BW   NN&X&==BF--BUBUBWBW$!##AT#2A5BW   OO'h' !//5577DA ##AT#2A57   OO-n- 

s   ='F''F'Fc                 6    U R                   R                  5       $ )z@Indicates if there are subscriptions to any channels or patterns)r  is_setr   s    rE   
subscribedPubSub.subscribed  s     $$++--r6   c                    U R                   c  U R                  R                  5       U l         U R                   R                  U R                  5        U R
                  b/  U R                   R                  R                  U R
                  5        U R                  R                  [        U R                   U R                  [        R                  U R                  5      5        U R                   nSU R                  (       + 0nU R                  (       d  U R                  5         U R                     U R                   " X"R"                  /UQ70 UD6  SSS5        g! , (       d  f       g= f)z#Execute a publish/subscribe commandNcheck_health)r   rr   r   register_connect_callbackr  r  _parserset_pubsub_push_handlerr   r   r"   r$   r   r  r  clean_health_check_responses_executer/  )rB   r2  r   rw   s       rE   r<  PubSub.execute_command  s     ??""22AACDO OO55dooF%%1''??@V@VW""++7OOT%9%9:??DJJ
 __
 doo"56--/ZZMM*&=&=OOO ZZs   -!E
E%c                    SnU R                   nU(       a  U R                  S:  a  US:  a  U R                  X"R                  UR                  S9(       aa  U R                  X"R
                  5      nU R                  U5      (       a  U =R                  S-  sl        O[        SR                  U5      5      eUS-  nU(       a  U R                  S:  a	  US:  a  M  gggggg)z7
If any health check responses are present, clean them
r   r   r  r   z>A non health check response was cleaned by execute_command: {}N)	r   r  r  can_readr   rP  is_health_check_responser(   format)rB   ttlr,  rQ  s       rE   r  #PubSub.clean_health_check_responses  s     t99A=#'}}T==$:M:M}N==/A/AB00::66!;6%..4fX.>  1HC t99A=#'=d'=dr6   c                 D    UR                  5         UR                  5         g)z
The supported exceptions are already checked in the
retry object so we don't need to do it here.

In this error handler we are trying to reconnect to the server.
N)r*  rJ  r+  s     rE   
_reconnectPubSub._reconnect  s     	r6   c                    ^ ^^^^ TR                  5       (       a  T R                  T5        TR                  R                  UUU4S jUU 4S j5      nU$ )a%  
Connect manually upon disconnection. If the Redis server is down,
this will fail and raise a ConnectionError as desired.
After reconnection, the ``on_connect`` callback should have been
called by the # connection to resubscribe us to any channels and
patterns we were previously listening to
c                     > T" T 0 TD6$ r?   r^   )r2  r   rw   s   rE   rB  !PubSub._execute.<locals>.<lambda>  s    GT,V,r6   c                 &   > TR                  T5      $ r?   )r  rE  s    rE   rB  r    s    dood+r6   )rI  r  r   rH  )rB   r,  r   r2  rw   rQ  s   ````` rE   r  PubSub._execute  sA       ""OOD!::--,+

 r6   c                    ^^^ U R                   mTc  [        S5      eU R                  5         UUU4S jnU R                  TU5      nU R	                  U5      (       a  U =R
                  S-  sl        gU$ )z3Parse the response from a publish/subscribe commandNNpubsub connection not set: did you forget to call subscribe() or psubscribe()?c                  ~   > T (       d  TR                  TS9(       d  g OTR                  5         TR                  SSS9$ )Nr  FT)disconnect_on_errorpush_request)r  rJ  rP  )blockr,  r  s   rE   try_read'PubSub.parse_response.<locals>.try_read  s=    }}W}5 6 %%%d%SSr6   r   )r   RuntimeErrorr  r  r  r  )rB   r  r  r  rQ  r,  s    ``  @rE   r0  PubSub.parse_response  st    <F 
 		T ==x0((22..!3.r6   c                 8    UU R                   U R                  4;   $ )z
Check if the response is a health check response.
If there are no subscriptions redis responds to PING command with a
bulk response, instead of a multi-bulk with "pong" and the response.
)r  r  r  s     rE   r  PubSub.is_health_check_response  s(     &&((
 
 	
r6   c                    U R                   nUc  [        S5      eUR                  (       aU  [        R                  " 5       UR
                  :  a1  UR                  SU R                  SS9  U =R                  S-  sl        g g g )Nr  PINGF)r  r   )	r   r  r   r   	monotonicnext_health_checkr/  r  r  r+  s     rE   r  PubSub.check_health  sw    <F 
 %%$..*:T=S=S*Sfd&?&?eT..!3. +T%r6   c           	          U R                   R                  nU R                   R                  nUR                  5        VVs0 s H  u  pEU" U" U5      5      U_M     snn$ s  snnf )z
normalize channel/pattern names to be either bytes or strings
based on whether responses are automatically decoded. this saves us
from coercing the value for each message coming in.
)rt  r  ru  r@   )rB   r<   r  ru  rC   rD   s         rE   _normalize_keysPubSub._normalize_keys   sP     $$$$15>vay!1$>>>s    Ac                    U(       a  [        US   USS 5      n[        R                  U5      nUR                  U5        U R                  " S/UR                  5       Q76 nU R                  U5      nU R                  R                  U5        U R                  (       d!  U R                  R                  5         SU l        U R                  R                  U5        U$ )a  
Subscribe to channel patterns. Patterns supplied as keyword arguments
expect a pattern name as the key and a callable as the value. A
pattern's callable will be invoked automatically when a message is
received on that pattern rather than producing a message via
``listen()``.
r   r   N
PSUBSCRIBE)r   dictfromkeysr\   r<  rO  r  r  r  r  r  r  r  difference_update)rB   r2  rw   new_patternsret_vals        rE   r  PubSub.psubscribe
  s     Qab2D}}T*F#&&|Jl6G6G6IJ ++L9\*!!%%'12D.));;LIr6   c                     U(       a7  [        US   USS 5      nU R                  [        R                  U5      5      nOU R                  nU R
                  R                  U5        U R                  " S/UQ76 $ )zR
Unsubscribe from the supplied patterns. If empty, unsubscribe from
all patterns.
r   r   NPUNSUBSCRIBE)r   r  r  r  r  r  r\   r<  )rB   r2  r  s      rE   r  PubSub.punsubscribe$  si    
 Qab2D++DMM$,?@H}}H))00:##N:T::r6   c                    U(       a  [        US   USS 5      n[        R                  U5      nUR                  U5        U R                  " S/UR                  5       Q76 nU R                  U5      nU R                  R                  U5        U R                  (       d!  U R                  R                  5         SU l        U R                  R                  U5        U$ )a"  
Subscribe to channels. Channels supplied as keyword arguments expect
a channel name as the key and a callable as the value. A channel's
callable will be invoked automatically when a message is received on
that channel rather than producing a message via ``listen()`` or
``get_message()``.
r   r   N	SUBSCRIBE)r   r  r  r\   r<  rO  r  r  r  r  r  r  r  r  )rB   r2  rw   new_channelsr  s        rE   r  PubSub.subscribe1  s     Qab2D}}T*F#&&{I\5F5F5HI ++L9\*!!%%'12D.));;LIr6   c                     U(       a7  [        US   USS 5      nU R                  [        R                  U5      5      nOU R                  nU R
                  R                  U5        U R                  " S/UQ76 $ )zQ
Unsubscribe from the supplied channels. If empty, unsubscribe from
all channels
r   r   NUNSUBSCRIBE)r   r  r  r  r  r  r\   r<  )rB   r2  r  s      rE   r  PubSub.unsubscribeK  si    
 Qab2D++DMM$,?@H}}H))00:##M9D99r6   )target_nodec                   U(       a  [        US   USS 5      n[        R                  U5      nUR                  U5        U R                  " S/UR                  5       Q76 nU R                  U5      nU R                  R                  U5        U R                  (       d!  U R                  R                  5         SU l        U R                  R                  U5        U$ )aJ  
Subscribes the client to the specified shard channels.
Channels supplied as keyword arguments expect a channel name as the key
and a callable as the value. A channel's callable will be invoked automatically
when a message is received on that channel rather than producing a message via
``listen()`` or ``get_sharded_message()``.
r   r   N
SSUBSCRIBE)r   r  r  r\   r<  rO  r  r  r  r  r  r  r  r  )rB   r  r2  rw   new_s_channelsr  s         rE   r  PubSub.ssubscribeX  s     Qab2Dt,f%&&|Ln6I6I6KL --n="">2!!%%'12D.//AA.Qr6   c                    U(       a7  [        US   USS 5      nU R                  [        R                  U5      5      nOU R                  nU R
                  R                  U5        U R                  " S/UQ76 $ )z]
Unsubscribe from the supplied shard_channels. If empty, unsubscribe from
all shard_channels
r   r   NSUNSUBSCRIBE)r   r  r  r  r  r  r\   r<  )rB   r  r2  
s_channelss       rE   r  PubSub.sunsubscriber  sk    
 Qab2D--dmmD.ABJ,,J//66zB##N:T::r6   c              #      #    U R                   (       a9  U R                  U R                  SS95      nUb  Uv   U R                   (       a  M8  gg7f)zBListen for messages on channels this client has been subscribed toT)r  N)r  handle_messager0  r  s     rE   r  PubSub.listen  s@     oo**4+>+>T+>+JKH# ooos   AAAr  c                 0   U R                   (       d[  [        R                  " 5       nU R                  R	                  U5      SL a'  [        R                  " 5       U-
  n[        SX$-
  5      nOgU R                  USL US9nU(       a  U R                  XQ5      $ g)z
Get the next message if one is available, otherwise None.

If timeout is specified, the system will wait for `timeout` seconds
before returning. Timeout should be specified as a floating point
number, or None, to wait indefinitely.
T        N)r  r  )r  r   r  r  waitmaxr0  r  )rB   r  r  
start_time
time_spentrQ  s         rE   get_messagePubSub.get_message  s     )J$$))'2d: "^^-
:
c7#78 &&go&P&&xKKr6   r  c                 4    Ub  SU/OS/nU R                   " U6 $ )z
Ping the Redis server to test connectivity.

Sends a PING command to the Redis server and returns True if the server
responds with "PONG".
r  r<  )rB   r  r2  s      rE   pingPubSub.ping  s(     %,$7 fX##T**r6   c                    Uc  g[        U[        5      (       a  US:w  a  SU/OSS/n[        US   5      nUS:X  a  UUS   US   US	   S
.nOUS:X  a  USSUS   S
.nOUSUS   US   S
.nX0R                  ;   Ga<  US:X  aL  US   nXPR                  ;   a7  U R                  R                  U5        U R                  R                  US5        OUS:X  aL  US   nX`R                  ;   a7  U R                  R                  U5        U R                  R                  US5        OKUS   nXpR                  ;   a7  U R                  R                  U5        U R                  R                  US5        U R                  (       d<  U R                  (       d+  U R                  (       d  U R                  R                  5         X0R                  ;   a~  US:X  a   U R                  R                  US   S5      nOEUS:X  a   U R                  R                  US   S5      nOU R                  R                  US   S5      nU(       a	  U" U5        g U$ US:w  a  U(       d  U R                   (       a  gU$ )z
Parses a pub/sub message. If the channel or pattern was subscribed to
with a message handler, the handler is invoked instead of a parsed
message being returned.
Ns   PONGr  r6   r   r  r   r   r   )r   patternchannelr<   r  r  r  r  r  r  )rs  r\  r4   UNSUBSCRIBE_MESSAGE_TYPESr  remover  rs   r  r  r  r  r  r  PUBLISH_MESSAGE_TYPESrU   r  )	rB   rQ  r  message_typer  r  	s_channelr  handlers	            rE   r  PubSub.handle_message  sO    h&&.6'.A*QT~H#HQK0:%$#A;#A; 	G V#$ 	G %#A; 	G 999~-"1+???55<<WEMM%%gt4/$QK	 G GG;;BB9M''++It<"1+???55<<WEMM%%gt4==t?R?R %%++-555z)--++GI,>E+--11')2DdK--++GI,>E    V# )D,J,Jr6   
sleep_timedaemonexception_handlersharded_pubsubPubSubWorkerThreadc                    U R                   R                  5        H  u  pgUb  M
  [        SU S35      e   U R                  R                  5        H  u  pUb  M
  [        SU S35      e   U R                  R                  5        H  u  pUb  M
  [        SU	 S35      e   Uc  U OUn[        UUUUUS9n
U
R                  5         U
$ )Nz
Channel: 'z' has no handler registeredz
Pattern: 'zShard Channel: ')r&  r'  r(  )r  r@   r(   r  r  r)  start)rB   r%  r&  r'  r  r(  r  r#  r  r"  threads              rE   run_in_threadPubSub.run_in_thread  s     !% 3 3 5G!Jwi7R"STT !6 !% 3 3 5G!Jwi7R"STT !6 #'"5"5";";"=I!&yk1LM  #>  V#/)
 	r6   )r   r  r  r   rr   rt  r  r  r  r  r  r  r  r  r  r  r   r  )NFNNN)r=   r  rV  )Tr   )Fr  r?   )F)r  FNNF)-r_   r`   ra   rb   rc   r   r  r  r[  r
   r   r   rd   rF   r  r  r#  r  r  r  propertyr  r<  r  r  r  r0  r  r  r   r  r  r  r  r  r  r  r  rZ  r  get_sharded_messager  r  r-  re   r^   r6   rE   r  r    s    @ O2
 */'+@D8<! $(	!
 )$! !xt'<!<=! ##45!F&.2 .D . .P4$&6	
D 	

4?t ?4;4: -1 4 /3 ; IL)-@E< &+E#t), + +IZ  04$  $H-	  
 r6   r  c                   t   ^  \ rS rSr   SS\S\S\\\SS /S4   S4   S\4U 4S jjjr	SS	 jr
SS
 jrSrU =r$ )r)  i  Nr%  r&  r'  r  r(  c                    > [         TU ]  5         X0l        Xl        X l        X@l        XPl        [        R                  " 5       U l	        g r?   )
rI   rF   r&  r  r%  r'  r(  r   r  _running)rB   r  r%  r&  r'  r(  rL   s         rE   rF   PubSubWorkerThread.__init__  s9     	$!2,!)r6   c                    U R                   R                  5       (       a  g U R                   R                  5         U R                  nU R                  nU R                   R                  5       (       aU   U R
                  (       d  UR                  SUS9  OUR                  SUS9   U R                   R                  5       (       a  MU  UR                  5         g ! [         a*  nU R                  c  e U R                  X1U 5         S nANaS nAff = f)NT)r  r  )r3  r  r  r  r%  r(  r  r0  BaseExceptionr'  r  )rB   r  r%  es       rE   runPubSubWorkerThread.run.  s    ==!!__
mm""$$8**&&26
 '  ..26
 /  mm""$$ 		 ! 8))1&&q$778s   3!C C 
D" DDc                 8    U R                   R                  5         g r?   )r3  r  r   s    rE   stopPubSubWorkerThread.stopD  s     	r6   )r3  r&  r'  r  r(  r%  )FNFrV  )r_   r`   ra   rb   rZ  r[  r   r   r"  rF   r8  r;  re   rf   rg   s   @rE   r)  r)    sp    
  $* * 	*
 !i+?@$FGM
* * *$, r6   r)  c                   &   \ rS rSrSr1 SkrS\4S jrS$S jrS r	S	 r
S\4S
 jrS\4S jrS%S jrS%S jrS%S jrS rS\S\SS4S jrS rS$S jrS\S\4S jrS rS rS rS rS rS\S\SS4S jr S&S\S\\!   4S jjr"S  r#S! r$S\4S" jr%S#r&g)'r   iK  aj  
Pipelines provide a way to transmit multiple commands to the Redis server
in one transmission.  This is convenient for batch processing, such as
saving all the values in a list to Redis.

All commands executed within a pipeline(when running in transactional mode,
which is the default behavior) are wrapped with MULTI and EXEC
calls. This guarantees all commands executed in the pipeline will be
executed atomically.

Any command raising an exception does *not* halt the execution of
subsequent commands in the pipeline. Instead, the exception is caught
and its instance is placed into the response list returned by execute().
Code iterating over the response list should be able to deal with an
instance of an exception as a potential value. In general, these will be
ResponseError exceptions, such as those raised when issuing a command
on a key of a different datatype.
>   EXECDISCARDUNWATCHrr   c                     Xl         S U l        X l        X0l        X@l        SU l        / U l        [        5       U l        SU l	        g )NF)
rr   r   r   r   r   watchingcommand_stackr  scriptsexplicit_transaction)rB   rr   r   r   r   s        rE   rF   Pipeline.__init__a  sB      /04"4&$$'E$)!r6   r=   c                     U $ r?   r^   r   s    rE   r  Pipeline.__enter__r  r  r6   c                 $    U R                  5         g r?   r  r  s       rE   r  Pipeline.__exit__u  r   r6   c                 F     U R                  5         g ! [         a     g f = fr?   r  r   s    rE   r#  Pipeline.__del__x  r%  r&  c                 ,    [        U R                  5      $ r?   )lenrC  r   s    rE   __len__Pipeline.__len__~  s    4%%&&r6   c                     g)z1Pipeline instances should always evaluate to TrueTr^   r   s    rE   __bool__Pipeline.__bool__  s    r6   Nc                    / U l         [        5       U l        U R                  (       aG  U R                  (       a6   U R                  R                  S5        U R                  R                  5         SU l        SU l	        U R                  (       a-  U R                  R                  U R                  5        S U l        g g ! [         a    U R                  R                  5          Nsf = f)Nr@  F)rC  r  rD  rB  r   r/  rP  r&   r*  rE  rr   r)  r   s    rE   r  Pipeline.reset  s    u ==T__- ,,Y7--/
 $)! ??  ((9"DO  # -**,-s   5B< <$C#"C#c                 $    U R                  5         g)zClose the pipelineNr  r   s    rE   r  Pipeline.close  s    

r6   c                     U R                   (       a  [        S5      eU R                  (       a  [        S5      eSU l         g)zz
Start a transactional block of the pipeline after WATCH commands
are issued. End the transactional block with `execute`.
z"Cannot issue nested calls to MULTIz:Commands without an initial WATCH have already been issuedTN)rE  r)   rC  r   s    rE   multiPipeline.multi  s<    
 $$ABBL  %)!r6   c                     U R                   (       d	  US   S:X  a#  U R                  (       d  U R                  " U0 UD6$ U R                  " U0 UD6$ )Nr   WATCH)rB  rE  immediate_execute_commandpipeline_execute_command)rB   r2  rw   s      rE   r<  Pipeline.execute_command  sH    MMT!W/9R9R114B6BB,,d=f==r6   r,  errorc                     UR                  5         U R                  (       a2  U R                  5         [        S[	        U5      R
                   S35      eg)aE  
Close the connection reset watching state and
raise an exception if we were watching.

The supported exceptions are already checked in the
retry object so we don't need to do it here.

After we disconnect the connection, it will try to reconnect and
do a health check as part of the send_command logic(on connection level).
A ) occurred while watching one or more keysN)r*  rB  r  r+   r   r_   rB   r,  r`  s      rE   #_disconnect_reset_raise_on_watching,Pipeline._disconnect_reset_raise_on_watching  sJ     	
 ==JJLT%[))**ST  r6   c                    ^ ^^^^ TS   mT R                   mT(       d!  T R                  R                  5       mTT l         TR                  R	                  UUUUU 4S jUU 4S j5      $ )z
Execute a command immediately, but don't auto-retry on the supported
errors for retry if we're already WATCHing a variable.
Used when issuing WATCH or subsequent commands retrieving their values but before
MULTI is called.
r   c                  2   > TR                   " TT/T Q70 TD6$ r?   r@  rA  s   rE   rB  4Pipeline.immediate_execute_command.<locals>.<lambda>  s%    D55l%)-4r6   c                 (   > TR                  TU 5      $ r?   )re  r`  r,  rB   s    rE   rB  ri    s    $BB4Or6   )r   rr   r   r   rH  )rB   r2  r3  r1  r,  s   ```@@rE   r]  "Pipeline.immediate_execute_command  s\     Aw''668D"DOzz))  P	
 	
r6   c                 >    U R                   R                  X45        U $ )a:  
Stage a command to be executed when execute() is next called

Returns the current Pipeline object back so commands can be
chained together, such as:

pipe = pipe.set('foo', 'bar').incr('baz').decr('bang')

At some other point, you can then run: pipe.execute(),
which will execute all commands queued in the pipe.
)rC  appendr;  s      rE   r^  !Pipeline.pipeline_execute_command  s     	!!4/2r6   r   c                    [        S0 4/US0 4/5      nUR                  U VVs/ s H  u  pV[        U;  d  M  UPM     snn5      nUR                  U5        / n U R	                  US5        [        U5       HC  u  p[        US   ;   a  UR                  XS   [           45        M0   U R	                  US5        ME      U R	                  US5      nSU l
        Uc  [        S5      eU H  u  pUR                  X5        M     [        U5      [        U5      :w  a%  U R                  R                  5         [        S5      eU(       a  U R!                  X,5        / n[#        X5       Hl  u  p[%        U[&        5      (       dA  Uu  pVUR)                  S	S 5        US   nUU R*                  ;   a  U R*                  U   " U40 UD6nUR                  U5        Mn     U$ s  snnf ! [
         a  n	UR                  SU	45         S n	A	GNS n	A	ff = f! [
         a6  n	U R                  XS-   US   5        UR                  X45         S n	A	GM  S n	A	ff = f! [         a    U(       a  US   S   ee f = f)
N)MULTI)r>  rF  r   r   FzWatched variable changed.z6Wrong number of response items from pipeline executionrO  )r   pack_commandsr7   send_packed_commandr0  r*   rn  	enumerateannotate_exceptionr'   rB  r+   insertrN  r   r*  raise_first_errorziprs  r"  rs   r   )rB   r   commandsraise_on_errorcmdsr2  r3  all_cmdserrorsr7  ir   rQ  r<   rcmdr1  s                    rE   _execute_transactionPipeline._execute_transaction  sZ    z2&'YO3DE++'+Mtmd~W/LTtM
 	&&x0	"
C0
 $H-JA+q!*^"<=>*''
C8 .	**:s;H 899 DAOOA!  x=CM)OO&&(H 
 ""86 (-FAa++ #FD)#Aw4#:#:://=aK7KAKKN . C N  	"MM1a&!!	" % *++A1ugajAMM1&))*  	Qil"	sF   G
G
G (H?I
 
H&G??H
I*II
I%c                 h   UR                  U VVs/ s H  u  pEUPM	     snn5      nUR                  U5        / nU H+  u  pH UR                  U R                  " XS   40 UD65        M-     U(       a  U R                  X'5        U$ s  snnf ! [         a  n	UR                  U	5         S n	A	Mp  S n	A	ff = fr  )rr  rs  rn  r0  r*   rw  )
rB   r   ry  rz  r2  rF  r|  	responsesr3  r7  s
             rE   _execute_pipelinePipeline._execute_pipeline9  s    ++,JgdT,JK&&x0	%MD$  !4!4Za!TG!TU & ""87 -K ! $  ##$s   B
%B
B1B,,B1c                     [        U5       H6  u  p4[        U[        5      (       d  M  U R                  XCS-   X   S   5        Ue   g )Nr   r   )rt  rs  r*   ru  )rB   ry  rQ  r~  r  s        rE   rw  Pipeline.raise_first_errorJ  s?    h'DA!]++''q5(+a.A (r6   c                     SR                  [        [        U5      5      nSU S[        U5       SUR                  S    3nU4UR                  SS  -   Ul        g )Nrh  z
Command # z (z) of pipeline caused error: r   r   )rz  mapr3   r5   r2  )rB   	exceptionnumberr   r  msgs         rE   ru  Pipeline.annotate_exceptionP  sc    hhs8W-.=#5"6 7&^^A./1 	 ).."44	r6   c                     [         R                  " XU40 UD6nX R                  ;   a	  SU l        U$ US:X  a  SU l        U$ )NFr\  T)rl   r0  UNWATCH_COMMANDSrB  )rB   r   r1  r3  results        rE   r0  Pipeline.parse_responseX  sI    %%dPP000!DM  W$ DMr6   c                 $   [        U R                  5      nU R                  nU Vs/ s H  o3R                  PM     nnU" S/UQ76 n[	        U5      (       d6  [        X5       H&  u  p6U(       a  M  U" SUR                  5      Ul        M(     g g s  snf )NzSCRIPT EXISTSzSCRIPT LOAD)listrD  r]  shaallrx  script)rB   rD  	immediatesshasexistsexists          rE   load_scriptsPipeline.load_scripts`  s}    t||$22	&'w!w' ?2T26{{0u%mQXX>AE 1 	 (s   Bc                     UR                  5         U R                  (       a"  [        S[        U5      R                   S35      eg)a-  
Close the connection, raise an exception if we were watching.

The supported exceptions are already checked in the
retry object so we don't need to do it here.

After we disconnect the connection, it will try to reconnect and
do a health check as part of the send_command logic(on connection level).
rb  rc  N)r*  rB  r+   r   r_   rd  s      rE   _disconnect_raise_on_watching&Pipeline._disconnect_raise_on_watchingm  sA     	 ==T%[))**ST  r6   rz  c                   ^ ^^^^ T R                   mT(       d  T R                  (       d  / $ T R                  (       a  T R                  5         T R                  (       d  T R
                  (       a  T R                  mOT R                  mT R                  mT(       d!  T R                  R                  5       mTT l         TR                  R                  UUUU4S jUU 4S j5      T R                  5         $ ! T R                  5         f = f)z0Execute all the commands in the current pipelinec                     > T" T TT5      $ r?   r^   )r,  r   rz  stacks   rE   rB  "Pipeline.execute.<locals>.<lambda>  s    e^<r6   c                 (   > TR                  TU 5      $ r?   )r  rk  s    rE   rB  r    s    d@@uMr6   )rC  rB  rD  r  r   rE  r  r  r   rr   r   r   rH  r  )rB   rz  r,  r   r  s   ``@@@rE   r   Pipeline.execute  s    ""T]]I<<t88//G,,G''668D #DO	::--<M JJLDJJLs   ='C5 5Dc                 &    U R                  S5        g)zO
Flushes all previously queued commands
See: https://redis.io/commands/DISCARD
r?  Nr  r   s    rE   discardPipeline.discard  s    
 	Y'r6   c                 `    U R                   (       a  [        S5      eU R                  " S/UQ76 $ )z$Watches the values at keys ``names``z"Cannot issue a WATCH after a MULTIr\  )rE  r)   r<  )rB   namess     rE   r   Pipeline.watch  s-    $$ABB##G4e44r6   c                 \    U R                   =(       a    U R                  S5      =(       d    S$ )z'Unwatches all previously specified keysr@  T)rB  r<  r   s    rE   unwatchPipeline.unwatch  s!    }}@!5!5i!@HDHr6   )	rC  r   rr   rE  r   rD  r   r   rB  rW  rV  )T)'r_   r`   ra   rb   rc   r  r   rF   r  r  r#  rY  rO  r[  rR  r  r  rY  r<  r   r"  re  r]  r^  r   r   r  r  rw  ru  r0  r  r  r   r   r  r   r  re   r^   r6   rE   r   r   K  s   & 6*'*"' '$ #0)>
   
	4
*F$F	FP"5?   
	.d d3i :(5I Ir6   r   )Ur   r  r   r   	itertoolsr   typingr   r   r   r   r   r	   r
   r   r   r   redis._parsers.encodersr   redis._parsers.helpersr   r   r   r   redis.backoffr   redis.cacher   r   redis.commandsr   r   r   r   redis.commands.corer   redis.connectionr   r   r   r   r   redis.credentialsr    redis.eventr!   r"   r#   r$   r%   redis.exceptionsr&   r'   r(   r)   r*   r+   
redis.lockr-   redis.maint_notificationsr.   redis.retryr/   redis.utilsr0   r1   r2   r3   r4   r5   r   OpenSSL	SYM_EMPTYr7   r8   r  r:   ri   rl   StrictRedisr  r  Threadr)  r   r^   r6   rE   <module>r     s    	      ,  7 3  '  1      	! $ 6	 	Q	*/? Q	*h I< I<XB BJ-)) -`eIu eIr6   