Skip to content

Cache

mongo_ops.cache

Summary

Cache backends and configuration for mongo-ops.

Classes

CacheBackend

Bases: ABC

Abstract interface for cache backends.

Implementations store byte-encoded values keyed by string, track usage statistics, and manage their own lifecycle. The in-memory and Redis backends both implement this contract.

Functions
clear_pattern abstractmethod async
clear_pattern(pattern: str) -> None

Remove all keys matching a glob pattern.

Parameters:

Name Type Description Default
pattern str

Glob-style pattern; a trailing * matches prefixes.

required
delete abstractmethod async
delete(key: str) -> None

Remove a key from the cache.

Parameters:

Name Type Description Default
key str

The cache key.

required
exists abstractmethod async
exists(key: str) -> bool

Check whether a key is present.

Parameters:

Name Type Description Default
key str

The cache key.

required

Returns:

Name Type Description
bool bool

True if the key exists, False otherwise.

get abstractmethod async
get(key: str) -> bytes | None

Fetch a value from the cache.

Parameters:

Name Type Description Default
key str

The cache key.

required

Returns:

Type Description
bytes | None

Optional[bytes]: The cached bytes, or None on a miss.

get_stats abstractmethod async
get_stats() -> CacheStats

Return a snapshot of cache statistics.

Returns:

Name Type Description
CacheStats CacheStats

A copy of the current stats counters.

initialize abstractmethod async
initialize() -> None

Start background resources owned by the backend.

Should be called once during application startup, after the repositories are connected.

set abstractmethod async
set(key: str, value: bytes, ttl: int | None = None) -> None

Store a value in the cache.

Parameters:

Name Type Description Default
key str

The cache key.

required
value bytes

The byte-encoded value to store.

required
ttl Optional[int]

Time-to-live in seconds. When None, the backend default applies.

None
shutdown abstractmethod async
shutdown() -> None

Stop and release background resources.

Should be called once during application shutdown.

CacheConfig dataclass

1
2
3
4
5
6
7
8
9
CacheConfig(
    enabled: bool = True,
    backend: Literal["memory", "redis"] = "memory",
    redis_client: Redis | None = None,
    default_ttl: int = 300,
    max_entries: int = 10000,
    key_prefix: str = "",
    cleanup_interval: int = 60,
)

Configuration for the cached repository layer.

Attributes:

Name Type Description
enabled bool

Whether caching is active for the repository.

backend Literal['memory', 'redis']

Which backend to use. Defaults to "memory".

redis_client Optional[Redis]

Redis client required when backend is "redis".

default_ttl int

Default time-to-live for cached entries, in seconds.

max_entries int

Maximum entries for the in-memory backend.

key_prefix str

Prefix applied to cache keys; defaults to the collection name when empty.

cleanup_interval int

Interval (seconds) for the in-memory expiry sweep.

Functions
__post_init__
__post_init__() -> None

Validate backend/redis consistency.

Raises:

Type Description
ValueError

If the backend is "redis" and no client is given.

ImportError

If the redis package is not installed.

CacheStats dataclass

1
2
3
4
5
6
7
8
CacheStats(
    hits: int = 0,
    misses: int = 0,
    sets: int = 0,
    deletes: int = 0,
    current_size: int = 0,
    max_size: int = 0,
)

Snapshot of cache usage and activity counters.

Attributes:

Name Type Description
hits int

Number of get() calls that found a value.

misses int

Number of get() calls that returned None.

sets int

Number of values written to the cache.

deletes int

Number of keys removed.

current_size int

Number of entries currently held.

max_size int

Maximum number of entries the cache allows (0 = unbounded).

CircularReferenceError

1
2
3
CircularReferenceError(
    collection: str, doc_id: ObjectId, path: list[str]
)

Bases: ValueError

Raised when population detects a cycle in the reference graph.

Attributes:

Name Type Description
collection str

Collection where the cycle was detected.

doc_id ObjectId

Document ID where the cycle was detected.

path list[str]

Ordered labels describing the visited reference path.

Initialize the error with cycle metadata.

Parameters:

Name Type Description Default
collection str

Collection where the cycle was detected.

required
doc_id ObjectId

Document ID where the cycle was detected.

required
path list[str]

Ordered labels describing the visited reference path.

required
Functions

InMemoryCacheBackend

1
2
3
4
5
InMemoryCacheBackend(
    max_entries: int = 10000,
    default_ttl: int = 300,
    cleanup_interval: int = 60,
)

Bases: CacheBackend

Cache backend backed by an in-memory dict with TTL expiry.

Entries are stored in an OrderedDict for LRU-compatible eviction and a min-heap of expiry timestamps drives periodic removal of stale entries.

Notes

Thread safety:

1
2
All operations take an asyncio lock; the backend is safe for
concurrent use within a single event loop.

Initialize the backend.

Parameters:

Name Type Description Default
max_entries int

Maximum number of entries before LRU eviction kicks in.

10000
default_ttl int

Default time-to-live for entries, in seconds.

300
cleanup_interval int

Seconds between periodic expired-entry sweeps.

60
Functions
clear_pattern async
clear_pattern(pattern: str) -> None

Remove all keys matching a glob pattern.

Parameters:

Name Type Description Default
pattern str

Glob-style pattern; a trailing * matches prefixes.

required
delete async
delete(key: str) -> None

Remove a key from the cache.

Parameters:

Name Type Description Default
key str

The cache key.

required
exists async
exists(key: str) -> bool

Check whether a key is present.

Parameters:

Name Type Description Default
key str

The cache key.

required

Returns:

Name Type Description
bool bool

True if the key exists, False otherwise.

get async
get(key: str) -> bytes | None

Fetch a value from the cache.

Parameters:

Name Type Description Default
key str

The cache key.

required

Returns:

Type Description
bytes | None

Optional[bytes]: The cached bytes, or None on a miss.

get_stats async
get_stats() -> CacheStats

Return a snapshot of cache statistics.

Returns:

Name Type Description
CacheStats CacheStats

A copy of the current stats counters.

initialize async
initialize() -> None

Start the periodic expired-entry cleanup task.

set async
set(key: str, value: bytes, ttl: int | None = None) -> None

Store a value in the cache.

Parameters:

Name Type Description Default
key str

The cache key.

required
value bytes

The byte-encoded value to store.

required
ttl Optional[int]

Time-to-live in seconds; defaults to the backend default.

None
shutdown async
shutdown() -> None

Cancel and await the cleanup task.