'ޜfdZddlZddlZddlZddlZddlmZ ddl Z ddl Z ddl Z ddl mZmZmZmZmZddlmZmZGddZeje_dS)z2Fanout cache automatically shards keys and values.N)DEFAULT_SETTINGSENOVALCacheDiskTimeout)DequeIndexcdeZdZdZdddefdZedZdZe j d2d Z d3d Z d Z d4d Zd3dZd5dZd5dZ d6dZdZdZdZ d7dZd8dZdZd9dZd8dZdZdZd8dZd8dZd8d Zd:d"Z d;d#Z!d$Z"d%Z#d&Z$d'Z%d(Z&d)Z'd*Z(d+Z)d,Z*e+fd-Z,d FanoutCachez"Cache that shards keys and values.Ng{Gz?c tjdttjtjt d}d||z ||_|_ |_ tfdt|D|_ |j djj|_i|_i|_i|_dS)a6Initialize cache instance. :param str directory: cache directory :param int shards: number of shards to distribute writes :param float timeout: SQLite connection timeout :param disk: `Disk` instance for serialization :param settings: any of `DEFAULT_SETTINGS` Nz diskcache-)prefix size_limitc 3fK|]+}tdtjd|zdV,dS)z%03d) directorytimeoutdiskrN)ropjoin).0numrrsettingsrrs p/builddir/build/BUILD/imunify360-venv-2.6.2/opt/imunify360/venv/lib/python3.11/site-packages/diskcache/fanout.py z'FanoutCache.__init__..+ss     ')Vc\::%              r)tempfilemkdtempstrr expanduser expandvarsrpop_count _directory_disktuplerange_shardsrhash_hash_caches_deques_indexes)selfrshardsrrrdefault_size_limitrs ` ``` @r__init__zFanoutCache.__init__s   ( ===I NN M),, M),, -l;\\,0BCCfL  #          V}}       \!_).    rc|jS)zCache directory.)r%r/s rrzFanoutCache.directory:s rcddh}|tvp||v}|sJd|t|jd|S)Nrrzcannot access {} in cache shardr)rformatgetattrr))r/name safe_names valid_names r __getattr__zFanoutCache.__getattr__?sY( --C1C II<CCDIIIIzt|A---rTc#K|s Jdtj5}|jD]-}|d}||.dVddddS#1swxYwYdS)aContext manager to perform a transaction by locking the cache. While the cache is locked, no other write operation is permitted. Transactions should therefore be as short as possible. Read and write operations performed in a transaction are atomic. Read operations may occur concurrent to a transaction. Transactions may be nested and may not be shared between threads. Blocks until transactions are held on all cache shards by retrying as necessary. >>> cache = FanoutCache() >>> with cache.transact(): # Atomically increment two keys. ... _ = cache.incr('total', 123.4) ... _ = cache.incr('count', 1) >>> with cache.transact(): # Atomically calculate average. ... average = cache['total'] / cache['count'] >>> average 123.4 :return: context manager for use in `with` statement z!retry must be True in FanoutCacheTretryN)cl ExitStackr)transact enter_context)r/r>stackshardshard_transactions rrAzFanoutCache.transactEs499999u \^^ u 7 7$)NNN$>$>!##$56666 EEE                   s:A))A-0A-Fc|||jz}|j|} |||||||S#t$rYdSwxYw)aSet `key` and `value` item in cache. When `read` is `True`, `value` should be a file-like object opened for reading in binary mode. If database timeout occurs then fails silently unless `retry` is set to `True` (default `False`). :param key: key for item :param value: value for item :param float expire: seconds until the key expires (default None, no expiry) :param bool read: read value as raw bytes from file (default False) :param str tag: text to associate with key (default None) :param bool retry: retry if database timeout occurs (default False) :return: True if item was set F)r+r$r)setr r/keyvalueexpirereadtagr>indexrDs rrGzFanoutCache.setfsi& 3$+- U# 99S%sEBB B   55 A AAcd|||jz}|j|}|||<dS)zSet `key` and `value` item in cache. Calls :func:`FanoutCache.set` internally with `retry` set to `True`. :param key: key for item :param value: value for item Nr+r$r))r/rIrJrNrDs r __setitem__zFanoutCache.__setitem__s3 3$+- U#c rc|||jz}|j|} ||||S#t$rYdSwxYw)aTouch `key` in cache and update `expire` time. If database timeout occurs then fails silently unless `retry` is set to `True` (default `False`). :param key: key for item :param float expire: seconds until the key expires (default None, no expiry) :param bool retry: retry if database timeout occurs (default False) :return: True if key was touched F)r+r$r)touchr)r/rIrKr>rNrDs rrTzFanoutCache.touchsc 3$+- U# ;;sFE22 2   55 sA AAc|||jz}|j|} |||||||S#t$rYdSwxYw)aAdd `key` and `value` item to cache. Similar to `set`, but only add to cache if key not present. This operation is atomic. Only one concurrent add operation for given key from separate threads or processes will succeed. When `read` is `True`, `value` should be a file-like object opened for reading in binary mode. If database timeout occurs then fails silently unless `retry` is set to `True` (default `False`). :param key: key for item :param value: value for item :param float expire: seconds until the key expires (default None, no expiry) :param bool read: read value as bytes from file (default False) :param str tag: text to associate with key (default None) :param bool retry: retry if database timeout occurs (default False) :return: True if item was added F)r+r$r)addrrHs rrVzFanoutCache.addsi0 3$+- U# 99S%sEBB B   55 rOrrc|||jz}|j|} |||||S#t$rYdSwxYw)aIncrement value by delta for item with key. If key is missing and default is None then raise KeyError. Else if key is missing and default is not None then use default for value. Operation is atomic. All concurrent increment operations will be counted individually. Assumes value may be stored in a SQLite column. Most builds that target machines with 64-bit pointer widths will support 64-bit signed integers. If database timeout occurs then fails silently unless `retry` is set to `True` (default `False`). :param key: key for item :param int delta: amount to increment (default 1) :param int default: value if key is missing (default 0) :param bool retry: retry if database timeout occurs (default False) :return: new value for item on success else None :raises KeyError: if key is not found and default is None N)r+r$r)incrrr/rIdeltadefaultr>rNrDs rrXzFanoutCache.incrse0 3$+- U# ::c5'599 9   44 A AAc|||jz}|j|} |||||S#t$rYdSwxYw)aDecrement value by delta for item with key. If key is missing and default is None then raise KeyError. Else if key is missing and default is not None then use default for value. Operation is atomic. All concurrent decrement operations will be counted individually. Unlike Memcached, negative values are supported. Value may be decremented below zero. Assumes value may be stored in a SQLite column. Most builds that target machines with 64-bit pointer widths will support 64-bit signed integers. If database timeout occurs then fails silently unless `retry` is set to `True` (default `False`). :param key: key for item :param int delta: amount to decrement (default 1) :param int default: value if key is missing (default 0) :param bool retry: retry if database timeout occurs (default False) :return: new value for item on success else None :raises KeyError: if key is not found and default is None N)r+r$r)decrrrYs rr^zFanoutCache.decrse6 3$+- U# ::c5'599 9   44 r\c|||jz}|j|} |||||||S#tt jf$r|cYSwxYw)aRetrieve value from cache. If `key` is missing, return `default`. If database timeout occurs then returns `default` unless `retry` is set to `True` (default `False`). :param key: key for item :param default: return value if key is missing (default None) :param bool read: if True, return file handle to value (default False) :param float expire_time: if True, return expire_time in tuple (default False) :param tag: if True, return tag in tuple (default False) :param bool retry: retry if database timeout occurs (default False) :return: value for item if key is found else default )r+r$r)getrsqlite3OperationalError) r/rIr[rL expire_timerMr>rNrDs rr`zFanoutCache.getss2 3$+- U# 99S'4c5II I12   NNN sAA! A!cf|||jz}|j|}||S)zReturn corresponding value for `key` from cache. Calls :func:`FanoutCache.get` internally with `retry` set to `True`. :param key: key for item :return: value for item :raises KeyError: if key is not found rQr/rIrNrDs r __getitem__zFanoutCache.__getitem__!s0 3$+- U#Szrcr||tdd}|turt||S)zReturn file handle corresponding to `key` from cache. :param key: key for item :return: file open for reading in binary mode :raises KeyError: if key is not found T)r[rLr>)r`rKeyError)r/rIhandles rrLzFanoutCache.read/s9#vDEE V  3--  rc^|||jz}|j|}||vS)zReturn `True` if `key` matching item is found in cache. :param key: key for item :return: True if key is found rQres r __contains__zFanoutCache.__contains__<s0 3$+- U#e|rc|||jz}|j|} ||||||S#t$r|cYSwxYw)aRemove corresponding item for `key` from cache and return value. If `key` is missing, return `default`. Operation is atomic. Concurrent operations will be serialized. If database timeout occurs then fails silently unless `retry` is set to `True` (default `False`). :param key: key for item :param default: return value if key is missing (default None) :param float expire_time: if True, return expire_time in tuple (default False) :param tag: if True, return tag in tuple (default False) :param bool retry: retry if database timeout occurs (default False) :return: value for item if key is found else default )r+r$r)r#r)r/rIr[rcrMr>rNrDs rr#zFanoutCache.popGsi* 3$+- U# 99S';UCC C   NNN sA AAc|||jz}|j|} |||S#t$rYdSwxYw)agDelete corresponding item for `key` from cache. Missing keys are ignored. If database timeout occurs then fails silently unless `retry` is set to `True` (default `False`). :param key: key for item :param bool retry: retry if database timeout occurs (default False) :return: True if item was deleted F)r+r$r)deleter)r/rIr>rNrDs rrnzFanoutCache.deletecsa 3$+- U# <<U++ +   55 sA AAc`|||jz}|j|}||=dS)zDelete corresponding item for `key` from cache. Calls :func:`FanoutCache.delete` internally with `retry` set to `True`. :param key: key for item :raises KeyError: if key is not found NrQres r __delitem__zFanoutCache.__delitem__ws1 3$+- U# #JJJrcnfd|jD}tjtj|gS)a3Check database and file system consistency. Intended for use in testing and post-mortem error analysis. While checking the cache table for consistency, a writer lock is held on the database. The lock blocks other cache clients from writing to the database. For caches with many file references, the lock may be held for a long time. For example, local benchmarking shows that a cache with 1,000 file references takes ~60ms to check. If database timeout occurs then fails silently unless `retry` is set to `True` (default `False`). :param bool fix: correct inconsistencies :param bool retry: retry if database timeout occurs (default False) :return: list of warnings :raises Timeout: if database timeout occurs c3DK|]}|VdSN)check)rrDfixr>s rrz$FanoutCache.check..s1FFEKKU++FFFFFFr)r) functoolsreduceoperatoriadd)r/rur>warningss `` rrtzFanoutCache.checks<(GFFFFFFF x<<)_removetimer/r>s rrKzFanoutCache.expires$||HDIKK>|GGGrcB|jD]}|dS)zCreate tag index on cache database. Better to initialize cache with `tag_index=True` than use this. :raises Timeout: if database timeout occurs N)r)create_tag_indexr/rDs rrzFanoutCache.create_tag_indexs4\ % %E  " " $ $ $ $ % %rcB|jD]}|dS)z`Drop tag index on cache database. :raises Timeout: if database timeout occurs N)r)drop_tag_indexrs rrzFanoutCache.drop_tag_indexs4 \ # #E  " " " " # #rc4|d|f|S)aLRemove items with matching `tag` from cache. If database timeout occurs then fails silently unless `retry` is set to `True` (default `False`). :param str tag: tag identifying items :param bool retry: retry if database timeout occurs (default False) :return: count of items removed evictr|r~)r/rMr>s rrzFanoutCache.evicts||G3&|>>>rc0|d|S)a-Cull items from cache until volume is less than size limit. If database timeout occurs then fails silently unless `retry` is set to `True` (default `False`). :param bool retry: retry if database timeout occurs (default False) :return: count of items removed cullr=rrs rrzFanoutCache.culls||F%|000rc0|d|S)aRemove all items from cache. If database timeout occurs then fails silently unless `retry` is set to `True` (default `False`). :param bool retry: retry if database timeout occurs (default False) :return: count of items removed clearr=rrs rrzFanoutCache.clears||G5|111rrcd}|jD]J}t||} ||d|i}||z }n(#t$r}||jdz }Yd}~nd}~wwxYw7K|S)NrTr>)r)r7rr}) r/r8r}r>totalrDmethodcountrs rr~zFanoutCache._removes\  EUD))F "FD666EUNE---W\!_,EEEEEE-   s , AA  Acfd|jD}td|D}td|D}||fS)zReturn cache statistics hits and misses. :param bool enable: enable collecting statistics (default True) :param bool reset: reset hits and misses to 0 (default False) :return: (hits, misses) c<g|]}|Sr)stats)rrDenableresets r z%FanoutCache.stats..s'HHH%5;;vu--HHHrc3 K|] \}}|V dSrsr)rhits_s rrz$FanoutCache.stats..s&55'$555555rc3 K|] \}}|V dSrsr)rrmissess rrz$FanoutCache.stats..s&;;ia6;;;;;;r)r)sum)r/rrresults total_hits total_missess `` rrzFanoutCache.statsshIHHHH4<HHH55W55555 ;;7;;;;; <''rc>td|jDS)zWReturn estimated total size of cache on disk. :return: size in bytes c3>K|]}|VdSrs)volumerrDs rrz%FanoutCache.volume..s*<><<<<<.s(;;UT%[[;;;;;;r)r)itchain from_iterabler/ iteratorss r__iter__zFanoutCache.__iter__s-;;dl;;; x%%i000rc|dt|jD}tj|S)z6Reverse iterate keys in cache including expired items.c34K|]}t|VdSrs)reversedrs rrz+FanoutCache.__reversed__..s(IIXe__IIIIIIr)rr)rrrrs r __reversed__zFanoutCache.__reversed__s5II(4<2H2HIII x%%i000rc>td|jDS)z0Count of items in cache including expired items.c34K|]}t|VdSrs)lenrs rrz&FanoutCache.__len__..#s(88%3u::888888rrr4s r__len__zFanoutCache.__len__!s!884<888888rcn|jD],} |||}n#t$rYnwxYw)-|S)aTReset `key` and `value` item from Settings table. If `value` is not given, it is reloaded from the Settings table. Otherwise, the Settings table is updated. Settings attributes on cache objects are lazy-loaded and read-only. Use `reset` to update the value. Settings with the ``sqlite_`` prefix correspond to SQLite pragmas. Updating the value will execute the corresponding PRAGMA statement. :param str key: Settings key for item :param value: value for item (optional) :return: updated value for item )r)rr)r/rIrJrDresults rrzFanoutCache.reset%sh$\  E "[[e44FD   s # 00<c |j} ||S#t$rU|d}tj|jdg|R}t d||||jntd|}|||<|cYSwxYw)a{Return Cache with given `name` in subdirectory. If disk is none (default), uses the fanout cache disk. >>> fanout_cache = FanoutCache() >>> cache = fanout_cache.cache('test') >>> cache.set('abc', 123) True >>> cache.get('abc') 123 >>> len(cache) 1 >>> cache.delete('abc') True :param str name: subdirectory name for Cache :param float timeout: SQLite connection timeout :param disk: Disk type or subclass for serialization :param settings: any of DEFAULT_SETTINGS :return: Cache with given name /cacheN)rrrr) r,rhsplitrrr%rr&r) r/r8rrrr,partsrtemps rrzFanoutCache.cacheAs., 4=    JJsOOEA5AAAI##'>> cache = FanoutCache() >>> deque = cache.deque('test') >>> deque.extend('abc') >>> deque.popleft() 'a' >>> deque.pop() 'c' >>> len(deque) 1 :param str name: subdirectory name for Deque :param maxlen: max length (default None, no max) :return: Deque with given name rdequenonerreviction_policy)maxlen) r-rhrrrr%rr&r fromcache)r/r8rr-rrrrs rrzFanoutCache.dequehs$, 4=    JJsOOEA5AAAI#Z &E OE&999E!GDMLLL sA+A?>A?c|j} ||S#t$rb|d}tj|jdg|R}t ||jd}tj |}|||<|cYSwxYw)aReturn Index with given `name` in subdirectory. >>> cache = FanoutCache() >>> index = cache.index('test') >>> index['abc'] = 123 >>> index['def'] = 456 >>> index['ghi'] = 789 >>> index.popitem() ('ghi', 789) >>> del index['abc'] >>> len(index) 1 >>> index['def'] 456 :param str name: subdirectory name for Index :return: Index with given name rrNrr) r.rhrrrr%rr&r r)r/r8r.rrrrNs rrNzFanoutCache.indexs(= D> !   JJsOOEA5AAAI#Z &E OE**E"HTNLLL sA)A=<A=)T)NFNF)NF)rrF)NFFFF)NFFF)F)FF)rF)TF)rNrs)0__name__ __module__ __qualname____doc__rr2propertyrr;r?contextmanagerrArGrRrTrVrXr^r`rfrLrkr#rnrprtrKrrrrrr~rrrrrrrrrrrrrrrNrrrr r s,,QD%%%%NX... @4   (>>    J  @         FK8(   ====. H H H H % % %### ? ? ? ? 1 1 1 1 2 2 2 2     ( ( ( (===MMM111 111 999 &8%%%%N    D"""""rr )r contextlibr?rv itertoolsrrxos.pathpathrrarrcorerrrrr persistentr r r memoizerrrrs88 @@@@@@@@@@@@@@$$$$$$$$\ \ \ \ \ \ \ \ ~m r