U
    dc.                    @   s  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mZmZmZ d dlmZmZmZ d dlmZ d dlmZmZmZmZmZmZmZmZ d dlmZ d d	l m!Z! d d
l"m#Z#m$Z$ dZ%dZ&dZ'dd Z(dd Z)G dd de*Z+dd Z,dd Z-dd Z.dd Z/e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0dZ1dd Z2dd  Z3d!d" Z4d#d$ Z5d%d& Z6dd(d)Z7d*d+ Z8d,d- Z9d.d/ Z:d0d1 Z;d2d3 Z<d4d5 Z=d6d7 Z>d8d9 Z?d:d; Z@d<d= ZAd>d? ZBd@dA ZCdBdC ZDdDdE ZEdFdG ZFdHdI ZGdJdK ZHdLdM ZIdNdO ZJdPdQ ZKdRdS ZLdTdU ZMdVdW ZNdXdY ZOdZd[ ZPd\d] ZQd^d_ ZRd`da ZSdbdc ZTddde ZUdfdg ZVdhdi ZWdjdk ZXdldm ZYdndo ZZdpdq Z[drds Z\G dtdu duZ]G dvdw dwe]eeeZ^e^Z_G dxdy dyZ`G dzd{ d{ZaG d|d} d}ejbZcG d~d de^ZddS )    N)chain)Optional)CoreCommandsRedisModuleCommandsSentinelCommandslist_or_args)ConnectionPoolSSLConnectionUnixDomainSocketConnection)CredentialProvider)ConnectionErrorExecAbortErrorModuleErrorPubSubError
RedisErrorResponseErrorTimeoutError
WatchErrorLock)Retry)safe_strstr_if_bytes    EMPTY_RESPONSENEVER_DECODEc                 C   s8   | sdS zt | } W n tk
r*   Y dS X tj| S )z5Converts a unix timestamp to a Python datetime objectN)int
ValueErrordatetimefromtimestampresponse r"   0/tmp/pip-unpacked-wheel-xj5sloo9/redis/client.pytimestamp_to_datetime'   s    r$   c                 C   s   t |  |S N)dictfromkeyssplit)Z
key_stringcallbackr"   r"   r#   string_keys_to_dict2   s    r*   c                       sf   e Zd ZdZdd Z fddZ fddZ fdd	Zd fdd	Z fddZ	 fddZ
  ZS )CaseInsensitiveDictz?Case insensitive dict implementation. Assumes string keys only.c                 C   s"   |  D ]\}}|| | < qd S r%   )itemsupper)selfdatakvr"   r"   r#   __init__9   s    zCaseInsensitiveDict.__init__c                    s   t  | S r%   )super__contains__r-   r.   r0   	__class__r"   r#   r4   =   s    z CaseInsensitiveDict.__contains__c                    s   t  |  d S r%   )r3   __delitem__r-   r5   r6   r"   r#   r8   @   s    zCaseInsensitiveDict.__delitem__c                    s   t  | S r%   )r3   __getitem__r-   r5   r6   r"   r#   r9   C   s    zCaseInsensitiveDict.__getitem__Nc                    s   t  | |S r%   )r3   getr-   )r.   r0   defaultr6   r"   r#   r:   F   s    zCaseInsensitiveDict.getc                    s   t  | | d S r%   )r3   __setitem__r-   )r.   r0   r1   r6   r"   r#   r<   I   s    zCaseInsensitiveDict.__setitem__c                    s   t |}t | d S r%   )r+   r3   updater.   r/   r6   r"   r#   r=   L   s    zCaseInsensitiveDict.update)N)__name__
__module____qualname____doc__r2   r4   r8   r9   r:   r<   r=   __classcell__r"   r"   r6   r#   r+   6   s   r+   c                 C   sP   t | } d|  } tdd |  D } d}|D ]}|| kr.t| | | |< q.| S )zDParse the results of Redis's DEBUG OBJECT command into a Python dictztype:c                 s   s   | ]}| d V  qdS :Nr(   ).0kvr"   r"   r#   	<genexpr>W   s     z%parse_debug_object.<locals>.<genexpr>)refcountZserializedlengthZlruZlru_seconds_idle)r   r&   r(   r   )r!   Z
int_fieldsfieldr"   r"   r#   parse_debug_objectQ   s    rL   c                 C   s   |dkrt | S | S )z&Parse the results of an OBJECT command)ZidletimerJ   )int_or_none)r!   Zinfotyper"   r"   r#   parse_objectc   s    rN   c                    s   i }t | }  fdd |  D ]}|r |ds |ddkr|dd\}}|dkrh|dd\}}|dkr|d	g  | q |||< q |d
g | q |S )z;Parse the result of Redis's INFO command into a Python dictc                    s   d| ksd| krLz d| kr$t | W S t| W S W q tk
rH   |  Y S X n4i }| dD ] }|dd\}} |||< qZ|S d S )N,=.   )floatr   r   r(   rsplit)valueZsub_dictitemr0   r1   	get_valuer"   r#   rX   o   s    
zparse_info.<locals>.get_value#rE   rR   Zcmdstat_hostmodulemodulesZ__raw__)r   
splitlines
startswithfindr(   rT   
setdefaultappend)r!   infolinekeyrU   r"   rW   r#   
parse_infoj   s    re   c                 K   s@   t | ddd}| D ]$\}}|drt |ddd||< q|S )z!Parse the results of MEMORY STATST)decode_keysdecode_string_valueszdb.)pairs_to_dictr,   r^   )r!   kwargsstatsrd   rU   r"   r"   r#   parse_memory_stats   s    
  rk   )zcan-failover-its-masterzconfig-epochzdown-after-millisecondszfailover-timeoutzinfo-refreshzlast-hello-messagezlast-ok-ping-replyzlast-ping-replyzlast-ping-sentzmaster-link-down-timezmaster-portznum-other-sentinelsz
num-slaveszo-down-timezpending-commandszparallel-syncsportZquorumzrole-reported-timezs-down-timezslave-priorityzslave-repl-offsetzvoted-leader-epochc                 C   s:   t | t}t|d d}dD ]\}}||k||< q |S )NflagsrO   ))Z	is_masterZmaster)Zis_slaveZslave)Zis_sdownZs_down)Zis_odownZo_down)Zis_sentinelsentinel)Zis_disconnectedZdisconnected)Zis_master_downZmaster_down)pairs_to_dict_typedSENTINEL_STATE_TYPESsetr(   )rV   resultrm   nameflagr"   r"   r#   parse_sentinel_state   s
    
	ru   c                 C   s   t tt| S r%   ru   mapr   r    r"   r"   r#   parse_sentinel_master   s    rx   c                 C   s,   i }| D ]}t tt|}|||d < q|S )Nrs   rv   )r!   rr   rV   stater"   r"   r#   parse_sentinel_masters   s
    rz   c                 C   s   dd | D S )Nc                 S   s   g | ]}t tt|qS r"   rv   rG   rV   r"   r"   r#   
