Ir para o conteúdo

tempest_fastapi_sdk.cache

Cache Redis assíncrono, o decorator @cached e a invalidação por chave e por tag.

« Admin, dados e API


AsyncRedisManager

AsyncRedisManager(url: str, *, decode_responses: bool = True, **client_kwargs: Any)

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

Initialize the manager (no connection opened yet).

Parameters:

Name Type Description Default
url str

The Redis URL (redis://... or rediss://... for TLS).

required
decode_responses bool

Whether to decode bytes to strings on every command.

True
**client_kwargs Any

Extra kwargs forwarded to redis.asyncio.Redis.from_url.

{}

client property

client: Redis

Return the live client.

Returns:

Name Type Description
Redis Redis

The connected Redis client.

Raises:

Type Description
RuntimeError

When :meth:connect was not called yet.

client_proxy property

client_proxy: Redis

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

connect() -> None

Open the underlying Redis client.

Safe to call multiple times — subsequent calls are no-ops while the same client is alive.

disconnect async

disconnect() -> None

Close the underlying client and release its connection pool.

get_client_context async

get_client_context() -> AsyncGenerator[Redis, None]

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

client_dependency() -> AsyncIterator[Redis]

Async generator dependency suitable for FastAPI Depends.

Yields:

Name Type Description
Redis AsyncIterator[Redis]

The connected client.

health_check async

health_check() -> bool

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

True when the server responded with PONG.

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:AsyncRedisManager.connect raises RuntimeError.

required
ttl int

Cache TTL in seconds. 0 disables expiration (Redis SET without EX). The registry sets share the same TTL, so they self-prune after their newest member.

300
key_prefix str

Prefix prepended to every cache key (e.g. "users:" to make invalidation easier). Pass the same prefix to :class:CacheInvalidator.

''
key_builder Callable[[str, tuple, dict], str] | None

Custom cache key builder, called with the qualified name and the call's full args / kwargs (receiver included). Defaults to a SHA-256 of args/kwargs encoded from their data, never from str(): a Pydantic model contributes every field (SecretStr included, as a hash of the secret), a dataclass its fields, and UUID / datetime / Decimal / Enum a typed value. An argument with no faithful encoding (an arbitrary object) makes the call run without the cache, with a cached_key_unencodable warning — pass a key_builder to cache it. The default leaves out the method receiver: when the decorated function's first parameter is self or cls, that argument is not part of the key, so every instance of the class shares the entry for the same remaining arguments. The qualified name (Class.method) still separates classes. A method whose result depends on instance state needs a key_builder that reads that state, or a pure function instead.

None
serializer Callable[[Any], str]

How to encode the result before storing. Defaults to :func:json.dumps.

dumps
deserializer Callable[[str | bytes], Any]

How to decode the cached payload (Redis returns bytes unless the client sets decode_responses=True). Defaults to :func:json.loads, which accepts both.

loads
skip_cache Callable[[tuple, dict], bool] | None

Optional predicate. When it returns True, the decorator bypasses cache for that call (read and write).

None
namespace str | None

Coarse label grouping every entry this decorator writes, cleared via :meth:CacheInvalidator.invalidate_namespace.

None
tags TagSpec

Static tags (a sequence) or a per-call builder (args, kwargs) -> Sequence[str] returning the tags for that entry (e.g. f"user:{id}"), cleared via :meth:CacheInvalidator.invalidate_tag.

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 @cached decorators whose entries are being invalidated.

required
key_prefix str

The same key_prefix those decorators use, so the registry set names line up.

''

invalidate_namespace async

invalidate_namespace(namespace: str) -> int

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

invalidate_tag(tag: str) -> int

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

invalidate_tags(*tags: str) -> int

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

invalidate_keys(*keys: str) -> int

Delete specific fully-qualified cache keys.

Parameters:

Name Type Description Default
*keys str

The raw entry keys (including key_prefix).

()

Returns:

Name Type Description
int int

The number of keys deleted (per Redis DEL).