Skip to content

CachePort

The cache Ports are the contract a cache adapter implements. Every adapter implements CachePort. An adapter that declares CacheCapabilities.TTL also subclasses CacheTTLPort, and one that declares CacheCapabilities.PATTERN_MATCH also subclasses CachePatternPort.

domain.caches[<name>] and domain.cache_for(<projection>) return a Cache. Cache builds the keys, serializes the projections and resolves TTLs, then calls the adapter through these Ports.

See Cache Adapters for concrete adapter configuration.

Bases: Protocol

The key-value members every cache adapter implements.

An adapter subclasses this, or a sub-protocol, explicitly. The members map to CacheCapabilities.KEY_VALUE.

Source code in src/protean/port/cache.py
81
82
83
def __init__(
    self, name: str, domain: "Domain", config: Mapping[str, Any]
) -> None: ...

capabilities abstractmethod property

capabilities: CacheCapabilities

The behaviours this cache adapter supports.

ping abstractmethod

ping() -> bool

Whether the cache is reachable.

Source code in src/protean/port/cache.py
90
91
92
@abstractmethod
def ping(self) -> bool:
    """Whether the cache is reachable."""

health abstractmethod

health() -> CacheHealth

The adapter's health record.

Source code in src/protean/port/cache.py
94
95
96
@abstractmethod
def health(self) -> CacheHealth:
    """The adapter's health record."""

get_connection abstractmethod

get_connection() -> object

The native client, or the backing store for an adapter without one.

Source code in src/protean/port/cache.py
 98
 99
100
@abstractmethod
def get_connection(self) -> object:
    """The native client, or the backing store for an adapter without one."""

close

close() -> None

Release the adapter's connections. Does nothing by default.

Source code in src/protean/port/cache.py
102
103
104
105
106
def close(self) -> None:
    """Release the adapter's connections. Does nothing by default."""
    # mypy treats a Protocol member whose body is only a docstring as
    # abstract, which would make every adapter implement `close`.
    return None  # noqa: RET501

clear abstractmethod

clear() -> None

Remove every entry.

Source code in src/protean/port/cache.py
108
109
110
@abstractmethod
def clear(self) -> None:
    """Remove every entry."""

get abstractmethod

get(key: str) -> CacheEntry | None

The value stored under key, or None when the key is absent or has expired.

Source code in src/protean/port/cache.py
112
113
114
115
@abstractmethod
def get(self, key: str) -> CacheEntry | None:
    """The value stored under `key`, or `None` when the key is absent or
    has expired."""

put abstractmethod

put(key: str, value: CacheEntry, ttl: float | None) -> None

Store value under key, replacing any earlier value and expiry.

ttl is a positive, finite number of seconds, or None for an entry that never expires. A backend can refuse a TTL above its own limit, and the adapter then raises the backend's error. Redis refuses a TTL above about 9.2e15 seconds.

Source code in src/protean/port/cache.py
117
118
119
120
121
122
123
124
125
@abstractmethod
def put(self, key: str, value: CacheEntry, ttl: float | None) -> None:
    """Store `value` under `key`, replacing any earlier value and expiry.

    `ttl` is a positive, finite number of seconds, or `None` for an entry
    that never expires. A backend can refuse a TTL above its own limit,
    and the adapter then raises the backend's error. Redis refuses a TTL
    above about 9.2e15 seconds.
    """

delete abstractmethod

delete(key: str) -> None

Remove key. Does nothing if the key is absent.

Source code in src/protean/port/cache.py
127
128
129
@abstractmethod
def delete(self, key: str) -> None:
    """Remove `key`. Does nothing if the key is absent."""

CacheTTLPort

Bases: CachePort, Protocol

The per-key expiry members, unlocked by CacheCapabilities.TTL.

Source code in src/protean/port/cache.py
81
82
83
def __init__(
    self, name: str, domain: "Domain", config: Mapping[str, Any]
) -> None: ...

set_ttl abstractmethod

set_ttl(key: str, ttl: float) -> None

Make key expire ttl seconds from now.

ttl is a positive, finite number of seconds, with the same backend limit as put. Does nothing if the key is absent or has expired.

Source code in src/protean/port/cache.py
135
136
137
138
139
140
141
@abstractmethod
def set_ttl(self, key: str, ttl: float) -> None:
    """Make `key` expire `ttl` seconds from now.

    `ttl` is a positive, finite number of seconds, with the same backend
    limit as `put`. Does nothing if the key is absent or has expired.
    """