<listcomp>   s     z7parse_sentinel_slaves_and_sentinels.<locals>.<listcomp>r"   r    r"   r"   r#   #parse_sentinel_slaves_and_sentinels   s    r}   c                 C   s   | r| d t | d fpd S Nr   rR   r   r    r"   r"   r#   parse_sentinel_get_master   s    r   Fc                 C   st   | dkri S |s|rZ| ddd }|r0t t|}| ddd }|rLt t|}tt||S t| }tt||S dS )z-Create a dict given a list of key/value pairsN   rR   )rw   r   r&   zipiter)r!   rf   rg   keysvaluesitr"   r"   r#   rh      s    

rh   c              	   C   sZ   t | }i }t||D ]>\}}||krLz|| |}W n tk
rJ   Y nX |||< q|S r%   )r   r   	Exception)r!   Z	type_infor   rr   rd   rU   r"   r"   r#   ro      s    
ro   c                 K   s:   | r| ds| S | dt}t| }tt|t||S )zr
    If ``withscores`` is specified in the options, return the response as
    a list of (value, score) pairs
    Z
withscoresscore_cast_func)r:   rS   r   listr   rw   )r!   optionsr   r   r"   r"   r#   zset_score_pairs  s
    r   c                    s:   r| dsS |d  tt fddt D  S )z
    If ``groups`` is specified, return the response as a list of
    n-element tuples with n being the value found in options['groups']
    groupsc                    s   g | ]}|d   qS r%   r"   rG   inr!   r"   r#   r|     s     z&sort_return_tuples.<locals>.<listcomp>)r:   r   r   ranger!   r   r"   r   r#   sort_return_tuples  s    r   c                 C   s   | d krd S t | S r%   r   r    r"   r"   r#   rM     s    rM   c                 C   sL   | d krd S g }| D ]2}|d k	r<| |d t|d f q| d q|S )Nr   rR   )NN)ra   rh   )r!   r/   rr"   r"   r#   parse_stream_list  s    r   c                 C   s   t | ddS )NTrf   rh   r    r"   r"   r#   pairs_to_dict_with_str_keys+  s    r   c                 C   s   t tt| S r%   )r   rw   r   r    r"   r"   r#   parse_list_of_dicts/  s    r   c                 K   s   | ddr| S t| S )Nparse_justidFr:   r   r   r"   r"   r#   parse_xclaim3  s    r   c                 K   s(   | ddr| d S t| d | d< | S )Nr   FrR   r   r   r"   r"   r#   parse_xautoclaim9  s    r   c                 K   s   t | dd}|ddsj|d }|d k	r@|d t |d f|d< |d }|d k	r|d t |d f|d< n,d	d
 |d D |d< dd |d D |d< |S )NTr   fullFzfirst-entryr   rR   z
last-entryc                 S   s   i | ]\}}|t |qS r"   r   )rG   Z_identryr"   r"   r#   
<dictcomp>J  s      z&parse_xinfo_stream.<locals>.<dictcomp>entriesc                 S   s   g | ]}t |d dqS )Tr   r   )rG   groupr"   r"   r#   r|   K  s    z&parse_xinfo_stream.<locals>.<listcomp>r   )rh   r:   )r!   r   r/   firstlastr"   r"   r#   parse_xinfo_stream@  s    
r   c                 C   s   | d krg S dd | D S )Nc                 S   s    g | ]}|d  t |d gqS )r   rR   )r   rG   r   r"   r"   r#   r|   T  s     zparse_xread.<locals>.<listcomp>r"   r    r"   r"   r#   parse_xreadQ  s    r   c                 K   sD   | ddrt| S dd | d p$g D }| d | d | d |d	S )
NZparse_detailFc                 S   s   g | ]\}}|t |d qS ))rs   pendingr   )rG   r   pr"   r"   r#   r|   Z  s     z"parse_xpending.<locals>.<listcomp>   r   rR   r   )r   minmax	consumers)r:   parse_xpending_range)r!   r   r   r"   r"   r#   parse_xpendingW  s    r   c                    s   d  fdd| D S )N)Z
message_idZconsumerZtime_since_deliveredZtimes_deliveredc                    s   g | ]}t t |qS r"   )r&   r   r   r0   r"   r#   r|   e  s     z(parse_xpending_range.<locals>.<listcomp>r"   r    r"   r   r#   r   c  s    r   c                 C   s   | d krd S t | S r%   rS   r    r"   r"   r#   float_or_noneh  s    r   c                 C   s   t | dkS NOKr   r    r"   r"   r#   bool_okn  s    r   c                 K   s&   | d krd S | drt| S t| S )NZas_score)r:   rS   r   r   r"   r"   r#   
parse_zaddr  s
    
r   c                 K   s8   g }t |  D ]"}|tdd |dD  q|S )Nc                 s   s   | ]}| d dV  qdS )rP   rR   NrF   )rG   pairr"   r"   r#   rI   ~  s     z$parse_client_list.<locals>.<genexpr> )r   r]   ra   r&   r(   )r!   r   Zclientscr"   r"   r#   parse_client_listz  s     r   c                 K   s   dd | D } | rt | pi S )Nc                 S   s    g | ]}|d k	rt |nd qS r%   r   r   r"   r"   r#   r|     s     z$parse_config_get.<locals>.<listcomp>r   r   r"   r"   r#   parse_config_get  s    r   c                 K   s   | \}}t ||fS r%   r   r!   r   cursorr   r"   r"   r#   
parse_scan  s    r   c                 K   s    | \}}t ||rt|pi fS r%   )r   rh   r   r"   r"   r#   parse_hscan  s    r   c                 K   s8   | dt}| \}}t|}t|tt|t||fS )Nr   )r:   rS   r   r   r   r   rw   )r!   r   r   r   r   r   r"   r"   r#   parse_zscan  s    r   c                 K   s   dd | D S )Nc                 S   s    g | ]}|d k	rt |nd qS r%   r   )rG   Zscorer"   r"   r#   r|     s     z!parse_zmscore.<locals>.<listcomp>r"   r   r"   r"   r#   parse_zmscore  s    r   c                    s2   | ddrdndfdd  fdd| D S )	Ndecode_responsesFr       c                    sd   | d t | d t | d d}t| d trB | d |d< n| d |d<  | d |d< |S )	Nr   rR   r   )id
start_timedurationr   commandZ
complexity   )r   
isinstancer   join)rV   rr   )spacer"   r#   
parse_item  s     z%parse_slowlog_get.<locals>.parse_itemc                    s   g | ]} |qS r"   r"   r{   )r   r"   r#   r|     s     z%parse_slowlog_get.<locals>.<listcomp>)r:   r   r"   )r   r   r#   parse_slowlog_get  s    r   c                 K   s~   | ddrt| S | ddrv| ddr@dd | d D }ndd | d D }t| d	 |t| d
 t| d iS t| S )a  
    Parse the response from `STRALGO` command.
    Without modifiers the returned value is string.
    When LEN is given the command returns the length of the result
    (i.e integer).
    When IDX is given the command returns a dictionary with the LCS
    length and all the ranges in both the strings, start and end
    offset for each string, where there are matches.
    When WITHMATCHLEN is given, each array representing a match will
    also have the length of the match at the beginning of the array.
    lenFidxZwithmatchlenc              	   S   s0   g | ](}t |d  gttt|dd   qS )rZ   N)r   r   rw   tuplerG   matchr"   r"   r#   r|     s   z!parse_stralgo.<locals>.<listcomp>rR   c                 S   s   g | ]}t tt|qS r"   )r   rw   r   r   r"   r"   r#   r|     s     r   r   r   )r:   r   r   )r!   r   matchesr"   r"   r#   parse_stralgo  s    
 
 
