
    sgX                         d 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
Z
ddlZddlZddlmZmZmZmZmZ ddlmZmZ  G d d      Zej.                  e_        y)z2Fanout cache automatically shards keys and values.    N   )DEFAULT_SETTINGSENOVALCacheDiskTimeout)DequeIndexc                   `   e Zd ZdZdddefdZed        Zd Ze	j                  d,d       Zd-d	Zd
 Zd.dZd-dZd/dZd/dZ	 	 	 	 	 d0dZd Zd Zd Z	 d1dZd2dZd Zd3dZd2dZd Zd Zd2dZd2dZd2dZd4dZ d5dZ!d Z"d  Z#d! Z$d" Z%d# Z&d$ Z'd% Z(d& Z)d' Z*e+fd(Z,d6d)Z-d7d*Z.d+ Z/y)8FanoutCachez"Cache that shards keys and values.N   g{Gz?c                    t        j                  d      t              t        j                        t        j
                        t        d   }j                  d|      |z  || _        | _	        | _
        t        fdt        |      D              | _        | j                  d   j                  j                  | _        i | _        i | _        i | _        y)a6  Initialize 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           	   3   l   K   | ]+  }t        dt        j                  d |z        d - yw)z%03d)	directorytimeoutdiskr   N )r   opjoin).0numr   r   settingsr   r   s     C/var/www/html/venv/lib/python3.12/site-packages/diskcache/fanout.py	<genexpr>z'FanoutCache.__init__.<locals>.<genexpr>+   sJ      	
   '')Vc\:%	
 	
s   14r   )tempfilemkdtempstrr   
expanduser
expandvarsr   pop_count
_directory_disktuplerange_shardsr   hash_hash_caches_deques_indexes)selfr   shardsr   r   r   default_size_limitr   s    ` ``` @r   __init__zFanoutCache.__init__   s      ((=I	N	MM),	MM),	-l;\\,0BCfL
#
 	
 V}	
 	
 \\!_))..
    c                     | j                   S )zCache directory.)r$   r.   s    r   r   zFanoutCache.directory:   s     r2   c                     ddh}|t         v xs ||v }|sJ dj                  |             t        | j                  d   |      S )Nr   r   zcannot access {} in cache shardr   )r   formatgetattrr(   )r.   name
safe_names
valid_names       r   __getattr__zFanoutCache.__getattr__?   sO    (
--C1C
I<CCDIIzt||A--r2   c              #      K   |sJ d       t        j                         5 }| j                  D ]%  }|j                  d      }|j	                  |       ' d ddd       y# 1 sw Y   yxY ww)a  Context 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 FanoutCacheTretryN)cl	ExitStackr(   transactenter_context)r.   r>   stackshardshard_transactions        r   rA   zFanoutCache.transactE   sm     4 999u\\^ 	u 7$)NNN$>!##$567 		 	 	s   A.9A"	A."A+'A.c                     | j                  |      | j                  z  }| j                  |   }	 |j                  ||||||      S # t        $ r Y yw xY w)a  Set `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.   keyvalueexpirereadtagr>   indexrD   s	            r   rG   zFanoutCache.setf   sX    & 

3$++-U#	99S%sEBB 		   A 	AAc                 h    | j                  |      | j                  z  }| j                  |   }|||<   y)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

        Nr*   r#   r(   )r.   rI   rJ   rN   rD   s        r   __setitem__zFanoutCache.__setitem__   s1     

3$++-U#c
r2   c                     | j                  |      | j                  z  }| j                  |   }	 |j                  |||      S # t        $ r Y yw xY w)a  Touch `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.   rI   rK   r>   rN   rD   s         r   rT   zFanoutCache.touch   sR     

3$++-U#	;;sFE22 		s   A 	AAc                     | j                  |      | j                  z  }| j                  |   }	 |j                  ||||||      S # t        $ r Y yw xY w)a  Add `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(   addr   rH   s	            r   rV   zFanoutCache.add   sX    0 

3$++-U#	99S%sEBB 		rO   c                     | j                  |      | j                  z  }| j                  |   }	 |j                  ||||      S # t        $ r Y yw xY w)a  Increment 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(   incrr   r.   rI   deltadefaultr>   rN   rD   s          r   rX   zFanoutCache.incr   sT    0 

3$++-U#	::c5'599 		   A 	AAc                     | j                  |      | j                  z  }| j                  |   }	 |j                  ||||      S # t        $ r Y yw xY w)a  Decrement 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(   decrr   rY   s          r   r^   zFanoutCache.decr   sT    6 

