mirror of
https://github.com/kuhyx/utils.git
synced 2026-11-10 21:27:14 +01:00
crdt_sync_dart: new domain-agnostic LogStore -- an in-memory Log with a reactive changes stream and upsert/delete(sticky tombstone)/replaceAll, behind an injectable LogPersistence port -- plus logToJson/logFromJson. FileLogPersistence (atomic temp-file-then-rename, generalizing diet_guard's LogStorageService) lives behind a separate crdt_sync_io.dart entrypoint so the core barrel stays pure Dart / web-safe. crdt-sync (Python): mirror dump_log/load_log/read_log/write_log sharing the same on-disk JSON format so a log written on one side parses on the other. Load/save only -- the reactive store is a Dart/Flutter convenience with no Python equivalent by design (Python consumers are headless sync ticks). Querying stays app-side: a Record's fields are opaque to the library, so filtering/sorting/search is the caller's job over LogStore.values. Both packages bumped to 0.2.0. 83 Dart tests + 71 Python tests (100% branch coverage) green. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019KwUCPESvE5CjCtmUFz8xQ
71 lines
2.4 KiB
Python
71 lines
2.4 KiB
Python
"""Local JSON persistence for a ``Log``.
|
|
|
|
Mirrors ``crdt_sync_dart``'s ``logToJson``/``FileLogPersistence`` serialization
|
|
so a log written by the Dart side parses here and vice versa. Deliberately
|
|
*non-reactive*: the change-stream/reactive store is a Dart/Flutter-only
|
|
convenience (it exists to drive a live UI). On the Python side, where consumers
|
|
are headless sync ticks, this is plain load and (atomic) save.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
from typing import TYPE_CHECKING
|
|
|
|
from crdt_sync._record import Record
|
|
|
|
if TYPE_CHECKING:
|
|
from pathlib import Path
|
|
|
|
from crdt_sync._log import Log
|
|
|
|
|
|
def dump_log(log: Log) -> str:
|
|
"""Serialize ``log`` to canonical JSON text (id -> record dict)."""
|
|
return json.dumps({rid: record.to_dict() for rid, record in log.items()})
|
|
|
|
|
|
def load_log(text: str) -> Log:
|
|
"""Parse text produced by :func:`dump_log` back into a ``Log``.
|
|
|
|
Raises ``ValueError`` (bad JSON), ``KeyError`` or ``TypeError`` (valid
|
|
JSON, wrong shape) on a corrupt payload -- callers reading from disk go
|
|
through :func:`read_log`, which turns those into an empty log.
|
|
"""
|
|
raw = json.loads(text)
|
|
if not isinstance(raw, dict):
|
|
msg = f"expected a JSON object mapping id -> record, got {type(raw).__name__}"
|
|
raise TypeError(msg)
|
|
return {rid: Record.from_dict(value) for rid, value in raw.items()}
|
|
|
|
|
|
def read_log(path: Path) -> Log:
|
|
"""Read a ``Log`` from ``path``; empty on a missing or unparsable file.
|
|
|
|
A truncated or corrupt file can never raise here: it is treated as "no log
|
|
yet", matching the Dart store's defensive load so a half-written file can't
|
|
brick a consumer.
|
|
"""
|
|
try:
|
|
text = path.read_text(encoding="utf-8")
|
|
except FileNotFoundError:
|
|
return {}
|
|
try:
|
|
return load_log(text)
|
|
except (ValueError, KeyError, TypeError):
|
|
return {}
|
|
|
|
|
|
def write_log(path: Path, log: Log) -> None:
|
|
"""Write ``log`` to ``path`` atomically (temp file then rename).
|
|
|
|
Writes to a per-process temp file and ``replace``s it over the real path,
|
|
so a concurrent reader never observes a half-written file. Mirrors the
|
|
Dart ``FileLogPersistence`` write scheme.
|
|
"""
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
tmp = path.with_name(f"{path.name}.{os.getpid()}.tmp")
|
|
tmp.write_text(dump_log(log), encoding="utf-8")
|
|
tmp.replace(path)
|