r   c                 K   s   t | } tdd |  D S )Nc                 s   s   | ]}|r| d V  qdS rD   rF   )rG   rc   r"   r"   r#   rI     s      z%parse_cluster_info.<locals>.<genexpr>)r   r&   r]   r   r"   r"   r#   parse_cluster_info  s    r   c              
   C   s   |  d}|  dd d \}}}}}}}}	| dd }||||||g g |	dkrVdndd	}
t|d	krt|dd  \}}|| |
d
< |
d< ||
fS )Nr      @r   	connectedTF)	node_idrm   	master_idZlast_ping_sentZlast_pong_rcvdepochslots
migrationsr   	   r   r   )r(   r   _parse_slots)rc   Z
line_itemsr   addrrm   r   pingpongr   r   Z	node_dictr   r   r"   r"   r#   _parse_node_line  s"    
"r   c                 C   s   g g  }}| D ]}d|krF|dd  dd\}}|||dd qd|krz|dd  dd\}}|||dd qdd	 | d
D }|| q||fS )Nz->-rR   rZ   Z	migrating)Zslotr   ry   z-<-Z	importingc                 S   s   g | ]}|qS r"   r"   )rG   slr"   r"   r#   r|     s     z _parse_slots.<locals>.<listcomp>-)r(   ra   )Zslot_rangesr   r   Zs_rangeZslot_idZdst_node_idZsrc_node_idr"   r"   r#   r     s    


r   c                 K   s(   t | ttfr|  } tdd | D S )z
    @see: https://redis.io/commands/cluster-nodes  # string / bytes
    @see: https://redis.io/commands/cluster-replicas # list of string / bytes
    c                 s   s   | ]}t t|V  qd S r%   )r   r   )rG   noder"   r"   r#   rI     s     z&parse_cluster_nodes.<locals>.<genexpr>)r   strbytesr]   r&   r   r"   r"   r#   parse_cluster_nodes  s    r   c                    s   d sd r| S t | tkr(| g}n| }d sHd sHd sH|S tdd td d	d g fd
ddD 7 fdd|D S )z
    Parse the response of 'GEOSEARCH', GEORADIUS' and 'GEORADIUSBYMEMBER'
    commands according to 'withdist', 'withhash' and 'withcoord' labels.
    storeZ
store_distwithdist	withcoordwithhashc                 S   s   t | d t | d fS r~   r   Zllr"   r"   r#   <lambda>  r   z)parse_geosearch_generic.<locals>.<lambda>)r   r   r   c                 S   s   | S r%   r"   xr"   r"   r#   r      r   c                    s   g | ]}| r | qS r"   r"   )rG   o)castr   r"   r#   r|   !  s      z+parse_geosearch_generic.<locals>.<listcomp>)r   r   r   c                    s$   g | ]}t td d t |qS )c                 S   s   | d | d S r~   r"   )Zfvr"   r"   r#   r   "  r   z4parse_geosearch_generic.<locals>.<listcomp>.<lambda>)r   rw   r   r   )fr"   r#   r|   "  s     )typer   rS   r   )r!   r   Zresponse_listr"   )r   r   r   r#   parse_geosearch_generic  s    
r   c                 K   s   i }| D ]}i }t |d }||d< t|d |d< dd |d D |d< |d	 |d
< |d |d< |d |d< t|dkr|d |d< |d |d< |d |d< |||< q|S )Nr   rs   rR   arityc                 S   s   g | ]}t |qS r"   r   )rG   rt   r"   r"   r#   r|   ,  s     z!parse_command.<locals>.<listcomp>r   rm   r   Zfirst_key_posr   Zlast_key_pos   Z
step_count   Ztipsr   Zkey_specificationsr   subcommands)r   r   r   )r!   r   commandsr   Zcmd_dictcmd_namer"   r"   r#   parse_command%  s     
r   c                 K   s"   t t| dd d | dd d S )Nr   r   rR   )r   r   r   r"   r"   r#   parse_pubsub_numsub8  s    r   c                 K   s   t | tr| S t| dkS r   r   r   r   r   r"   r"   r#   parse_client_kill<  s    
r  c                 K   sx  | d krd S t | dd}ttt|d |d< ttt|d |d< t|d |d< t|d tspt|d trtt|d d|d< |d dgkrg |d< d	|krt|d	 tst|d	 trtt|d	 d|d	< |d	 dgkrg |d	< d
|krdd |d
 D |d
< g g  }}|d dD ]&}d|krF|| n
|| q,||d< ||d< d|d k|d< |S )NTr   rm   	passwordsr   r   r    channels	selectorsc                 S   s   g | ]}t tt|qS r"   r   rw   r   )rG   selectorr"   r"   r#   r|   U  s    z%parse_acl_getuser.<locals>.<listcomp>r   
categoriesonZenabled)	rh   r   rw   r   r   r   r   r(   ra   )r!   r   r/   r   r  r   r"   r"   r#   parse_acl_getuserB  s8    



r
  c                 K   sp   | d krd S t | trdg }| D ]B}t|dd}|dd}t||d< t|d |d< || qnt| }|S )NTzclient-infor  zage-seconds)r   r   rh   r:   parse_client_inforS   ra   r   )r!   r   r/   logZlog_dataclient_infor"   r"   r#   parse_acl_logg  s    
r  c                 C   sP   i }t | d}|D ]}|d\}} | ||< qdD ]}t|| ||< q6|S )zg
    Parsing client-info in ACL Log in following format.
    "key1=value1 key2=value2 key3=value3"
    r   rP   >   r   tot-memobl	qbuf-freedbpsubagemultiollidleomemargv-memsubqbuf)r   r(   r   )rU   r  Zinfosrb   rd   Zint_keyr"   r"   r#   r  y  s    
r  c                 C   s   t | tr| dS NT)r   r   r    r"   r"   r#   parse_module_result  s    
r  c                 K   s   | dr| S | ot| dkS )z
    Handle SET result since GET argument is available since Redis 6.2.
    Parsing SET result into:
    - BOOL
    - String when GET argument is used
    r:   r   )r:   r   r   r"   r"   r#   parse_set_result  s    
