
    Q
i$                         d Z ddlmZ ddlmZmZmZmZ ddlm	Z	 ddl
mZ ddlmZ ddlmZmZmZ  G d d	          Zd
S )zBase cache interface for RedisVL.

This module defines the abstract base cache interface that is implemented by
specific cache types such as LLM caches and embedding caches.
    )Mapping)AnyDictOptionalUnion)Redis)RedisCluster)RedisConnectionFactory)AsyncRedisClientSyncRedisClientSyncRedisClusterc                   ~   e Zd ZU dZee         ed<   ee         ed<   ddddi fdedee	         dee         d	ee         d
ede
eef         fdZdefdZdedefdZedee	         fd            Zddee	         ddfdZdefdZdefdZddedee	         ddfdZddedee	         ddfdZddZddZddZddZdS )	BaseCachezBase abstract cache interface for all RedisVL caches.

    This class defines common functionality shared by all cache implementations,
    including TTL management, connection handling, and basic cache operations.
    _redis_client_async_redis_clientNzredis://localhost:6379namettlredis_clientasync_redis_client	redis_urlconnection_kwargsc                     || _         d| _        |                     |           |||d| _        || _        || _        |s|r	d| _        dS d| _        dS )a?  Initialize a base cache.

        Args:
            name (str): The name of the cache.
            ttl (Optional[int], optional): The time-to-live for records cached
                in Redis. Defaults to None.
            redis_client (Optional[SyncRedisClient], optional): A redis client connection instance.
                Defaults to None.
            redis_url (str, optional): The redis url. Defaults to redis://localhost:6379.
            connection_kwargs (Dict[str, Any]): The connection arguments
                for the redis client. Defaults to empty {}.
        N)r   r   r   FT)r   _ttlset_ttlredis_kwargsr   r   _owns_redis_client)selfr   r   r   r   r   r   s          C:\Users\Dell Inspiron 16\Desktop\tws\AgrotaPowerBi\back-agrota-powerbi\mcp-client-agrota\venv\Lib\site-packages\redisvl/extensions/cache/base.py__init__zBaseCache.__init__   s|    * 	#'	S )"!2
 
 $6 ) 	+- 	+&+D###&*D###    returnc                     | j          dS )zpGet the key prefix for Redis keys.

        Returns:
            str: The prefix to use for Redis keys.
        :)r   r   s    r   _get_prefixzBaseCache._get_prefixC   s     )r    entry_idc                 2    |                                   | S )zGenerate a full Redis key for the given entry ID.

        Args:
            entry_id (str): The unique entry ID.

        Returns:
            str: The full Redis key including prefix.
        )r%   )r   r&   s     r   	_make_keyzBaseCache._make_keyK   s!     ""$$0h000r    c                     | j         S )z6The default TTL, in seconds, for entries in the cache.)r   r$   s    r   r   zBaseCache.ttlV   s     yr    c                     |r=t          |t                    st          d|           t          |          | _        dS d| _        dS )a#  Set the default TTL, in seconds, for entries in the cache.

        Args:
            ttl (Optional[int], optional): The optional time-to-live expiration
                for the cache, in seconds.

        Raises:
            ValueError: If the time-to-live value is not an integer.
        z"TTL must be an integer value, got N)