3$++-U#	::c5'599 		r\   c                     | j                  |      | j                  z  }| j                  |   }	 |j                  ||||||      S # t        t
        j                  f$ r |cY S w xY w)a  Retrieve 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(   getr   sqlite3OperationalError)	r.   rI   r[   rL   expire_timerM   r>   rN   rD   s	            r   r`   zFanoutCache.get  se    2 

3$++-U#	99S'4c5II112 	N	s   A A#"A#c                 f    | j                  |      | j                  z  }| 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

        rQ   r.   rI   rN   rD   s       r   __getitem__zFanoutCache.__getitem__!  s2     

3$++-U#Szr2   c                 ^    | j                  |t        dd      }|t        u rt        |      |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[   rL   r>   )r`   r   KeyError)r.   rI   handles      r   rL   zFanoutCache.read/  s1     #vDEV3-r2   c                 d    | j                  |      | j                  z  }| j                  |   }||v S )zReturn `True` if `key` matching item is found in cache.

        :param key: key for item
        :return: True if key is found

        rQ   re   s       r   __contains__zFanoutCache.__contains__<  s2     

3$++-U#e|r2   c                     | j                  |      | j                  z  }| j                  |   }	 |j                  |||||      S # t        $ r |cY S w xY w)a  Remove 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.   rI   r[   rc   rM   r>   rN   rD   s           r   r"   zFanoutCache.popG  sX    * 

3$++-U#	99S';UCC 	N	s   A AAc                     | j                  |      | j                  z  }| j                  |   }	 |j                  ||      S # t        $ r Y yw xY w)ag  Delete 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.   rI   r>   rN   rD   s        r   rn   zFanoutCache.deletec  sP     

3$++-U#	<<U++ 		s   A 	AAc                 d    | j                  |      | j                  z  }| j                  |   }||= y)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

        NrQ   re   s       r   __delitem__zFanoutCache.__delitem__w  s/     

3$++-U##Jr2   c                 |    fd| j                   D        }t        j                  t        j                  |g       S )a3  Check 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

        c              3   B   K   | ]  }|j                          y wN)check)r   rD   fixr>   s     r   r   z$FanoutCache.check.<locals>.<genexpr>  s     FEKKU+Fs   )r(   	functoolsreduceoperatoriadd)r.   ru   r>   warningss    `` r   rt   zFanoutCache.check  s-    ( GFx<<r2   c                 P    | j                  dt        j                         f|      S )a  Remove expired 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

        rK   argsr>   )_removetimer.   r>   s     r   rK   zFanoutCache.expire  s!     ||HDIIK>|GGr2   c                 F    | j                   D ]  }|j                           y)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_indexr.   rD   s     r   r   zFanoutCache.create_tag_index  s#     \\ 	%E""$	%r2   c                 F    | j                   D ]  }|j                           y)z`Drop tag index on cache database.

        :raises Timeout: if database timeout occurs

        N)r(   drop_tag_indexr   s     r   r   zFanoutCache.drop_tag_index  s#     \\ 	#E  "	#r2   c                 ,    | j                  d|f|      S )aL  Remove 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.   rM   r>   s      r   r   zFanoutCache.evict  s     ||G3&|>>r2   c                 (    | j                  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=   r   r   s     r   r   zFanoutCache.cull  s     ||F%|00r2   c                 (    | j                  d|      S )a  Remove 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=   r   r   s     r   r   zFanoutCache.clear  s     ||G5|11r2   c                     d}| j                   D ]  }t        ||      }	 	  ||d|i}||z  } |S # t        $ r}||j                  d   z  }Y d }~nd }~ww xY w;)Nr   r>   )r(   r7   r   r}   )	r.   r8   r}   r>   totalrD   methodcountr   s	            r   r~   zFanoutCache._remove  s{    \\ 		EUD)F"D66EUNE 		 	  -W\\!_,E-	 s   1	AAAc                     | j                   D cg c]  }|j                  ||       }}t        d |D              }t        d |D              }||fS c c}w )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              3   &   K   | ]	  \  }}|  y wrs   r   )r   hits_s      r   r   z$FanoutCache.stats.<locals>.<genexpr>  s     5'$5   c              3   &   K   | ]	  \  }}|  y wrs   r   )r   r   missess      r   r   z$FanoutCache.stats.<locals>.<genexpr>  s     ;ia6;r   )r(   statssum)r.   enableresetrD   results
total_hitstotal_missess          r   r   zFanoutCache.stats  sX     <@<<H%5;;vu-HH5W55
;7;;<'' Is   Ac                 :    t        d | j                  D              S )zWReturn estimated total size of cache on disk.

        :return: size in bytes

        c              3   <   K   | ]  }|j                           y wrs   )volumer   rD   s     r   r   z%FanoutCache.volume.<locals>.<genexpr>  s     <e5<<><s   r   r(   r4   s    r   r   zFanoutCache.volume  s     <t||<<<r2   c                     | j                   D ]  }|j                           | j                  j                          | j                  j                          | j
                  j                          y)zClose database connection.N)r(   closer+   r   r,   r-   r   s     r   r   zFanoutCache.close  sN    \\ 	EKKM	r2   c                     | S rs   r   r4   s    r   	__enter__zFanoutCache.__enter__  s    r2   c                 $    | j                          y rs   )r   )r.   	exceptions     r   __exit__zFanoutCache.__exit__  s    