r  c                ~   @   s  e Zd Zedeedeedeeddd edeedeed	e	ed
dd eddd ede
eddd edeedeedeeddd dd eeedd dd e	ee	e	dd eeeeeee	dd e	edd e	e	dd dd e	e	e	e	dd edd e	eee	e	e	e	e	eeed d ee	e	ee	e	e	d!d d"d eeed#d eeee	eeeed$d ed%d e	e e!d&d ee"d'd e	e	ee	e	e	e#e$e%e	e	e	e&e	e&e'e(ee	e"d(d e)e*e	eee	e+e+e,e-e.e/e0d)nZ1d*S )+AbstractRediszyAUTH COPY EXPIRE EXPIREAT PEXPIRE PEXPIREAT HEXISTS HMSET MOVE MSETNX PERSIST PSETEX RENAMENX SISMEMBER SMOVE SETEX SETNXa  BITCOUNT BITPOS DECRBY DEL EXISTS GEOADD GETBIT HDEL HLEN HSTRLEN INCRBY LINSERT LLEN LPUSHX PFADD PFCOUNT RPUSHX SADD SCARD SDIFFSTORE SETBIT SETRANGE SINTERSTORE SREM STRLEN SUNIONSTORE UNLINK XACK XDEL XLEN XTRIM ZCARD ZLEXCOUNT ZREM ZREMRANGEBYLEX ZREMRANGEBYRANK ZREMRANGEBYSCOREzINCRBYFLOAT HINCRBYFLOATzLPUSH RPUSHc                 C   s   t | tr| pt| dkS r   r   r   r"   r"   r#   r     r   zAbstractRedis.<lambda>ZSORTzZSCORE ZINCRBY GEODISTz|FLUSHALL FLUSHDB LSET LTRIM MSET PFMERGE ASKING READONLY READWRITE RENAME SAVE SELECT SHUTDOWN SLAVEOF SWAPDB WATCH UNWATCH zBLPOP BRPOPc                 C   s   | rt | pd S r%   )r   r   r"   r"   r#   r     r   zSDIFF SINTER SMEMBERS SUNIONc                 C   s   | rt | pt  S r%   )rq   r   r"   r"   r#   r     r   zSZPOPMAX ZPOPMIN ZINTER ZDIFF ZUNION ZRANGE ZRANGEBYSCORE ZREVRANGE ZREVRANGEBYSCOREzBZPOPMIN BZPOPMAXc                 C   s"   | r| d | d t | d fp d S )Nr   rR   r   r   r   r"   r"   r#   r     r   zZRANK ZREVRANKzXREVRANGE XRANGEzXREAD XREADGROUPzBGREWRITEAOF BGSAVEc                 C   s   dS r  r"   r   r"   r"   r#   r     r   c                 C   s   t tt| S r%   r  r   r"   r"   r#   r     r   c                 C   s   t tt| S r%   r  r   r"   r"   r#   r     r   c                 C   s   t tt| S r%   r  r   r"   r"   r#   r     r   c                 C   s   t tt| S r%   r  r   r"   r"   r#   r     r   c                 C   s   | rt | dkpdS )NrR   Fr   r   r"   r"   r#   r     r   c                 C   s   t tt| S r%   r  r   r"   r"   r#   r     r   c                 C   s   t | S r%   r   r   r"   r"   r#   r     r   c                 C   s   t | S r%   r   r   r"   r"   r#   r     r   c                 C   s   t tt| S r%   r  r   r"   r"   r#   r     r   c                 C   s   t | S r%   r   r   r"   r"   r#   r     r   c                 C   s   t tt| S r%   r  r   r"   r"   r#   r     r   c                 C   s   t tt| S r%   r  r   r"   r"   r#   r     r   c                 C   s   t tdd | S )Nc                 S   s$   | d k	r t | d t | d fS d S r~   r   r   r"   r"   r#   r     r   z(AbstractRedis.<lambda>.<locals>.<lambda>)r   rw   r   r"   r"   r#   r     s   c                 C   s   | rt | pi S r%   r   r   r"   r"   r#   r     r   c                 C   s   dd | D S )Nc                 S   s   g | ]}t |qS r"   r   )rG   mr"   r"   r#   r|     s     z*AbstractRedis.<lambda>.<locals>.<listcomp>r"   r   r"   r"   r#   r     r   c                 C   s   t | dkS )NZPONGr   r   r"   r"   r#   r      r   c                 C   s   | r| p
d S r%   r"   r   r"   r"   r#   r   $  r   c                 C   s   t tt| S r%   )r   rw   boolr   r"   r"   r#   r   '  r   c                 C   s   t | d t | d fS r~   r   r   r"   r"   r#   r   <  r   )nzACL CATzACL DELUSERzACL GENPASSzACL GETUSERzACL HELPzACL LISTzACL LOADzACL LOGzACL SAVEzACL SETUSERz	ACL USERSz
ACL WHOAMIzCLIENT GETNAMEz	CLIENT IDzCLIENT KILLzCLIENT LISTzCLIENT INFOzCLIENT SETNAMEzCLIENT UNBLOCKzCLIENT PAUSEzCLIENT GETREDIRzCLIENT TRACKINGINFOzCLUSTER ADDSLOTSzCLUSTER ADDSLOTSRANGEzCLUSTER COUNT-FAILURE-REPORTSzCLUSTER COUNTKEYSINSLOTzCLUSTER DELSLOTSzCLUSTER DELSLOTSRANGEzCLUSTER FAILOVERzCLUSTER FORGETzCLUSTER GETKEYSINSLOTzCLUSTER INFOzCLUSTER KEYSLOTzCLUSTER MEETzCLUSTER NODESzCLUSTER REPLICASzCLUSTER REPLICATEzCLUSTER RESETzCLUSTER SAVECONFIGzCLUSTER SET-CONFIG-EPOCHzCLUSTER SETSLOTzCLUSTER SLAVESZCOMMANDzCOMMAND COUNTzCOMMAND GETKEYSz
CONFIG GETzCONFIG RESETSTATz
CONFIG SETzDEBUG OBJECTzFUNCTION DELETEzFUNCTION FLUSHzFUNCTION RESTOREZGEOHASHZGEOPOSZ	GEOSEARCHZ	GEORADIUSZGEORADIUSBYMEMBERZHGETALLZHSCANINFOZLASTSAVEzMEMORY PURGEzMEMORY STATSzMEMORY USAGEzMODULE LOADzMODULE UNLOADzMODULE LISTZOBJECTPINGZQUITZSTRALGOzPUBSUB NUMSUBZ	RANDOMKEYRESETZSCANSCRIPT EXISTSzSCRIPT FLUSHzSCRIPT KILLSCRIPT LOADzSENTINEL CKQUORUMzSENTINEL FAILOVERzSENTINEL FLUSHCONFIGz SENTINEL GET-MASTER-ADDR-BY-NAMEzSENTINEL MASTERzSENTINEL MASTERSzSENTINEL MONITORzSENTINEL RESETzSENTINEL REMOVEzSENTINEL SENTINELSzSENTINEL SETzSENTINEL SLAVESZSETzSLOWLOG GETzSLOWLOG LENzSLOWLOG RESETZSSCANZTIMEZXCLAIMZ
XAUTOCLAIMzXGROUP CREATEzXGROUP DELCONSUMERzXGROUP DESTROYzXGROUP SETIDzXINFO CONSUMERSzXINFO GROUPSzXINFO STREAMZXPENDINGZZADDZZSCANZZMSCOREN)2r?   r@   rA   r*   r"  r   rS   r   r   r   r   rM   r   r   r   r
  r  r  r   r  r   r   r   r   rL   r   r   re   r$   rk   r  rN   r   r   r   r   rx   rz   r}   r  r   r   r   r   r   r   r   r   r   RESPONSE_CALLBACKSr"   r"   r"   r#   r    s(     r  c                &   @   s   e Zd ZdZedd Zd>ee dddZdd Z	dd Z