get_ttl abstractmethod

get_ttl(key: str) -> float | None

Seconds remaining before key expires.

  • None when there is no such key.
  • math.inf when the key exists and never expires.
  • the seconds remaining otherwise.
Source code in src/protean/port/cache.py
143
144
145
146
147
148
149
150
@abstractmethod
def get_ttl(self, key: str) -> float | None:
    """Seconds remaining before `key` expires.

    - `None` when there is no such key.
    - `math.inf` when the key exists and never expires.
    - the seconds remaining otherwise.
    """

CachePatternPort

Bases: CachePort, Protocol

The glob members, unlocked by CacheCapabilities.PATTERN_MATCH.

A pattern is a glob. * matches any run of characters, ? matches one, [...] is a character class, and other characters, including ., are literal. Bracket negation and escaping can differ between adapters, so callers keep patterns to the name:::* shape.

Source code in src/protean/port/cache.py
81
82
83
def __init__(
    self, name: str, domain: "Domain", config: Mapping[str, Any]
) -> None: ...

keys_matching abstractmethod

keys_matching(pattern: str) -> list[str]

The distinct keys that match pattern, in ascending order.

Source code in src/protean/port/cache.py
162
163
164
@abstractmethod
def keys_matching(self, pattern: str) -> list[str]:
    """The distinct keys that match `pattern`, in ascending order."""

count_matching abstractmethod

count_matching(pattern: str) -> int

The number of distinct keys that match pattern.

Source code in src/protean/port/cache.py
166
167
168
@abstractmethod
def count_matching(self, pattern: str) -> int:
    """The number of distinct keys that match `pattern`."""

delete_matching abstractmethod

delete_matching(pattern: str) -> None

Remove every key that matches pattern. Does nothing if none match.

Source code in src/protean/port/cache.py
170
171
172
@abstractmethod
def delete_matching(self, pattern: str) -> None:
    """Remove every key that matches `pattern`. Does nothing if none match."""

CacheCapabilities

Bases: Flag

The behaviours a cache adapter supports.

Each adapter declares one value through CachePort.capabilities. A caller or a conformance test reads the flag directly to learn whether the adapter supports a behaviour. Most adapters declare a named tier, LOCAL or DISTRIBUTED.

KEY_VALUE class-attribute instance-attribute

KEY_VALUE = auto()

Reads, writes and deletes by key, and clearing the cache: the CachePort members get, put, delete and clear, which every cache adapter implements.

TTL class-attribute instance-attribute

TTL = auto()

Per-key expiry: the CacheTTLPort members set_ttl and get_ttl.

PATTERN_MATCH class-attribute instance-attribute

PATTERN_MATCH = auto()

Glob reads, counts and deletes: the CachePatternPort members keys_matching, count_matching and delete_matching.

SHARED class-attribute instance-attribute

SHARED = auto()

A second adapter built from the same config sees the first one's writes while both are open.

DURABLE class-attribute instance-attribute

DURABLE = auto()

Entries survive closing the adapter and building a new one from the same config.

LOCAL class-attribute instance-attribute

Key-value reads and writes, per-key expiry and glob patterns, inside one adapter instance.

DISTRIBUTED class-attribute instance-attribute

DISTRIBUTED = LOCAL | SHARED | DURABLE

Everything in LOCAL, with entries shared across adapter instances and kept after an adapter closes.

CacheHealth

What CachePort.health reports.

pool instance-attribute

pool: PoolStats | None

The adapter's connection pool, or None for an adapter without one.

Cache

The framework's view of one cache adapter.

domain.caches[<name>] and domain.cache_for(<projection>) return one. The service builds every cache key: callers ask key_for for an entry's key and pattern_for for the glob over a projection's entries.

RAISES DESCRIPTION
ConfigurationError

When it is built, if the adapter has no capabilities or config attribute, if it declares TTL or PATTERN_MATCH without subclassing CacheTTLPort or CachePatternPort, or if the cache config has a TTL that is not a positive, finite number of seconds.

Source code in src/protean/infra/cache.py
146
147
148
149
150
151
def __init__(self, adapter: CachePort) -> None:
    self._adapter = adapter
    self._check_adapter_attributes()
    self._check_capability_ports()
    self._ttl = _resolve_ttl(adapter.config.get("TTL"), self._source)
    self._projections: dict[str, type[BaseProjection]] = {}