isinstanceint
ValueErrorr   )r   r   s     r   r   zBaseCache.set_ttl[   sR      	c3'' M !Kc!K!KLLLCDIIIDIIIr    c                     | j         1| j        d         }| j        d         }t          j        |fi || _         | j         S )znGet or create a Redis client.

        Returns:
            SyncRedisClient: A Redis client instance.
        Nr   r   )r   r   r   from_url)r   urlkwargss      r   _get_redis_clientzBaseCache._get_redis_clientl   sK     %#K0C&':;F!&!>!>v!>!>D!!r    c                   K   t          | d          r| j        | j                            d          }|r6t	          |t
          t          f          rt          j        |          | _        nt          | j        d                   }| j                            di           }t	          |t                    s$t          dt          |          j                   t          j        |fi || _        | j        S )z}Get or create an async Redis client.

        Returns:
            AsyncRedisClient: An async Redis client instance.
        r   Nr   r   r   zaExpected `connection_kwargs` to be a dictionary (e.g. {'decode_responses': True}), but got type: )hasattrr   r   getr+   r   r	   r
   sync_to_async_redisstrr   	TypeErrortype__name__get_async_redis_connection)r   clientr0   r1   s       r   _get_async_redis_clientz!BaseCache._get_async_redis_clienty   s      t233 	t7O7W&**>::F *Ve\-BCC +A+U, ,(( $+K899*../BBGG!&'22 #A)-f)>A A  
 +EcTTVTT ( ''r    keyc                 x    ||n| j         }|r,|                                 }|                    ||           dS dS )a  Set or refresh the expiration time for a key in the cache.

        Args:
            key (str): The Redis key to set the expiration on.
            ttl (Optional[int], optional): The time-to-live in seconds. If None,
                uses the default TTL configured for this cache instance.
                Defaults to None.

        Note:
            If neither the provided TTL nor the default TTL is set (both are None),
            this method will have no effect.
        N)r   r2   expirer   r>   r   r   r<   s        r   r@   zBaseCache.expire   sP     oss49 	%++--FMM#t$$$$$	% 	%r    c                    K   ||n| j         }|r8|                                  d{V }|                    ||           d{V  dS dS )a  Asynchronously set or refresh the expiration time for a key in the cache.

        Args:
            key (str): The Redis key to set the expiration on.
            ttl (Optional[int], optional): The time-to-live in seconds. If None,
                uses the default TTL configured for this cache instance.
                Defaults to None.

        Note:
            If neither the provided TTL nor the default TTL is set (both are None),
            this method will have no effect.
        N)r   r=   r@   rA   s        r   aexpirezBaseCache.aexpire   sx       oss49 	+7799999999F--T***********	+ 	+r    c                 f   |                                  }|                                 }d}	 |                    || dd          \  }}|r
 |j        |  |dk    rdS t	          |t
                    r=t          |                                          }t          d |D                       rdS n|})zClear the cache of all keys.r   T*d   cursormatchcountc              3   "   K   | ]
}|d k    V  dS r   N .0vs     r   	<genexpr>z"BaseCache.clear.<locals>.<genexpr>   &      55!qAv555555r    N)	r2   r%   scandeleter+   r   listvaluesallr   r<   prefixrH   
cursor_intkeyscursor_valuess          r   clearzBaseCache.clear   s    ''))!!## 	$%{{&6TW{XXJ %t$$Q J00 $ $Z%6%6%8%8 9 955}55555 E $	$r    c                   K   |                                   d{V }|                                 }d}	 |                    || dd           d{V \  }}|r |j        |  d{V  |dk    rdS t	          |t
                    r=t          |                                          }t          d |D                       rdS n|})z"Async clear the cache of all keys.Nr   TrE   rF   rG   c              3   "   K   | ]
}|d k    V  dS rL   rM   rN   s     r   rQ   z#BaseCache.aclear.<locals>.<genexpr>   rR   r    )	r=   r%   rS   rT   r+   r   rU   rV   rW   rX   s          r   aclearzBaseCache.aclear   s)     3355555555!!## 	$%+[[\\\ &1 & &            J  +#fmT********Q J00 $ $Z%6%6%8%8 9 955}55555 E $	$r    c                 |    | j         du rdS | j        r)| j                                         d| _        d| _        dS dS )zDisconnect from Redis.FN)r   r   closer   r$   s    r   
disconnectzBaseCache.disconnect   sW    "e++F 	,$$&&&!%D (,D$$$	, 	,r    c                    K   | j         du rdS | j        r | j                                         d| _        t          | d          r/| j        r*| j                                         d{V  d| _        dS dS dS )zAsync disconnect from Redis.FNr   )r   r   rb   r4   r   acloser$   s    r   adisconnectzBaseCache.adisconnect   s      "e++F 	&$$&&&!%D4.// 	,D4L 	,*11333333333'+D$$$	, 	, 	, 	,r    )N)r!   N)r:   
__module____qualname____doc__r   r   __annotations__r   r7   r,   r   r   r   r%   r(   propertyr   r   r2   r=   r@   rC   r]   r`   rc   rf   rM   r    r   r   r      s?          O,,,,!"23333
 "269=1,.&+ &+&+ c]&+ /	&+
 %%56&+ &+  S>&+ &+ &+ &+PS    	1# 	1# 	1 	1 	1 	1 Xc]    X 8C= D    ""? " " " "(/? ( ( ( (4% %# %HSM %T % % % %$+ + +8C= +D + + + +$$ $ $ $,$ $ $ $0
, 
, 
, 
,, , , , , ,r    r   N)ri   collections.abcr   typingr   r   r   r   redisr   redis.clusterr	   redisvl.redis.connectionr
   redisvl.typesr   r   r   r   rM   r    r   <module>rr      s     $ # # # # # - - - - - - - - - - - -       & & & & & & ; ; ; ; ; ; M M M M M M M M M Ml, l, l, l, l, l, l, l, l, l,r    