In Memory
mongo_ops.cache.in_memory
Summary
In-memory cache backend with TTL-based eviction and encode/decode helpers.
Classes
InMemoryCacheBackend
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 | |
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
Remove all keys matching a glob pattern.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern |
str
|
Glob-style pattern; a trailing |
required |
delete
async
Remove a key from the cache.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key |
str
|
The cache key. |
required |
exists
async
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
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
Return a snapshot of cache statistics.
Returns:
| Name | Type | Description |
|---|---|---|
CacheStats |
CacheStats
|
A copy of the current stats counters. |
set
async
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
|
Functions
decode_value
Decode cache bytes back into a dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data |
bytes
|
UTF-8 JSON bytes produced by encode_value(). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
The decoded dictionary. |
encode_value
Encode a dict into cache-ready bytes.
Non-serializable values (e.g., ObjectId) are coerced with str().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value |
dict
|
The dictionary to encode. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bytes |
bytes
|
UTF-8 JSON bytes. |