name property

name: str

The cache's name in the domain config.

capabilities property

capabilities: CacheCapabilities

The behaviours the adapter supports.

key_for

key_for(
    projection_cls: type[BaseProjection], identifier: Any
) -> str

The key the entry for identifier of projection_cls lives under.

The key is the projection class name in snake case, then :::, then str(identifier): key_for(OrderSummary, "ord-1") returns "order_summary:::ord-1". It needs no capability and does no I/O.

Source code in src/protean/infra/cache.py
206
207
208
209
210
211
212
213
def key_for(self, projection_cls: "type[BaseProjection]", identifier: Any) -> str:
    """The key the entry for `identifier` of `projection_cls` lives under.

    The key is the projection class name in snake case, then `:::`, then
    `str(identifier)`: `key_for(OrderSummary, "ord-1")` returns
    `"order_summary:::ord-1"`. It needs no capability and does no I/O.
    """
    return f"{_prefix_for(projection_cls)}{_KEY_SEPARATOR}{identifier!s}"

pattern_for

pattern_for(projection_cls: type[BaseProjection]) -> str

The glob that matches every entry of projection_cls.

pattern_for(OrderSummary) returns "order_summary:::*", the pattern count and remove_by_key_pattern take. It needs no capability and does no I/O.

Source code in src/protean/infra/cache.py
215
216
217
218
219
220
221
222
def pattern_for(self, projection_cls: "type[BaseProjection]") -> str:
    """The glob that matches every entry of `projection_cls`.

    `pattern_for(OrderSummary)` returns `"order_summary:::*"`, the pattern
    `count` and `remove_by_key_pattern` take. It needs no capability and
    does no I/O.
    """
    return f"{_prefix_for(projection_cls)}{_KEY_SEPARATOR}*"

ping

ping() -> bool

Whether the cache is reachable.

Source code in src/protean/infra/cache.py
289
290
291
def ping(self) -> bool:
    """Whether the cache is reachable."""
    return self._adapter.ping()

get_connection

get_connection() -> object

The adapter's native client, such as a redis.Redis instance.

Source code in src/protean/infra/cache.py
293
294
295
def get_connection(self) -> object:
    """The adapter's native client, such as a `redis.Redis` instance."""
    return self._adapter.get_connection()

add

add(
    projection: BaseProjection, ttl: TTLValue | None = None
) -> None

Cache the projection's to_dict() data under its key.

PARAMETER DESCRIPTION
projection

The projection to cache.

TYPE: BaseProjection

ttl

Seconds the entry lives, as a number or a string holding one. None or "" uses this cache's TTL, which is DEFAULT_TTL when the cache configures none. On a cache without CacheCapabilities.TTL, an unset TTL stores the entry with no expiry.

TYPE: TTLValue | None DEFAULT: None

RAISES DESCRIPTION
ConfigurationError

ttl is not a positive, finite number of seconds. The message names the cache, and nothing is cached.

NotSupportedError

The caller supplied ttl and the cache does not support CacheCapabilities.TTL. Nothing is cached.

Source code in src/protean/infra/cache.py
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
def add(self, projection: "BaseProjection", ttl: TTLValue | None = None) -> None:
    """Cache the projection's `to_dict()` data under its key.

    Args:
        projection: The projection to cache.
        ttl: Seconds the entry lives, as a number or a string holding one.
            `None` or `""` uses this cache's `TTL`, which is `DEFAULT_TTL`
            when the cache configures none. On a cache without
            `CacheCapabilities.TTL`, an unset TTL stores the entry with no
            expiry.

    Raises:
        ConfigurationError: `ttl` is not a positive, finite number of
            seconds. The message names the cache, and nothing is cached.
        NotSupportedError: The caller supplied `ttl` and the cache does not
            support `CacheCapabilities.TTL`. Nothing is cached.
    """
    resolved_ttl = self._write_ttl(ttl)
    self._adapter.put(self._key_for(projection), projection.to_dict(), resolved_ttl)

get

get(key: str) -> BaseProjection | None

The projection cached under key, or None when there is none.

RAISES DESCRIPTION
KeyError

No projection class is registered under the key's prefix.

Source code in src/protean/infra/cache.py
317
318
319
320
321
322
323
324
325
def get(self, key: str) -> "BaseProjection | None":
    """The projection cached under `key`, or `None` when there is none.

    Raises:
        KeyError: No projection class is registered under the key's prefix.
    """
    projection_cls = self._projection_cls(key)
    value = self._adapter.get(key)
    return None if value is None else projection_cls(value)