dd Zed dddZdddddZdd Zdd Zd?d!d"Zd#d$ Zd@d&d'Zd(d) Zd*d+ Zd,d- Zd.d/ Zd0d1 Zd2d3 Zd4d5 Zd6d7 Zd8d9 Zd:d; Zd<d= ZdS )ARedisa  
    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.
    c                 K   s   t j|f|}| |dS )a  
        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.

        )connection_pool)r   from_url)clsurlri   r*  r"   r"   r#   r+  \  s    *zRedis.from_url	localhost  r   Nutf-8strictFrequired)credential_providerc'           (      C   s  |	s|dk	rt td |}|dk	r8t td |}|s@g }|dkrR|t ||#||||||t|$||!|"|%|&d}'|
dk	r|'|
td n@|'|||||d |r|'t	||||||||||||d t
f |'}	|	| _d| _| r| jd	| _t| jj| _dS )
a  
        Initialize a new Redis client.
        To specify a retry policy for specific errors, first set
        `retry_on_error` to a list of the error/s to retry on, then set
        `retry` to a valid `Retry` object.
        To retry on TimeoutError, `retry_on_timeout` can also be set to `True`.

        Args:

        single_connection_client:
            if `True`, connection pool is not used. In that case `Redis`
            instance use is not thread safe.
        Nz/"charset" is deprecated. Use "encoding" insteadz5"errors" is deprecated. Use "encoding_errors" insteadT)r  usernamepasswordsocket_timeoutencodingencoding_errorsr   retry_on_errorretrymax_connectionshealth_check_intervalclient_nameredis_connect_funcr3  )pathconnection_class)hostrl   socket_connect_timeoutsocket_keepalivesocket_keepalive_options)r@  ssl_keyfilessl_certfilessl_cert_reqsssl_ca_certsssl_ca_datassl_check_hostnamessl_passwordssl_ca_pathssl_validate_ocsp_stapledssl_validate_ocspssl_ocsp_contextssl_ocsp_expected_cert_)warningswarnDeprecationWarningra   r   copydeepcopyr=   r
   r	   r   r*  
connectionget_connectionr+   r7   r(  response_callbacks)(r.   rA  rl   r  r5  r6  rB  rC  rD  r*  Zunix_socket_pathr7  r8  charseterrorsr   retry_on_timeoutr9  sslrE  rF  rG  rH  rL  rI  rJ  rK  rN  rM  rO  rP  r;  single_connection_clientr<  r=  r4  r:  r>  r3  ri   r"   r"   r#   r2     s    6


zRedis.__init__c                 C   s   t | j dt| j dS )N<>)r   r?   reprr*  r.   r"   r"   r#   __repr__  s    zRedis.__repr__c                 C   s
   | j  S )z!Get the connection pool's encoder)r*  get_encoderrb  r"   r"   r#   rd    s    zRedis.get_encoderc                 C   s   | j jS )z'Get the connection's key-word arguments)r*  Zconnection_kwargsrb  r"   r"   r#   get_connection_kwargs  s    zRedis.get_connection_kwargsr   )returnc                 C   s   |   dS Nr:  )re  r:   rb  r"   r"   r#   	get_retry  s    zRedis.get_retry)r:  rf  c                 C   s"   |   d|i | j| d S rg  )re  r=   r*  	set_retry)r.   r:  r"   r"   r#   ri    s    zRedis.set_retryc                 C   s   || j |< dS )zSet a custom Response CallbackN)rY  )r.   r   r)   r"   r"   r#   set_response_callback"  s    zRedis.set_response_callbackc                 C   s   t | || dS )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)r.   funcnamefuncr"   r"   r#   load_external_module&  s    zRedis.load_external_moduleTc                 C   s   t | j| j||S )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.
        )Pipeliner*  rY  )r.   transaction
shard_hintr"   r"   r#   pipeline=  s       zRedis.pipelinec           
   
   O   s   | dd}| dd}| dd}| d|t}z8|rB|j|  ||}| }	|rZ|n|	W W  5 Q R  S  tk
r   |dk	r|dkrt| Y q2Y q2X q2W 5 Q R X dS )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.
        rq  Nvalue_from_callableFwatch_delayTr   )poprr  watchexecuter   timesleep)
r.   rm  Zwatchesri   rq  rs  rt  pipeZ
func_valueZ
exec_valuer"   r"   r#   rp  I  s    

zRedis.transaction皙?c              	   C   s"   |dkrt }|| ||||||dS )aL  
        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.

        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.N)timeoutry  blockingblocking_timeoutthread_localr   )r.   rs   r|  ry  r}  r~  
lock_classr  r"   r"   r#   lock_  s    >z
Redis.lockc                 K   s   t | jf|S )z
        Return a Publish/Subscribe object. With this object, you can
        subscribe to channels and listen for messages that get published to
        them.
        )PubSubr*  )r.   ri   r"   r"   r#   pubsub  s    zRedis.pubsubc                 C   s
   t | jS r%   )Monitorr*  rb  r"   r"   r#   monitor  s    zRedis.monitorc                 C   s   | j | jddS )NT)r*  r^  )r7   r*  rb  r"   r"   r#   client  s     zRedis.clientc                 C   s   | S r%   r"   rb  r"   r"   r#   	__enter__  s    zRedis.__enter__c                 C   s   |    d S r%   closer.   exc_type	exc_value	tracebackr"   r"   r#   __exit__  s    zRedis.__exit__c                 C   s   |    d S r%   r  rb  r"   r"   r#   __del__  s    zRedis.__del__c                 C   s.   t | dsd S | j}|r*d | _| j| d S )NrW  )hasattrrW  r*  releaser.   connr"   r"   r#   r    s    
zRedis.closec                 O   s   |j |  | j||f|S )z7
        Send a command and parse the response
        )send_commandparse_response)r.   r  command_nameargsr   r"   r"   r#   _send_command_parse_response  s    
z"Redis._send_command_parse_responsec                 C   s.   |   |jdks&t|t|jdkr*|dS )z
        Close the connection and raise an exception
        if retry_on_error is not set or the error
        is not one of the specified error types
        NF)
