Import cultcache-py into monorepo

This commit is contained in:
Meta Vens 2026-05-24 11:35:15 +01:00
commit 4472745cab
9 changed files with 949 additions and 0 deletions

7
python/cultcache-py/.gitignore vendored Normal file
View file

@ -0,0 +1,7 @@
__pycache__/
*.py[cod]
.venv/
.pytest_cache/
*.egg-info/
dist/
build/

View file

@ -0,0 +1,130 @@
# cultcache-py
`cultcache-py` is the Python port of GameCult's CultCache persistence pattern: callers work with registered domain documents while the cache owns schema identity, routing, globals, name lookups, indexes, and backing-store envelopes.
It is intentionally small. It is not an ORM, a database, or distributed consensus wearing rented authority.
## Current Shape
- document types are registered explicitly
- each persisted envelope stores `type`, `key`, `payload`, and `stored_at`
- payloads decode only through the registered document definition for that type
- unknown persisted types fail closed
- global documents are singleton-style per type
- type-specific backing stores beat generic backing stores
- the JSONL store uses only the Python standard library for bootstrap consumers
- the MessagePack store is available when the `msgpack` package is installed
- `define_database_entry_type(...)` emits Rust/C#-style slot-indexed
MessagePack array payloads for cross-runtime `DatabaseEntry` contracts
## Example
```python
from dataclasses import dataclass, asdict
from cultcache_py import CultCache, JsonLinesBackingStore, define_document_type
@dataclass
class Settings:
theme: str
retries: int
settings_doc = define_document_type(
"settings",
encode=lambda value: asdict(value),
decode=lambda payload: Settings(**payload),
global_document=True,
)
cache = (
CultCache.builder()
.register_document_type(settings_doc)
.add_generic_store(JsonLinesBackingStore("state.cultcache.jsonl"))
.build()
)
cache.pull_all_backing_stores()
cache.put_global(settings_doc, Settings(theme="ash", retries=3))
settings = cache.get_required_global(settings_doc)
```
## Public Surface
- `define_document_type(...)`
- `define_database_entry_type(...)`
- `database_entry_field(...)`
- `define_document_registry(...)`
- `CultCache.builder()`
- `register_document_type(...)`
- `register_registry(...)`
- `register_name_lookup(...)`
- `register_index(...)`
- `add_backing_store(...)`
- `add_generic_store(...)`
- `pull_all_backing_stores()`
- `get(...)`
- `get_required(...)`
- `get_all(...)`
- `get_key_by_name(...)`
- `get_by_name(...)`
- `get_key_by_index(...)`
- `get_by_index(...)`
- `get_global(...)`
- `get_required_global(...)`
- `put(...)`
- `put_global(...)`
- `update(...)`
- `update_global(...)`
- `delete(...)`
- `delete_global(...)`
- `snapshot()`
## Persistence Model
Backing stores persist envelopes, not caller domain objects. The cache decodes payloads through registered document definitions and rejects unknown type discriminators. This keeps Python's dynamic runtime from turning persistence into an open polymorphic sewer with a cheerful docstring.
`JsonLinesBackingStore` is the dependency-free control-plane store. It rewrites an atomic JSONL snapshot and base64-encodes payload bytes. It is designed for compact state spines, settings, ledgers, and bootstrap surfaces.
`SingleFileMessagePackBackingStore` follows the same envelope model using MessagePack. Install `msgpack` to use it:
```powershell
python -m pip install msgpack
```
Large corpora should use a sharded store or a real database. A single snapshot file is a scalpel, not a forklift.
## DatabaseEntry Slot Contract
For cross-runtime cache entries, use `define_database_entry_type(...)` instead
of the generic JSON formatter:
```python
from dataclasses import dataclass
from cultcache_py import define_database_entry_type
@dataclass
class Settings:
theme: str
retries: int = 0
settings_doc = define_database_entry_type(
"settings",
[
("theme", 0),
("retries", 1, 0),
],
cls=Settings,
)
```
The payload is a MessagePack array. Field keys are durable slot indexes:
- key `0` writes array slot 0
- key `4` writes array slot 4
- unused slots are written as nil
- deleted fields should leave their slots reserved
- newly added fields should use new keys
- fields with defaults tolerate missing or nil slots when older payloads are read
That matches the Rust `#[derive(DatabaseEntry)]` formatter shape and the C#
`[Key(n)]` intent: schema evolution comes from stable field slots, not source
member order.

