Recover schema-stamped cache records across runtimes
This commit is contained in:
parent
c911eb561d
commit
a0b31b8f2a
11 changed files with 773 additions and 25 deletions
|
|
@ -17,6 +17,7 @@ class CultCacheError(RuntimeError):
|
|||
@dataclass
|
||||
class _State:
|
||||
documents: dict[str, DocumentDefinition[Any]] = field(default_factory=dict)
|
||||
documents_by_schema_name: dict[str, DocumentDefinition[Any]] = field(default_factory=dict)
|
||||
values: dict[str, dict[str, Any]] = field(default_factory=dict)
|
||||
envelopes: dict[str, dict[str, CultCacheEnvelope]] = field(default_factory=dict)
|
||||
stores_by_type: dict[str, list[BackingStore]] = field(default_factory=dict)
|
||||
|
|
@ -72,7 +73,11 @@ class CultCache:
|
|||
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}")
|
||||
schema_name = document.catalog_entry().schema_name
|
||||
if schema_name in self._state.documents_by_schema_name:
|
||||
raise CultCacheError(f"Document schema name already registered: {schema_name}")
|
||||
self._state.documents[document.type] = document
|
||||
self._state.documents_by_schema_name[schema_name] = document
|
||||
if document.name is not None:
|
||||
self.register_name_lookup(document, document.name)
|
||||
for index, extractor in document.indexes.items():
|
||||
|
|
@ -105,9 +110,18 @@ class CultCache:
|
|||
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)
|
||||
document = self._resolve_document_for_envelope(envelope)
|
||||
if document is None:
|
||||
raise CultCacheError(f"Unknown persisted document type: {envelope.type}")
|
||||
if envelope.type != document.type:
|
||||
envelope = CultCacheEnvelope(
|
||||
key=envelope.key,
|
||||
type=document.type,
|
||||
payload=envelope.payload,
|
||||
stored_at=envelope.stored_at,
|
||||
schema_id=envelope.schema_id,
|
||||
catalog_entry=envelope.catalog_entry,
|
||||
)
|
||||
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}")
|
||||
|
|
@ -361,3 +375,9 @@ class CultCache:
|
|||
self._assert_registered(document)
|
||||
if not document.global_document:
|
||||
raise CultCacheError(f"Document type is not global: {document.type}")
|
||||
|
||||
def _resolve_document_for_envelope(self, envelope: CultCacheEnvelope) -> DocumentDefinition[Any] | None:
|
||||
document = self._state.documents.get(envelope.type)
|
||||
if document is not None:
|
||||
return document
|
||||
return self._state.documents_by_schema_name.get(envelope.type)
|
||||
|
|
|
|||
|
|
@ -178,12 +178,25 @@ def _decode_v1_snapshot(decoded: Any) -> list[CultCacheEnvelope] | None:
|
|||
raise ValueError("CultCache persisted records must declare storedAt")
|
||||
catalog_entry = catalog_by_schema_id.get(schema_id)
|
||||
if catalog_entry is None:
|
||||
raise ValueError(f'CultCache persisted record "{key}" references missing schema id "{schema_id}"')
|
||||
schema_version = _infer_schema_version_from_payload(_normalize_payload(payload))
|
||||
schema_name = _infer_schema_name(schema_version) if schema_version is not None else None
|
||||
if schema_name is None:
|
||||
raise ValueError(f'CultCache persisted record "{key}" references missing schema id "{schema_id}"')
|
||||
catalog_entry = CultCacheSchemaCatalogEntry(
|
||||
schema_id=schema_id,
|
||||
schema_name=schema_name,
|
||||
schema_version=schema_version,
|
||||
content_hash=schema_id,
|
||||
canonical_schema_json="",
|
||||
compatible_schema_ids=(),
|
||||
members=(),
|
||||
)
|
||||
normalized_payload = _normalize_payload(payload)
|
||||
envelopes.append(
|
||||
CultCacheEnvelope(
|
||||
key=key,
|
||||
type=catalog_entry.schema_name,
|
||||
payload=_normalize_payload(payload),
|
||||
payload=normalized_payload,
|
||||
stored_at=stored_at,
|
||||
schema_id=schema_id,
|
||||
catalog_entry=catalog_entry,
|
||||
|
|
@ -316,3 +329,27 @@ def _normalize_payload(payload: Any) -> bytes:
|
|||
if isinstance(payload, list) and all(isinstance(item, int) and 0 <= item <= 255 for item in payload):
|
||||
return bytes(payload)
|
||||
raise ValueError("CultCache record payload must be binary MessagePack bytes")
|
||||
|
||||
|
||||
def _infer_schema_version_from_payload(payload: bytes) -> str | None:
|
||||
try:
|
||||
msgpack = SingleFileMessagePackBackingStore._msgpack()
|
||||
decoded = msgpack.unpackb(payload, raw=False)
|
||||
except Exception:
|
||||
return None
|
||||
if isinstance(decoded, list) and decoded and isinstance(decoded[0], str):
|
||||
return decoded[0]
|
||||
if isinstance(decoded, dict):
|
||||
value = decoded.get("schemaVersion", decoded.get("schema_version"))
|
||||
return value if isinstance(value, str) else None
|
||||
return None
|
||||
|
||||
|
||||
def _infer_schema_name(schema_version: str) -> str | None:
|
||||
marker = schema_version.rfind(".v")
|
||||
if marker <= 0:
|
||||
return None
|
||||
version = schema_version[marker + 2:]
|
||||
if not version or not version.isdigit():
|
||||
return None
|
||||
return schema_version[:marker]
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ def schema_document_map(documents: Iterable[DocumentDefinition[Any]]) -> dict[st
|
|||
for document in documents:
|
||||
catalog_entry = document.catalog_entry()
|
||||
mapped[catalog_entry.schema_id] = document
|
||||
mapped[catalog_entry.schema_name] = document
|
||||
for compatible_schema_id in catalog_entry.compatible_schema_ids:
|
||||
mapped[compatible_schema_id] = document
|
||||
return mapped
|
||||
|
|
@ -35,7 +36,7 @@ def apply_raw_document_record(
|
|||
) -> CultNetAppliedRecord:
|
||||
wire = record.to_wire() if isinstance(record, CultNetRawDocumentRecord) else record
|
||||
schema_id = str(wire["schemaId"])
|
||||
document = documents_by_schema_id[schema_id]
|
||||
document = resolve_document_for_raw_record(documents_by_schema_id, schema_id, wire)
|
||||
envelope = raw_record_to_envelope(document, schema_id, wire)
|
||||
value = cache.put_envelope(document, envelope)
|
||||
return CultNetAppliedRecord(
|
||||
|
|
@ -76,7 +77,7 @@ def apply_raw_snapshot(
|
|||
if not isinstance(record, dict):
|
||||
continue
|
||||
schema_id = str(record["schemaId"])
|
||||
document = documents_by_schema_id[schema_id]
|
||||
document = resolve_document_for_raw_record(documents_by_schema_id, schema_id, record)
|
||||
envelope = raw_record_to_envelope(document, schema_id, record)
|
||||
batch = batches.setdefault(document.type, (document, []))
|
||||
batch[1].append((schema_id, envelope))
|
||||
|
|
@ -120,7 +121,7 @@ def apply_shard_log_response(
|
|||
if change_kind in ("added", "updated") and isinstance(entry.get("put"), dict):
|
||||
put = entry["put"]
|
||||
schema_id = str(put["document"]["schemaId"])
|
||||
if schema_id not in documents_by_schema_id:
|
||||
if not can_resolve_document_for_raw_record(documents_by_schema_id, schema_id, put["document"]):
|
||||
continue
|
||||
result = apply_raw_document_record(cache, documents_by_schema_id, put["document"])
|
||||
applied.append(CultNetAppliedRecord(result.schema_id, result.record_key, str(change_kind), result.value))
|
||||
|
|
@ -134,3 +135,54 @@ def apply_shard_log_response(
|
|||
cache.delete(document, record_key)
|
||||
applied.append(CultNetAppliedRecord(schema_id, record_key, "removed", None))
|
||||
return applied
|
||||
|
||||
|
||||
def can_resolve_document_for_raw_record(
|
||||
documents_by_schema_id: dict[str, DocumentDefinition[Any]],
|
||||
schema_id: str,
|
||||
record: dict[str, Any],
|
||||
) -> bool:
|
||||
try:
|
||||
resolve_document_for_raw_record(documents_by_schema_id, schema_id, record)
|
||||
return True
|
||||
except KeyError:
|
||||
return False
|
||||
|
||||
|
||||
def resolve_document_for_raw_record(
|
||||
documents_by_schema_id: dict[str, DocumentDefinition[Any]],
|
||||
schema_id: str,
|
||||
record: dict[str, Any],
|
||||
) -> DocumentDefinition[Any]:
|
||||
document = documents_by_schema_id.get(schema_id)
|
||||
if document is not None:
|
||||
return document
|
||||
schema_version = _infer_schema_version_from_payload(bytes(record["payload"]))
|
||||
schema_name = _infer_schema_name(schema_version) if schema_version is not None else None
|
||||
if schema_name is not None and schema_name in documents_by_schema_id:
|
||||
return documents_by_schema_id[schema_name]
|
||||
raise KeyError(schema_id)
|
||||
|
||||
|
||||
def _infer_schema_version_from_payload(payload: bytes) -> str | None:
|
||||
try:
|
||||
import msgpack # type: ignore
|
||||
decoded = msgpack.unpackb(payload, raw=False)
|
||||
except Exception:
|
||||
return None
|
||||
if isinstance(decoded, list) and decoded and isinstance(decoded[0], str):
|
||||
return decoded[0]
|
||||
if isinstance(decoded, dict):
|
||||
value = decoded.get("schemaVersion", decoded.get("schema_version"))
|
||||
return value if isinstance(value, str) else None
|
||||
return None
|
||||
|
||||
|
||||
def _infer_schema_name(schema_version: str) -> str | None:
|
||||
marker = schema_version.rfind(".v")
|
||||
if marker <= 0:
|
||||
return None
|
||||
version = schema_version[marker + 2:]
|
||||
if not version or not version.isdigit():
|
||||
return None
|
||||
return schema_version[:marker]
|
||||
|
|
|
|||
Loading…
Reference in a new issue