tempest_fastapi_sdk.cache¶
Cache Redis assíncrono, o decorator @cached e a invalidação por chave e por tag.
AsyncRedisManager
¶
Manage the lifecycle of a single async Redis client.
Mirrors the public surface of
:class:tempest_fastapi_sdk.AsyncDatabaseManager so application
bootstrapping stays uniform across backends. The actual client is
created on first :meth:connect call; in-process callers can use
:meth:get_client_context from a FastAPI dependency or any async
context manager.
Attributes:
| Name | Type | Description |
|---|---|---|
url |
str
|
The Redis connection URL. |
decode_responses |
bool
|
Whether the underlying client
decodes responses to |
Initialize the manager (no connection opened yet).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The Redis URL ( |
required |
decode_responses
|
bool
|
Whether to decode bytes to strings on every command. |
True
|
**client_kwargs
|
Any
|
Extra kwargs forwarded to
|
{}
|
client
property
¶
Return the live client.
Returns:
| Name | Type | Description |
|---|---|---|
Redis |
Redis
|
The connected Redis client. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When :meth: |
client_proxy
property
¶
Return a stable handle that stays valid across reconnects.
Use this -- not :attr:client -- wherever a Redis-backed store
has to be built before the lifespan runs, which is every
store passed to add_middleware:
.. code-block:: python
redis = AsyncRedisManager(settings.REDIS_URL)
app.add_middleware(
RateLimitMiddleware,
store=RedisRateLimitStore(redis.client_proxy),
)
The same object comes back on every call, and each command it
forwards resolves the client that is live at that moment, so a
:meth:disconnect / :meth:connect cycle does not leave the
store holding a dead client.
It is a forwarding handle, not a Redis instance: the return
type is declared as Redis so it type-checks into every store
parameter, but isinstance(manager.client_proxy, Redis) is
False and dunder protocols looked up on the type (async
with proxy) do not forward. Reading an attribute before the
first :meth:connect raises RuntimeError, same as
:attr:client -- what changes is that building the store no
longer does.
Returns:
| Name | Type | Description |
|---|---|---|
Redis |
Redis
|
The forwarding handle onto the live client. |
connect
async
¶
Open the underlying Redis client.
Safe to call multiple times — subsequent calls are no-ops while the same client is alive.
disconnect
async
¶
Close the underlying client and release its connection pool.
get_client_context
async
¶
Yield the live client inside an async with block.
The manager owns the lifecycle — exiting the context does
NOT close the underlying client. Use :meth:disconnect
during application shutdown instead.
Yields:
| Name | Type | Description |
|---|---|---|
Redis |
AsyncGenerator[Redis, None]
|
The connected client. |
client_dependency
async
¶
Async generator dependency suitable for FastAPI Depends.
Yields:
| Name | Type | Description |
|---|---|---|
Redis |
AsyncIterator[Redis]
|
The connected client. |
health_check
async
¶
Return True when PING succeeds.
Errors are caught and logged at WARNING level — the health router treats exceptions as a failed check.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
cached
¶
cached(
redis: AsyncRedisManager,
*,
ttl: int = 300,
key_prefix: str = "",
key_builder: Callable[[str, tuple[Any, ...], dict[str, Any]], str] | None = None,
serializer: Callable[[Any], str] = dumps,
deserializer: Callable[[str | bytes], Any] = loads,
skip_cache: Callable[[tuple[Any, ...], dict[str, Any]], bool] | None = None,
namespace: str | None = None,
tags: TagSpec = None,
) -> Callable[[F[T]], F[T]]
Cache the result of an async function in Redis.
Cache keys are <key_prefix><func_qualname>:<sha256>. On miss
the wrapped function runs and its result is stored with TTL
ttl. On hit the cached value is deserialized and returned
without re-running the function.
Tag / namespace invalidation. When namespace and/or tags
are set, every stored entry's key is also added to a Redis set per
label (see :func:tempest_fastapi_sdk.cache.namespace_registry_key
/ :func:tag_registry_key). A mutation then drops every dependent
entry at once via
:class:tempest_fastapi_sdk.cache.CacheInvalidator, instead of
waiting out each TTL::
@cached(redis, key_prefix="users:", namespace="profiles",
tags=lambda args, kwargs: [f"user:{kwargs['user_id']}"])
async def get_profile(*, user_id: int) -> dict[str, Any]: ...
# On update:
await CacheInvalidator(redis, key_prefix="users:").invalidate_tag(
f"user:{user_id}",
)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
redis
|
AsyncRedisManager
|
The connected Redis manager. Calling
the decorated function before
:meth: |
required |
ttl
|
int
|
Cache TTL in seconds. |
300
|
key_prefix
|
str
|
Prefix prepended to every cache key (e.g.
|
''
|
key_builder
|
Callable[[str, tuple, dict], str] | None
|
Custom
cache key builder, called with the qualified name and the
call's full |
None
|
serializer
|
Callable[[Any], str]
|
How to encode the result
before storing. Defaults to :func: |
dumps
|
deserializer
|
Callable[[str | bytes], Any]
|
How to decode the
cached payload (Redis returns |
loads
|
skip_cache
|
Callable[[tuple, dict], bool] | None
|
Optional
predicate. When it returns |
None
|
namespace
|
str | None
|
Coarse label grouping every entry this
decorator writes, cleared via
:meth: |
None
|
tags
|
TagSpec
|
Static tags (a sequence) or a per-call builder
|
None
|
Returns:
| Type | Description |
|---|---|
Callable[[F[T]], F[T]]
|
Callable[[F[T]], F[T]]: A decorator preserving the signature |
Callable[[F[T]], F[T]]
|
of the wrapped async callable. |
CacheInvalidator
¶
CacheInvalidator(redis: AsyncRedisManager, *, key_prefix: str = '')
Drops @cached entries by namespace, tag or raw key.
Bind it to the same :class:AsyncRedisManager and key_prefix
the matching @cached decorators use, then call it from the
service that performs the mutation::
invalidator = CacheInvalidator(redis, key_prefix="users:")
await invalidator.invalidate_tag(f"user:{user_id}")
Each method returns the number of entry keys deleted.
Initialize the invalidator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
redis
|
AsyncRedisManager
|
The connected Redis manager. It
must match the manager used by the |
required |
key_prefix
|
str
|
The same |
''
|
invalidate_namespace
async
¶
Delete every entry written under namespace.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
str
|
The namespace label to clear. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The number of entry keys deleted. |
invalidate_tag
async
¶
Delete every entry carrying tag.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tag
|
str
|
The tag label to clear. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The number of entry keys deleted. |
invalidate_tags
async
¶
Delete every entry carrying any of tags.
Entries shared by several tags are deleted once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*tags
|
str
|
The tag labels to clear. |
()
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The number of distinct entry keys deleted. |
invalidate_keys
async
¶
Delete specific fully-qualified cache keys.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*keys
|
str
|
The raw entry keys (including |
()
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The number of keys deleted (per Redis |