View file

@ -0,0 +1,25 @@
[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"
[project]
name = "cultcache-py"
version = "0.1.0"
description = "Python CultCache-style typed persistence layer for GameCult control-plane state."
readme = "README.md"
requires-python = ">=3.10"
license = { text = "Private GameCult infrastructure" }
authors = [{ name = "GameCult" }]
classifiers = [
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
]
dependencies = []
[project.optional-dependencies]
msgpack = ["msgpack>=1.0"]
[tool.setuptools.packages.find]
where = ["src"]

View file

@ -0,0 +1,26 @@
from .backing_store import BackingStore, CultCacheEnvelope
from .cache import CultCache, CultCacheBuilder
from .documents import (
DatabaseEntryField,
DocumentDefinition,
database_entry_field,
define_database_entry_type,
define_document_registry,
define_document_type,
)
from .stores import JsonLinesBackingStore, SingleFileMessagePackBackingStore
__all__ = [
"BackingStore",
"CultCache",
"CultCacheBuilder",
"CultCacheEnvelope",
"DatabaseEntryField",
"DocumentDefinition",
"JsonLinesBackingStore",
"SingleFileMessagePackBackingStore",
"database_entry_field",
"define_database_entry_type",
"define_document_registry",
"define_document_type",
]

View file

@ -0,0 +1,44 @@
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Protocol
@dataclass(frozen=True)
class CultCacheEnvelope:
key: str
type: str
payload: bytes
stored_at: str
@classmethod
def create(cls, *, key: str, type: str, payload: bytes) -> "CultCacheEnvelope":
return cls(
key=key,
type=type,
payload=payload,
stored_at=datetime.now(timezone.utc).isoformat(),
)
class BackingStore(Protocol):
def pull_all(self) -> list[CultCacheEnvelope]:
...
def push(self, envelope: CultCacheEnvelope) -> None:
...
def delete(self, type: str, key: str) -> None:
...
def push_all(self, envelopes: list[CultCacheEnvelope]) -> None:
existing = {
(envelope.type, envelope.key): envelope for envelope in self.pull_all()
}
for envelope in envelopes:
existing[(envelope.type, envelope.key)] = envelope
self._replace_all(list(existing.values()))
def _replace_all(self, envelopes: list[CultCacheEnvelope]) -> None:
...

View file

@ -0,0 +1,235 @@
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Generic, TypeVar
from .backing_store import BackingStore, CultCacheEnvelope
from .documents import DocumentDefinition, extract_value
T = TypeVar("T")
GLOBAL_KEY = "__global__"
class CultCacheError(RuntimeError):
pass
@dataclass
class _State:
documents: dict[str, DocumentDefinition[Any]] = field(default_factory=dict)
values: dict[tuple[str, str], Any] = field(default_factory=dict)
stores_by_type: dict[str, list[BackingStore]] = field(default_factory=dict)
generic_stores: list[BackingStore] = field(default_factory=list)
name_extractors: dict[str, str | Any] = field(default_factory=dict)
index_extractors: dict[str, dict[str, str | Any]] = field(default_factory=dict)
names: dict[tuple[str, str], str] = field(default_factory=dict)
indexes: dict[tuple[str, str, str], str] = field(default_factory=dict)
class CultCacheBuilder:
def __init__(self) -> None:
self._cache = CultCache()
def register_document_type(self, document: DocumentDefinition[Any]) -> "CultCacheBuilder":
self._cache.register_document_type(document)
return self
def register_registry(self, documents: list[DocumentDefinition[Any]] | tuple[DocumentDefinition[Any], ...]) -> "CultCacheBuilder":
self._cache.register_registry(documents)
return self
def register_name_lookup(self, document: DocumentDefinition[Any], extractor: str | Any) -> "CultCacheBuilder":
self._cache.register_name_lookup(document, extractor)
return self
def register_index(self, document: DocumentDefinition[Any], index: str, extractor: str | Any) -> "CultCacheBuilder":
self._cache.register_index(document, index, extractor)
return self
def add_backing_store(self, store: BackingStore, types: list[str] | tuple[str, ...] | set[str]) -> "CultCacheBuilder":
self._cache.add_backing_store(store, types)
return self
def add_generic_store(self, store: BackingStore) -> "CultCacheBuilder":
self._cache.add_generic_store(store)
return self
def build(self) -> "CultCache":
return self._cache
class CultCache:
GLOBAL_KEY = GLOBAL_KEY
@classmethod
def builder(cls) -> CultCacheBuilder:
return CultCacheBuilder()
def __init__(self) -> None:
self._state = _State()
def register_document_type(self, document: DocumentDefinition[Any]) -> None:
if document.type in self._state.documents:
raise CultCacheError(f"Document type already registered: {document.type}")
self._state.documents[document.type] = document
if document.name is not None:
self.register_name_lookup(document, document.name)
for index, extractor in document.indexes.items():
self.register_index(document, index, extractor)
def register_registry(self, documents: list[DocumentDefinition[Any]] | tuple[DocumentDefinition[Any], ...]) -> None:
for document in documents:
self.register_document_type(document)
def register_name_lookup(self, document: DocumentDefinition[Any], extractor: str | Any) -> None:
self._assert_registered(document)
self._state.name_extractors[document.type] = extractor
self._rebuild_indexes()
def register_index(self, document: DocumentDefinition[Any], index: str, extractor: str | Any) -> None:
self._assert_registered(document)
self._state.index_extractors.setdefault(document.type, {})[index] = extractor
self._rebuild_indexes()
def add_backing_store(self, store: BackingStore, types: list[str] | tuple[str, ...] | set[str]) -> None:
for type in types:
self._state.stores_by_type.setdefault(type, []).append(store)
def add_generic_store(self, store: BackingStore) -> None:
self._state.generic_stores.append(store)
def pull_all_backing_stores(self) -> None:
self._state.values.clear()
seen_globals: set[str] = set()
for store in [*self._all_specific_stores(), *self._state.generic_stores]:
for envelope in store.pull_all():
document = self._state.documents.get(envelope.type)
if document is None:
raise CultCacheError(f"Unknown persisted document type: {envelope.type}")
if document.global_document:
if envelope.type in seen_globals and envelope.key == GLOBAL_KEY:
raise CultCacheError(f"Duplicate global document for type: {envelope.type}")
seen_globals.add(envelope.type)
value = document.decode_payload(envelope.payload)
self._state.values[(envelope.type, envelope.key)] = value
self._rebuild_indexes()
def get(self, document: DocumentDefinition[T], key: str) -> T | None:
self._assert_registered(document)
return self._state.values.get((document.type, key))
def get_required(self, document: DocumentDefinition[T], key: str) -> T:
value = self.get(document, key)
if value is None:
raise CultCacheError(f"Missing {document.type}:{key}")
return value
def get_all(self, document: DocumentDefinition[T]) -> list[T]:
self._assert_registered(document)
return [value for (type, _), value in self._state.values.items() if type == document.type]
def get_global(self, document: DocumentDefinition[T]) -> T | None:
self._assert_global(document)
return self.get(document, GLOBAL_KEY)
def get_required_global(self, document: DocumentDefinition[T]) -> T:
self._assert_global(document)
return self.get_required(document, GLOBAL_KEY)
def get_key_by_name(self, document: DocumentDefinition[Any], name: str) -> str | None:
self._assert_registered(document)
return self._state.names.get((document.type, name))
def get_by_name(self, document: DocumentDefinition[T], name: str) -> T | None:
key = self.get_key_by_name(document, name)
return None if key is None else self.get(document, key)
def get_key_by_index(self, document: DocumentDefinition[Any], index: str, value: str) -> str | None:
self._assert_registered(document)
return self._state.indexes.get((document.type, index, value))
def get_by_index(self, document: DocumentDefinition[T], index: str, value: str) -> T | None:
key = self.get_key_by_index(document, index, value)
return None if key is None else self.get(document, key)
def put(self, document: DocumentDefinition[T], key: str, value: T) -> None:
self._assert_registered(document)
if document.global_document and key != GLOBAL_KEY:
raise CultCacheError(f"Global document {document.type} must use key {GLOBAL_KEY}")
envelope = CultCacheEnvelope.create(key=key, type=document.type, payload=document.encode_payload(value))
stores = self._stores_for_type(document.type)
if not stores:
raise CultCacheError(f"No backing store registered for {document.type}")
for store in stores:
store.push(envelope)
self._state.values[(document.type, key)] = value
self._rebuild_indexes()
def put_global(self, document: DocumentDefinition[T], value: T) -> None:
self._assert_global(document)
self.put(document, GLOBAL_KEY, value)
def update(self, document: DocumentDefinition[T], key: str, updater: Any) -> T:
current = self.get_required(document, key)
updated = updater(current)
self.put(document, key, updated)
return updated
def update_global(self, document: DocumentDefinition[T], updater: Any) -> T:
self._assert_global(document)
return self.update(document, GLOBAL_KEY, updater)
def delete(self, document: DocumentDefinition[Any], key: str) -> None:
self._assert_registered(document)
for store in self._stores_for_type(document.type):
store.delete(document.type, key)
self._state.values.pop((document.type, key), None)
self._rebuild_indexes()
def delete_global(self, document: DocumentDefinition[Any]) -> None:
self._assert_global(document)
self.delete(document, GLOBAL_KEY)
def snapshot(self) -> dict[str, dict[str, Any]]:
out: dict[str, dict[str, Any]] = {}
for (type, key), value in self._state.values.items():
out.setdefault(type, {})[key] = value
return out
def _stores_for_type(self, type: str) -> list[BackingStore]:
specific = self._state.stores_by_type.get(type)
return specific if specific else self._state.generic_stores
def _all_specific_stores(self) -> list[BackingStore]:
stores: list[BackingStore] = []
seen: set[int] = set()
for routed in self._state.stores_by_type.values():
for store in routed:
marker = id(store)
if marker not in seen:
stores.append(store)
seen.add(marker)
return stores
def _rebuild_indexes(self) -> None:
self._state.names.clear()
self._state.indexes.clear()
for (type, key), value in self._state.values.items():
name_extractor = self._state.name_extractors.get(type)
if name_extractor is not None:
name = extract_value(value, name_extractor)
if name is not None:
self._state.names[(type, str(name))] = key
for index, extractor in self._state.index_extractors.get(type, {}).items():
index_value = extract_value(value, extractor)
if index_value is not None:
self._state.indexes[(type, index, str(index_value))] = key
def _assert_registered(self, document: DocumentDefinition[Any]) -> None:
if self._state.documents.get(document.type) is not document:
raise CultCacheError(f"Document type is not registered on this cache: {document.type}")
def _assert_global(self, document: DocumentDefinition[Any]) -> None:
self._assert_registered(document)
if not document.global_document:
raise CultCacheError(f"Document type is not global: {document.type}")

View file

@ -0,0 +1,207 @@
from __future__ import annotations
import json
from dataclasses import MISSING, dataclass, field
from typing import Any, Callable, Generic, Iterable, TypeVar
T = TypeVar("T")
Encoder = Callable[[T], Any]
Decoder = Callable[[Any], T]
Validator = Callable[[T], None]
Extractor = Callable[[T], str | int | float | bool | None]
def _default_encode(value: Any) -> Any:
if hasattr(value, "model_dump"):
return value.model_dump()
if hasattr(value, "to_dict"):
return value.to_dict()
if hasattr(value, "__dict__"):
return dict(value.__dict__)
return value
def _default_decode(value: Any) -> Any:
return value
def _json_payload_encoder(value: Any) -> bytes:
return json.dumps(value, ensure_ascii=False, sort_keys=True).encode("utf-8")
def _json_payload_decoder(payload: bytes) -> Any:
return json.loads(payload.decode("utf-8"))
def _messagepack_payload_encoder(value: Any) -> bytes:
try:
import msgpack # type: ignore
except ModuleNotFoundError as exc:
raise RuntimeError(
"MessagePack payload encoding requires the optional 'msgpack' dependency. "
"Install with: python -m pip install cultcache-py[msgpack]"
) from exc
return msgpack.packb(value, use_bin_type=True)
def _messagepack_payload_decoder(payload: bytes) -> Any:
try:
import msgpack # type: ignore
except ModuleNotFoundError as exc:
raise RuntimeError(
"MessagePack payload decoding requires the optional 'msgpack' dependency. "
"Install with: python -m pip install cultcache-py[msgpack]"
) from exc
return msgpack.unpackb(payload, raw=False)
@dataclass(frozen=True)
class DatabaseEntryField:
name: str
key: int
default: Any = MISSING
def database_entry_field(name: str, key: int, *, default: Any = MISSING) -> DatabaseEntryField:
if key < 0:
raise ValueError("DatabaseEntry field keys must be non-negative integers")
return DatabaseEntryField(name=name, key=key, default=default)
@dataclass(frozen=True)
class DocumentDefinition(Generic[T]):
type: str
encode: Encoder[T] = _default_encode
decode: Decoder[T] = _default_decode
validate: Validator[T] | None = None
global_document: bool = False
name: str | Extractor[T] | None = None
indexes: dict[str, str | Extractor[T]] = field(default_factory=dict)
payload_encoder: Callable[[Any], bytes] = _json_payload_encoder
payload_decoder: Callable[[bytes], Any] = _json_payload_decoder
def encode_payload(self, value: T) -> bytes:
if self.validate:
self.validate(value)
return self.payload_encoder(self.encode(value))
def decode_payload(self, payload: bytes) -> T:
value = self.decode(self.payload_decoder(payload))
if self.validate:
self.validate(value)
return value
def define_document_type(
type: str,
*,
encode: Encoder[T] = _default_encode,
decode: Decoder[T] = _default_decode,
validate: Validator[T] | None = None,
global_document: bool = False,
name: str | Extractor[T] | None = None,
indexes: dict[str, str | Extractor[T]] | None = None,
payload_encoder: Callable[[Any], bytes] = _json_payload_encoder,
payload_decoder: Callable[[bytes], Any] = _json_payload_decoder,
) -> DocumentDefinition[T]:
return DocumentDefinition(
type=type,
encode=encode,
decode=decode,
validate=validate,
global_document=global_document,
name=name,
indexes=indexes or {},
payload_encoder=payload_encoder,
payload_decoder=payload_decoder,
)
def define_database_entry_type(
type: str,
fields: Iterable[DatabaseEntryField | tuple[str, int] | tuple[str, int, Any]],
*,
cls: type[T] | None = None,
validate: Validator[T] | None = None,
global_document: bool = False,
name: str | Extractor[T] | None = None,
indexes: dict[str, str | Extractor[T]] | None = None,
) -> DocumentDefinition[T]:
"""Define a Rust/C#-style DatabaseEntry payload formatter.
Payloads are MessagePack arrays indexed by explicit field keys. Missing
slots are written as nil, so deleted fields can leave their slot reserved
and newly added fields can use higher keys without rewriting older payloads.
"""
normalized = [_normalize_database_entry_field(field) for field in fields]
if not normalized:
raise ValueError("DatabaseEntry document types require at least one field")
keys = [field.key for field in normalized]
if len(keys) != len(set(keys)):
raise ValueError(f"DatabaseEntry document type {type!r} has duplicate field keys")
normalized.sort(key=lambda field: field.key)
max_key = max(keys)
def encode(value: Any) -> list[Any]:
slots = [None] * (max_key + 1)
for field in normalized:
slots[field.key] = extract_value(value, field.name)
return slots
def decode(raw: Any) -> Any:
if not isinstance(raw, list):
raise ValueError(f"DatabaseEntry document type {type!r} expected a MessagePack array")
values: dict[str, Any] = {}
for field in normalized:
if field.key < len(raw):
value = raw[field.key]
elif field.default is not MISSING:
value = field.default() if callable(field.default) else field.default
else:
raise ValueError(
f"DatabaseEntry document type {type!r} is missing required slot {field.key}"
)
if value is None and field.default is not MISSING:
value = field.default() if callable(field.default) else field.default
values[field.name] = value
if cls is None:
return values
return cls(**values)
return define_document_type(
type,
encode=encode,
decode=decode,
validate=validate,
global_document=global_document,
name=name,
indexes=indexes,
payload_encoder=_messagepack_payload_encoder,
payload_decoder=_messagepack_payload_decoder,
)
def define_document_registry(*documents: DocumentDefinition[Any]) -> tuple[DocumentDefinition[Any], ...]:
return tuple(documents)
def extract_value(value: Any, extractor: str | Extractor[Any]) -> str | int | float | bool | None:
if callable(extractor):
return extractor(value)
if isinstance(value, dict):
return value.get(extractor)
return getattr(value, extractor, None)
def _normalize_database_entry_field(
field: DatabaseEntryField | tuple[str, int] | tuple[str, int, Any],
) -> DatabaseEntryField:
if isinstance(field, DatabaseEntryField):
return field
if len(field) == 2:
return database_entry_field(field[0], field[1])
if len(field) == 3:
return database_entry_field(field[0], field[1], default=field[2])
raise ValueError("DatabaseEntry field tuples must be (name, key) or (name, key, default)")

View file

@ -0,0 +1,138 @@
from __future__ import annotations
import base64
import json
import os
import threading
from pathlib import Path
from typing import Any
from .backing_store import CultCacheEnvelope
class JsonLinesBackingStore:
def __init__(self, path: str | os.PathLike[str]) -> None:
self.path = Path(path)
self._lock = threading.RLock()
def pull_all(self) -> list[CultCacheEnvelope]:
with self._lock:
if not self.path.exists():
return []
envelopes: list[CultCacheEnvelope] = []
for line_number, line in enumerate(self.path.read_text(encoding="utf-8").splitlines(), start=1):
if not line.strip():
continue
raw = json.loads(line)
try:
payload = base64.b64decode(raw["payload"])
envelopes.append(
CultCacheEnvelope(
key=raw["key"],
type=raw["type"],
payload=payload,
stored_at=raw.get("stored_at", raw.get("storedAt")),
)
)
except KeyError as exc:
raise ValueError(f"Malformed CultCache JSONL envelope at {self.path}:{line_number}: missing {exc}") from exc
return envelopes
def push(self, envelope: CultCacheEnvelope) -> None:
with self._lock:
existing = {(item.type, item.key): item for item in self.pull_all()}
existing[(envelope.type, envelope.key)] = envelope
self._replace_all(list(existing.values()))
def push_all(self, envelopes: list[CultCacheEnvelope]) -> None:
with self._lock:
existing = {(item.type, item.key): item for item in self.pull_all()}
for envelope in envelopes:
existing[(envelope.type, envelope.key)] = envelope
self._replace_all(list(existing.values()))
def delete(self, type: str, key: str) -> None:
with self._lock:
existing = [item for item in self.pull_all() if not (item.type == type and item.key == key)]
self._replace_all(existing)
def _replace_all(self, envelopes: list[CultCacheEnvelope]) -> None:
self.path.parent.mkdir(parents=True, exist_ok=True)
temp = self.path.with_suffix(self.path.suffix + ".tmp")
lines = []
for envelope in sorted(envelopes, key=lambda item: (item.type, item.key)):
lines.append(json.dumps({
"key": envelope.key,
"type": envelope.type,
"payload": base64.b64encode(envelope.payload).decode("ascii"),
"stored_at": envelope.stored_at,
}, ensure_ascii=False, sort_keys=True))
temp.write_text("\n".join(lines) + ("\n" if lines else ""), encoding="utf-8")
temp.replace(self.path)
class SingleFileMessagePackBackingStore:
def __init__(self, path: str | os.PathLike[str]) -> None:
self.path = Path(path)
self._lock = threading.RLock()
def pull_all(self) -> list[CultCacheEnvelope]:
msgpack = self._msgpack()
with self._lock:
if not self.path.exists():
return []
raw_items = msgpack.unpackb(self.path.read_bytes(), raw=False)
return [
CultCacheEnvelope(
key=item["key"],
type=item["type"],
payload=item["payload"],
stored_at=item.get("storedAt", item.get("stored_at")),
)
for item in raw_items
]
def push(self, envelope: CultCacheEnvelope) -> None:
with self._lock:
existing = {(item.type, item.key): item for item in self.pull_all()}
existing[(envelope.type, envelope.key)] = envelope
self._replace_all(list(existing.values()))
def push_all(self, envelopes: list[CultCacheEnvelope]) -> None:
with self._lock:
existing = {(item.type, item.key): item for item in self.pull_all()}
for envelope in envelopes:
existing[(envelope.type, envelope.key)] = envelope
self._replace_all(list(existing.values()))
def delete(self, type: str, key: str) -> None:
with self._lock:
existing = [item for item in self.pull_all() if not (item.type == type and item.key == key)]
self._replace_all(existing)
def _replace_all(self, envelopes: list[CultCacheEnvelope]) -> None:
msgpack = self._msgpack()
self.path.parent.mkdir(parents=True, exist_ok=True)
temp = self.path.with_suffix(self.path.suffix + ".tmp")
raw_items: list[dict[str, Any]] = [
{
"key": envelope.key,
"type": envelope.type,
"payload": envelope.payload,
"storedAt": envelope.stored_at,
}
for envelope in sorted(envelopes, key=lambda item: (item.type, item.key))
]
temp.write_bytes(msgpack.packb(raw_items, use_bin_type=True))
temp.replace(self.path)
@staticmethod
def _msgpack() -> Any:
try:
import msgpack # type: ignore
except ModuleNotFoundError as exc:
raise RuntimeError(
"SingleFileMessagePackBackingStore requires the optional 'msgpack' dependency. "
"Install with: python -m pip install cultcache-py[msgpack]"
) from exc
return msgpack

View file

@ -0,0 +1,137 @@
from __future__ import annotations
import tempfile
import unittest
from dataclasses import asdict, dataclass
from pathlib import Path
from cultcache_py import (
CultCache,
JsonLinesBackingStore,
SingleFileMessagePackBackingStore,
define_database_entry_type,
define_document_type,
)
@dataclass
class Item:
name: str
category: str
value: int
def item_doc():
return define_document_type(
"item",
encode=lambda item: asdict(item),
decode=lambda raw: Item(**raw),
name="name",
indexes={"category": "category"},
)
class CultCacheTests(unittest.TestCase):
def test_round_trips_registered_documents(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
document = item_doc()
cache = (
CultCache.builder()
.register_document_type(document)
.add_generic_store(JsonLinesBackingStore(Path(tmp) / "cache.jsonl"))
.build()
)
cache.pull_all_backing_stores()
cache.put(document, "item:potion", Item(name="Potion", category="Consumable", value=50))
loaded = (
CultCache.builder()
.register_document_type(document)
.add_generic_store(JsonLinesBackingStore(Path(tmp) / "cache.jsonl"))
.build()
)
loaded.pull_all_backing_stores()
self.assertEqual(loaded.get_required(document, "item:potion").value, 50)
self.assertEqual(loaded.get_key_by_name(document, "Potion"), "item:potion")
self.assertEqual(loaded.get_by_index(document, "category", "Consumable").name, "Potion")
def test_global_document_uses_singleton_key(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
settings = define_document_type("settings", global_document=True)
cache = (
CultCache.builder()
.register_document_type(settings)
.add_generic_store(JsonLinesBackingStore(Path(tmp) / "cache.jsonl"))
.build()
)
cache.pull_all_backing_stores()
cache.put_global(settings, {"theme": "ash"})
self.assertEqual(cache.get_required_global(settings)["theme"], "ash")
def test_update_and_delete(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
document = item_doc()
cache = (
CultCache.builder()
.register_document_type(document)
.add_generic_store(JsonLinesBackingStore(Path(tmp) / "cache.jsonl"))
.build()
)
cache.pull_all_backing_stores()
cache.put(document, "item:potion", Item(name="Potion", category="Consumable", value=50))
cache.update(document, "item:potion", lambda item: Item(item.name, item.category, item.value + 5))
self.assertEqual(cache.get_required(document, "item:potion").value, 55)
cache.delete(document, "item:potion")
self.assertIsNone(cache.get(document, "item:potion"))
def test_database_entry_formatter_uses_slot_indexed_messagepack_array(self) -> None:
try:
import msgpack # type: ignore
except ModuleNotFoundError:
self.skipTest("msgpack optional dependency is not installed")
@dataclass
class Settings:
theme: str
retries: int = 0
document = define_database_entry_type(
"settings",
[
("theme", 0),
("retries", 2, 0),
],
cls=Settings,
)
payload = document.encode_payload(Settings(theme="ash", retries=3))
self.assertEqual(msgpack.unpackb(payload, raw=False), ["ash", None, 3])
self.assertEqual(document.decode_payload(msgpack.packb(["ash"], use_bin_type=True)).retries, 0)
def test_messagepack_store_writes_camel_case_envelope(self) -> None:
try:
import msgpack # type: ignore
except ModuleNotFoundError:
self.skipTest("msgpack optional dependency is not installed")
with tempfile.TemporaryDirectory() as tmp:
document = define_database_entry_type("settings", [("theme", 0)])
store_path = Path(tmp) / "cache.msgpack"
cache = (
CultCache.builder()
.register_document_type(document)
.add_generic_store(SingleFileMessagePackBackingStore(store_path))
.build()
)
cache.pull_all_backing_stores()
cache.put(document, "app", {"theme": "ash"})
raw = msgpack.unpackb(store_path.read_bytes(), raw=False)
self.assertEqual(raw[0]["type"], "settings")
self.assertIn("storedAt", raw[0])
self.assertNotIn("stored_at", raw[0])
if __name__ == "__main__":
unittest.main()