disconnectr9  r   r   r.   r  errorr"   r"   r#   _disconnect_raise  s    zRedis._disconnect_raisec              	      sf   j } d jp |jfz,j fddfddW S js`| X dS )z.Execute a command and return a parsed responser   c                      s   j f S r%   r  r"   r  r  r  r   r.   r"   r#   r     s    z'Redis.execute_command.<locals>.<lambda>c                    s     | S r%   )r  r  r  r.   r"   r#   r     r   N)r*  rW  rX  r  r:  call_with_retry)r.   r  r   poolr"   r  r#   execute_command  s    zRedis.execute_commandc                 K   s   z,t |kr"|jdd}|t  n| }W n* tk
rV   t|krP|t  Y S  Y nX t|krj|t || jkr| j| |f|S |S )z'Parses a response from the Redis serverT)Zdisable_decoding)r   read_responseru  r   r   rY  )r.   rW  r  r   r!   r"   r"   r#   r    s    

zRedis.parse_response)&r.  r/  r   NNNNNNNr0  r1  NNFFNFNNr2  NNNFNFFNNNFr   NNNNN)TN)Nr{  TNNT)r?   r@   rA   rB   classmethodr+  r   r   r2   rc  rd  re  rh  ri  rj  rn  rr  rp  r  r  r  r  r  r  r  r  r  r  r  r  r"   r"   r"   r#   r)  M  s   
.                                      ' 
      
Jr)  c                   @   sL   e Zd ZdZedZedZdd Zdd Z	dd	 Z
d
d Zdd ZdS )r  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                 C   s   || _ | j d| _d S )NMONITOR)r*  rX  rW  )r.   r*  r"   r"   r#   r2     s    zMonitor.__init__c                 C   s0   | j d | j  }t|s,td| | S )Nr  zMONITOR failed: )rW  r  r  r   r   r.   r!   r"   r"   r#   r    s
    
zMonitor.__enter__c                 G   s   | j   | j| j  d S r%   )rW  r  r*  r  )r.   r  r"   r"   r#   r  "  s    
zMonitor.__exit__c                 C   s   | j  }t|tr&| j jj|dd}|dd\}}| j|}|	 \}}}d
| j|}|dd}|dkrd}d}	d}
n4|d	rd	}|d
d }	d	}
n|dd\}}	d}
t|t|||	|
|dS )z)Parse the response from a monitor commandTforcer   rR   z\""Zluar  unixr   NrE   Ztcp)rx  r  client_addressclient_portclient_typer   )rW  r  r   r   encoderdecoder(   
monitor_rer   r   r   
command_refindallreplacer^   rT   rS   r   )r.   r!   Zcommand_timeZcommand_datar!  Zdb_idr  r   r  r  r  r"   r"   r#   next_command&  s2    


zMonitor.next_commandc                 c   s   |   V  q dS )z)Listen for commands coming to the server.N)r  rb  r"   r"   r#   listenI  s    zMonitor.listenN)r?   r@   rA   rB   recompiler  r  r2   r  r  r  r  r"   r"   r"   r#   r    s   

#r  c                   @   s   e Zd ZdZdZdZdZd<ddZd	d
 Zdd Z	dd Z
dd Zdd Zdd Zedd Zdd Zdd Zdd Zdd Zd=d!d"Zd#d$ Zd%d& Zd'd( Zd)d* Zd+d, Zd-d. Zd/d0 Zd1d2 Zd>d4d5Zd?d6d7Zd@d8d9ZdAd:d;Z dS )Br  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)unsubscribepunsubscribezredis-py-health-checkNFc                 C   s|   || _ || _|| _d | _t | _|| _| jd kr>| j  | _| j	| j
| _| jjrdd| j
g| _nd| jg| _|   d S )Nr   s   pong)r*  rq  ignore_subscribe_messagesrW  	threadingEventsubscribed_eventr  rd  encodeHEALTH_CHECK_MESSAGEhealth_check_response_br   health_check_responsereset)r.   r*  rq  r  r  r"   r"   r#   r2   \  s    

zPubSub.__init__c                 C   s   | S r%   r"   rb  r"   r"   r#   r  t  s    zPubSub.__enter__c                 C   s   |    d S r%   r  r  r"   r"   r#   r  w  s    zPubSub.__exit__c                 C   s&   z|    W n tk
r    Y nX d S r%   r  r   rb  r"   r"   r#   r  z  s    zPubSub.__del__c                 C   s^   | j r.| j   | j   | j| j  d | _ i | _d| _t | _i | _	t | _
| j  d S )Nr   )rW  r  Zclear_connect_callbacksr*  r  r  health_check_response_counterrq   pending_unsubscribe_channelspatternspending_unsubscribe_patternsr  clearrb  r"   r"   r#   r    s    

zPubSub.resetc                 C   s   |    d S r%   r  rb  r"   r"   r#   r    s    zPubSub.closec                 C   s   | j   | j  | jrRi }| j D ]\}}||| jj|dd< q(| jf | | jri }| j D ]\}}||| jj|dd< qf| j	f | dS )zBRe-subscribe to any channels and patterns previously subscribed toTr  N)
r  r  r  r  r,   r  r  	subscriber  
psubscribe)r.   rW  r  r0   r1   r  r"   r"   r#   
on_connect  s    

zPubSub.on_connectc                 C   s
   | j  S )z@Indicates if there are subscriptions to any channels or patterns)r  is_setrb  r"   r"   r#   
subscribed  s    zPubSub.subscribedc                 G   sd   | j dkr*| jd| j| _ | j | j | j }d| j i}| jsJ|   | j||j	f|| dS )z#Execute a publish/subscribe commandNr  check_health)
rW  r*  rX  rq  Zregister_connect_callbackr  r  clean_health_check_responses_executer  )r.   r  rW  ri   r"   r"   r#   r    s    
 zPubSub.execute_commandc                 C   st   d}| j }| jdkrp|dkrp| j||j|jdrf| ||j}| |rX|  jd8  _ntd||d8 }q
dS )zG
        If any health check responses are present, clean them
        
   r   r|  rR   z?A non health check response was cleaned by execute_command: {0}N)	rW  r  r  can_readr6  r  is_health_check_responser   format)r.   Zttlr  r!   r"   r"   r#   r    s    
z#PubSub.clean_health_check_responsesc                 C   s(   |   |jrt|ts||  dS )z
        Close the connection and raise an exception
        if retry_on_timeout is not set or the error
        is not a TimeoutError. Otherwise, try to reconnect
        N)r  r\  r   r   connectr  r"   r"   r#   _disconnect_raise_connect  s    z PubSub._disconnect_raise_connectc                    s$   j  fddfddS )aU  
        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                      s
    S r%   r"   r"   )r  r   ri   r"   r#   r     r   z!PubSub._execute.<locals>.<lambda>c                    s     | S r%   )r  r  r  r"   r#   r     r   )r:  r  )r.   r  r   r  ri   r"   )r  r   r  ri   r.   r#   r    s    zPubSub._executeTr   c                    sZ   | j dkrtd|    fdd}| |}| |rV|  jd8  _dS |S )z3Parse the response from a publish/subscribe commandNNpubsub connection not set: did you forget to call subscribe() or psubscribe()?c                      s&    sj dsd S n   S )Nr  )r  r  r  r"   blockr  r|  r"   r#   try_read  s
    z'PubSub.parse_response.<locals>.try_readrR   )rW  RuntimeErrorr  r  r  r  )r.   r  r|  r  r!   r"   r  r#   r    s    