count

count(key_pattern: str) -> int

Number of entries whose key matches key_pattern.

key_pattern is a glob. See _get_all for the syntax.

RAISES DESCRIPTION
NotSupportedError

The cache does not support CacheCapabilities.PATTERN_MATCH.

Source code in src/protean/infra/cache.py
359
360
361
362
363
364
365
366
367
368
def count(self, key_pattern: str) -> int:
    """Number of entries whose key matches `key_pattern`.

    `key_pattern` is a glob. See `_get_all` for the syntax.

    Raises:
        NotSupportedError: The cache does not support
            `CacheCapabilities.PATTERN_MATCH`.
    """
    return self._pattern_port().count_matching(key_pattern)

remove

remove(projection: BaseProjection) -> None

Remove the projection's entry. Does nothing if there is none.

Source code in src/protean/infra/cache.py
370
371
372
def remove(self, projection: "BaseProjection") -> None:
    """Remove the projection's entry. Does nothing if there is none."""
    self._adapter.delete(self._key_for(projection))

remove_by_key

remove_by_key(key: str) -> None

Remove the entry under key. Does nothing if the key is absent.

Source code in src/protean/infra/cache.py
374
375
376
def remove_by_key(self, key: str) -> None:
    """Remove the entry under `key`. Does nothing if the key is absent."""
    self._adapter.delete(key)

remove_by_key_pattern

remove_by_key_pattern(key_pattern: str) -> None

Remove every entry whose key matches key_pattern.

key_pattern is a glob. See _get_all for the syntax. Does nothing if the pattern matches no keys.

RAISES DESCRIPTION
NotSupportedError

The cache does not support CacheCapabilities.PATTERN_MATCH.

Source code in src/protean/infra/cache.py
378
379
380
381
382
383
384
385
386
387
388
def remove_by_key_pattern(self, key_pattern: str) -> None:
    """Remove every entry whose key matches `key_pattern`.

    `key_pattern` is a glob. See `_get_all` for the syntax. Does nothing if
    the pattern matches no keys.

    Raises:
        NotSupportedError: The cache does not support
            `CacheCapabilities.PATTERN_MATCH`.
    """
    self._pattern_port().delete_matching(key_pattern)

clear

clear() -> None

Remove every entry in the cache.

Source code in src/protean/infra/cache.py
390
391
392
def clear(self) -> None:
    """Remove every entry in the cache."""
    self._adapter.clear()

set_ttl

set_ttl(key: str, ttl: TTLValue | None) -> None

Set a TTL explicitly on a key.

Takes the same shapes as add: a number, or a string holding one. None or "" uses this cache's TTL. Does nothing if the key is absent.

RAISES DESCRIPTION
NotSupportedError

The cache does not support CacheCapabilities.TTL.

ConfigurationError

ttl is not a positive, finite number of seconds, whether or not the key is present.

Source code in src/protean/infra/cache.py
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
def set_ttl(self, key: str, ttl: TTLValue | None) -> None:
    """Set a TTL explicitly on a key.

    Takes the same shapes as `add`: a number, or a string holding one.
    `None` or `""` uses this cache's `TTL`. Does nothing if the key is
    absent.

    Raises:
        NotSupportedError: The cache does not support
            `CacheCapabilities.TTL`.
        ConfigurationError: `ttl` is not a positive, finite number of
            seconds, whether or not the key is present.
    """
    port = self._ttl_port()
    port.set_ttl(key, float(self._resolved_ttl(ttl)))

get_ttl

get_ttl(key: str) -> float | None

Seconds remaining before key expires.

  • None when there is no such key.
  • math.inf when the key exists and never expires.
  • the seconds remaining otherwise.
RAISES DESCRIPTION
NotSupportedError

The cache does not support CacheCapabilities.TTL.

Source code in src/protean/infra/cache.py
410
411
412
413
414
415
416
417
418
419
420
421
def get_ttl(self, key: str) -> float | None:
    """Seconds remaining before `key` expires.

    - `None` when there is no such key.
    - `math.inf` when the key exists and never expires.
    - the seconds remaining otherwise.

    Raises:
        NotSupportedError: The cache does not support
            `CacheCapabilities.TTL`.
    """
    return self._ttl_port().get_ttl(key)