r2   c                 p    | j                   | j                  | j                  t        | j                        fS rs   )r$   r#   r   typer   r4   s    r   __getstate__zFanoutCache.__getstate__  s%    dllDOLLr2   c                 "     | j                   |  y rs   )r1   )r.   states     r   __setstate__zFanoutCache.__setstate__  s    ur2   c                 f    d | j                   D        }t        j                  j                  |      S )z.Iterate keys in cache including expired items.c              3   2   K   | ]  }t        |        y wrs   )iterr   s     r   r   z'FanoutCache.__iter__.<locals>.<genexpr>  s     ;UT%[;   )r(   itchainfrom_iterabler.   	iteratorss     r   __iter__zFanoutCache.__iter__  s%    ;dll;	xx%%i00r2   c                 x    d t        | j                        D        }t        j                  j	                  |      S )z6Reverse iterate keys in cache including expired items.c              3   2   K   | ]  }t        |        y wrs   )reversedr   s     r   r   z+FanoutCache.__reversed__.<locals>.<genexpr>  s     IXe_Ir   )r   r(   r   r   r   r   s     r   __reversed__zFanoutCache.__reversed__  s*    I(4<<2HI	xx%%i00r2   c                 :    t        d | j                  D              S )z0Count of items in cache including expired items.c              3   2   K   | ]  }t        |        y wrs   )lenr   s     r   r   z&FanoutCache.__len__.<locals>.<genexpr>#  s     8%3u:8r   r   r4   s    r   __len__zFanoutCache.__len__!  s    84<<888r2   c                 p    | j                   D ]  }	 	 |j                  ||      } S # t        $ r Y nw xY w')aT  Reset `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(   r   r   )r.   rI   rJ   rD   results        r   r   zFanoutCache.reset%  sT    $ \\ 	E"[[e4F 	 	   s   (	44c                     | j                   }	 ||   S # t        $ r] |j                  d      }t        j                  | j
                  dg| }t        d|||| j                  nt        d|}|||<   |cY S w xY w)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

        /cache)r   r   r   r   )	r+   rh   splitr   r   r$   r   r%   r   )	r.   r8   r   r   r   r+   partsr   temps	            r   r   zFanoutCache.cacheA  s    . ,,	4=  
	JJsOEA5AI ##'<TZZT 	D !GDMK
	s    A#A98A9c                    | j                   }	 ||   S # t        $ rk |j                  d      }t        j                  | j
                  dg| }t        || j                  d      }t        j                  ||      }|||<   |cY S w xY w)a  Return Deque with given `name` in subdirectory.

        >>> 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

        r   dequenoner   r   eviction_policy)maxlen)
r,   rh   r   r   r   r$   r   r%   r	   	fromcache)r.   r8   r   r,   r   r   r   r   s           r   r   zFanoutCache.dequeh  s    $ ,,	4=  
	JJsOEA5AI#ZZ &E
 OOE&9E!GDML
	s    A1BBc                    | j                   }	 ||   S # t        $ ri |j                  d      }t        j                  | j
                  dg| }t        || j                  d      }t        j                  |      }|||<   |cY S w xY w)a  Return 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

        r   rN   r   r   )
r-   rh   r   r   r   r$   r   r%   r
   r   )r.   r8   r-   r   r   r   rN   s          r   rN   zFanoutCache.index  s    ( ==	D>! 
	JJsOEA5AI#ZZ &E
 OOE*E"HTNL
	s    A/BB)T)NFNF)NF)r   r   F)NFFFF)NFFF)F)FF)r   F)TF)<   Nrs   )0__name__
__module____qualname____doc__r   r1   propertyr   r;   r?   contextmanagerrA   rG   rR   rT   rV   rX   r^   r`   rf   rL   rk   r"   rn   rp   rt   rK   r   r   r   r   r   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rN   r   r2   r   r   r      s   , QD%N  .  @4(>> J @	 FK8(=.
H	%#?
1
2(=M1
1
9  & 8%N D"r2   r   )r   
contextlibr?   rv   	itertoolsr   rx   os.pathpathr   ra   r   r   corer   r   r   r   r   
persistentr	   r
   r   memoizer   r2   r   <module>r      sD    8         @ @ $\
 \
~ mm r2   