zPubSub.parse_responsec                 C   s   || j | jfkS )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  r"   r"   r#   r    s    zPubSub.is_health_check_responsec                 C   sN   | j }|d krtd|jrJt |jkrJ|jd| jdd |  jd7  _d S )Nr  r$  F)r  rR   )rW  r  r<  rx  Znext_health_checkr  r  r  r  r"   r"   r#   r    s    zPubSub.check_healthc                    s(   | j j| j j  fdd| D S )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.
        c                    s   i | ]\}} ||qS r"   r"   )rG   r0   r1   r  r  r"   r#   r   "  s     
 z*PubSub._normalize_keys.<locals>.<dictcomp>)r  r  r  r,   r>   r"   r  r#   _normalize_keys  s    zPubSub._normalize_keysc                 O   s|   |rt |d |dd }t|}|| | jd|  }| |}| j| | jsl| j	
  d| _| j| |S )aE  
        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   rR   N
PSUBSCRIBE)r  )r   r&   r'   r=   r  r   r  r  r  r  rq   r  r  difference_update)r.   r  ri   Znew_patternsret_valr"   r"   r#   r  $  s    



zPubSub.psubscribec                 G   sL   |r,t |d |dd }| t|}n| j}| j| | jd| S )zj
        Unsubscribe from the supplied patterns. If empty, unsubscribe from
        all patterns.
        r   rR   NPUNSUBSCRIBE)r  )r   r  r&   r'   r  r  r=   r  )r.   r  r  r"   r"   r#   r  >  s    zPubSub.punsubscribec                 O   s|   |rt |d |dd }t|}|| | jd|  }| |}| j| | jsl| j	
  d| _| j| |S )aR  
        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   rR   N	SUBSCRIBE)r  )r   r&   r'   r=   r  r   r  r  r  r  rq   r  r  r  )r.   r  ri   Znew_channelsr  r"   r"   r#   r  K  s    



zPubSub.subscribec                 G   sL   |r,t |d |dd }| t|}n| j}| j| | jd| S )zi
        Unsubscribe from the supplied channels. If empty, unsubscribe from
        all channels
        r   rR   NUNSUBSCRIBE)r  )r   r  r&   r'   r  r  r=   r  )r.   r  r  r"   r"   r#   r  e  s    zPubSub.unsubscribec                 c   s,   | j r(| | jdd}|dk	r |V  q dS )zBListen for messages on channels this client has been subscribed toT)r  N)r  handle_messager  r  r"   r"   r#   r  r  s    zPubSub.listen        c                 C   sd   | j s>t }| j|dkr:t | }td|| }ndS | j|dk|d}|r`| ||S dS )a  
        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.
        Tr  N)r  r|  )r  rx  r  waitr   r  r  )r.   r  r|  r   Z
time_spentr!   r"   r"   r#   get_messagey  s    zPubSub.get_messagec                 C   s   |dkrdn|}|  d|S )z'
        Ping the Redis server
        Nr  r$  r  )r.   r  r"   r"   r#   r     s    zPubSub.pingc                 C   s`  |dkrdS t |d }|dkr<||d |d |d d}n2|dkrX|dd|d d}n|d|d |d d}|| jkr|d	kr|d }|| jkr| j| | j|d n,|d }|| jkr| j| | j|d | js| js| j	  || j
kr@|dkr| j|d
 d}n| j|d d}|r\|| dS n|dkr\|sX| jr\dS |S )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.
        Nr   r  rR   r   r   )r   patternchannelr/   r   r  r  r  )r   UNSUBSCRIBE_MESSAGE_TYPESr  remover  ru  r  r  r  r  PUBLISH_MESSAGE_TYPESr:   r  )r.   r!   r  Zmessage_typer  r  r  handlerr"   r"   r#   r    sV    





zPubSub.handle_messagec                 C   st   | j  D ] \}}|d kr
td| dq
| j D ] \}}|d kr6td| dq6t| |||d}|  |S )Nz
Channel: 'z' has no handler registeredz
Pattern: ')daemonexception_handler)r  r,   r   r  PubSubWorkerThreadstart)r.   
sleep_timer  r  r  r  r  threadr"   r"   r#   run_in_thread  s       zPubSub.run_in_thread)NFN)Tr   )Fr  )N)F)r   FN)!r?   r@   rA   rB   r  r  r  r2   r  r  r  r  r  r  propertyr  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r"   r"   r"   r#   r  O  sB      
	





Ar  c                       s.   e Zd Zd	 fdd	Zdd Zdd Z  ZS )
r  FNc                    s0   t    || _|| _|| _|| _t | _d S r%   )	r3   r2   r  r  r  r  r  r  _running)r.   r  r  r  r  r6   r"   r#   r2     s    
zPubSubWorkerThread.__init__c              
   C   s   | j  rd S | j   | j}| j}| j  rz|jd|d W q$ tk
r| } z| jd kr^ | |||  W 5 d }~X Y q$X q$|  d S )NT)r  r|  )	r  r  rq   r  r  r  BaseExceptionr  r  )r.   r  r  er"   r"   r#   run  s    



"zPubSubWorkerThread.runc                 C   s   | j   d S r%   )r  r  rb  r"   r"   r#   stop  s    zPubSubWorkerThread.stop)FN)r?   r@   rA   r2   r  r   rC   r"   r"   r6   r#   r    s   r  c                   @   s   e Zd ZdZdddhZdd Zdd Zd	d
 Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd  Zd!d" Zd#d$ Zd%d& Zd'd( Zd)d* Zd5d,d-Zd.d/ Zd0d1 Zd2d3 Zd4S )6ro  a_  
    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 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.
    DISCARDEXECUNWATCHc                 C   s0   || _ d | _|| _|| _|| _d| _|   d S )NF)r*  rW  rY  rp  rq  watchingr  )r.   r*  rY  rp  rq  r"   r"   r#   r2     s    zPipeline.__init__c                 C   s   | S r%   r"   rb  r"   r"   r#   r  )  s    zPipeline.__enter__c                 C   s   |    d S r%   r  r  r"   r"   r#   r  ,  s    zPipeline.__exit__c                 C   s&   z|    W n tk
r    Y nX d S r%   r  rb  r"   r"   r#   r  /  s    zPipeline.__del__c                 C   s
   t | jS r%   )r   command_stackrb  r"   r"   r#   __len__5  s    zPipeline.__len__c                 C   s   dS )z1Pipeline instances should always evaluate to TrueTr"   rb  r"   r"   r#   __bool__8  s    zPipeline.__bool__c                 C   s~   g | _ t | _| jrT| jrTz| jd | j  W n tk
rR   | j  Y nX d| _d| _	| jrz| j
| j d | _d S )Nr  F)r  rq   scriptsr  rW  r  r  r   r  explicit_transactionr*  r  rb  r"   r"   r#   r  <  s    zPipeline.resetc                 C   s&   | j rtd| jrtdd| _ dS )z
        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)r	  r   r  rb  r"   r"   r#   r  S  s    zPipeline.multic                 O   s0   | j s|d dkr$| js$| j||S | j||S )Nr   WATCH)r  r	  immediate_execute_commandpipeline_execute_command)r.   r  ri   r"   r"   r#   r  `  s    zPipeline.execute_commandc                 C   s<   |   | jr|   td|jr.t|ts8|    dS )z
        Close the connection, reset watching state and
        raise an exception if we were watching,
        retry_on_timeout is not set,
        or the error is not a TimeoutError
        =A ConnectionError occurred on while watching one or more keysN)r  r  r  r   r\  r   r   r  r"   r"   r#   _disconnect_reset_raisee  s    z Pipeline._disconnect_reset_raisec                    sP    d j s(jj_ j fddfddS )z
        Execute a command immediately, but don't auto-retry on a
        ConnectionError if we're already WATCHing a variable. Used when
        issuing WATCH or subsequent commands retrieving their values but before
        MULTI is called.
        r   c                      s   j f S r%   r  r"   r  r"   r#   r     s    z4Pipeline.immediate_execute_command.<locals>.<lambda>c                    s     | S r%   )r  r  r  r"   r#   r     r   )rW  r*  rX  rq  r:  r  r.   r  r   r"   r  r#   r  {  s    z"Pipeline.immediate_execute_commandc                 O   s   | j ||f | S )ar  
        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.
        )r  ra   r  r"   r"   r#   r    s    z!Pipeline.pipeline_execute_commandc                 C   s  t di fg|di fg}|dd |D }|| g }z| |d W n0 tk
rz } z|d|f W 5 d }~X Y nX t|D ]\}}	t|	d kr|||	d t f qz| |d W q tk
r } z(| ||d |	d  |||f W 5 d }~X Y qX qz| |d}
W n* t	k
rF   |r@|d d  Y nX d| _
|
d kr`td	|D ]\}}|
|| qdt|
t|kr| j  td
|r| ||
 g }t|
|D ]N\}}t|ts|\}}|d }|| jkr| j| |f|}|| q|S )N)MULTI)r  c                 S   s   g | ]\}}t |kr|qS r"   )r   )rG   r  r   r"   r"   r#   r|     s      z1Pipeline._execute_transaction.<locals>.<listcomp>rQ  r   rR   FzWatched variable changed.z6Wrong number of response items from pipeline execution)r   pack_commandssend_packed_commandr  r   ra   	enumerater   annotate_exceptionr   r  r   insertr   rW  r  raise_first_errorr   r   r   rY  )r.   rW  r   raise_on_errorZcmdsall_cmdsr[  r  r   r   r!   r/   r   cmdr  r   r  r"   r"   r#   _execute_transaction  sZ    
 "

zPipeline._execute_transactionc           	      C   s   | dd |D }|| g }|D ]T\}}z|| j||d f| W q& tk
rx } z|| W 5 d }~X Y q&X q&|r| || |S )Nc                 S   s   g | ]\}}|qS r"   r"   )rG   r  rQ  r"   r"   r#   r|     s     z.Pipeline._execute_pipeline.<locals>.<listcomp>r   )r  r  ra   r  r   r  )	r.   rW  r   r  r  r!   r  r   r  r"   r"   r#   _execute_pipeline  s    
zPipeline._execute_pipelinec                 C   s>   t |D ]0\}}t|tr| ||d || d  |qd S )NrR   r   )r  r   r   r  )r.   r   r!   r   r   r"   r"   r#   r    s    
zPipeline.raise_first_errorc                 C   sF   d tt|}d| d| d|jd  }|f|jdd   |_d S )Nr   z
Command # z (z) of pipeline caused error: r   rR   )r   rw   r   r  )r.   	exceptionnumberr   r  msgr"   r"   r#   r    s    zPipeline.annotate_exceptionc                 K   s6   t j| ||f|}|| jkr$d| _n|dkr2d| _|S )NFr
  T)r)  r  UNWATCH_COMMANDSr  )r.   rW  r  r   rr   r"   r"   r#   r     s    
zPipeline.parse_responsec                 C   s\   t | j}| j}dd |D }|d| }t|sXt||D ]\}}|s<|d|j|_q<d S )Nc                 S   s   g | ]
}|j qS r"   )sha)rG   sr"   r"   r#   r|     s     z)Pipeline.load_scripts.<locals>.<listcomp>r&  r'  )r&  )r   r  r  allr   scriptr   )r.   r  Z	immediateZshasexistsr!  existr"   r"   r#   load_scripts  s    
zPipeline.load_scriptsc                 C   s4   |   | jrtd|jr&t|ts0|    dS )z
        Close the connection, raise an exception if we were watching,
        and raise an exception if retry_on_timeout is not set,
        or the error is not a TimeoutError
        r  N)r  r  r   r\  r   r   r  r  r"   r"   r#   _disconnect_raise_reset  s    z Pipeline._disconnect_raise_resetTc                    s   j sjsg S jr"  js.jr6jnjj  s\j	
dj  _z* j fdd fddW S   X dS )z0Execute all the commands in the current pipeliner  c                      s    S r%   r"   r"   )r  rw  r  stackr"   r#   r   >  r   z"Pipeline.execute.<locals>.<lambda>c                    s     | S r%   )r'  r  r  r"   r#   r   ?  r   N)r  r  r  r&  rp  r	  r  r  rW  r*  rX  rq  r  r:  r  )r.   r  r"   )r  rw  r  r.   r(  r#   rw  )  s$    
zPipeline.executec                 C   s   |  d dS )zg
        Flushes all previously queued commands
        See: https://redis.io/commands/DISCARD
        r  Nr  rb  r"   r"   r#   discardD  s    zPipeline.discardc                 G   s   | j rtd| jd| S )z$Watches the values at keys ``names``z"Cannot issue a WATCH after a MULTIr
  )r
  )r	  r   r  )r.   namesr"   r"   r#   rv  K  s    zPipeline.watchc                 C   s   | j r| dpdS )z'Unwatches all previously specified keysr  T)r  r  rb  r"   r"   r#   unwatchQ  s    zPipeline.unwatchN)T)r?   r@   rA   rB   r  r2   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r&  r'  rw  r)  rv  r+  r"   r"   r"   r#   ro  
  s2   

C
ro  )FF)erU  r   r  r  rx  rR  	itertoolsr   typingr   Zredis.commandsr   r   r   r   Zredis.connectionr   r	   r
   Zredis.credentialsr   Zredis.exceptionsr   r   r   r   r   r   r   r   Z
redis.lockr   Zredis.retryr   Zredis.utilsr   r   Z	SYM_EMPTYr   r   r$   r*   r&   r+   rL   rN   re   rk   r   rp   ru   rx   rz   r}   r   rh   ro   r   r   rM   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   r   r   r  r
  r  r  r  r  r  r)  ZStrictRedisr  r  Threadr  ro  r"   r"   r"   r#   <module>   s   (
,

!%  !   ?C   