utils/crdt-sync/crdt_sync/_store.py
Krzysztof kuhy Rudnicki 305e59b3e8
Some checks failed
crdt-sync pre-commit / pre-commit (push) Has been cancelled
crdt-sync tests / test (push) Has been cancelled
dependency freshness / dependencies on newest stable (push) Has been cancelled
file length / file-length (push) Has been cancelled
gatelock pre-commit / pre-commit (push) Has been cancelled
gatelock tests / test (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
palette drift / palette (push) Has been cancelled
shared gate tests / gate unit tests (push) Has been cancelled
Grade crdt-sync and gatelock against 3.14 too, not just run on them
Both libraries had already moved `requires-python` to 3.14, but ruff, mypy and
pylint were still grading against 3.10 -- three tools judging an interpreter
nothing runs any more, and ruff withholding the pyupgrade fixes that only
become safe at the newer target. `pin_ci_python.py` rewrites these three knobs.

What the stale target was hiding: `datetime.timezone.utc` where `datetime.UTC`
is now correct (UP017), a dead `timezone` import left behind by it, and ruff's
stable formatter applying PEP 758 -- `except (A, B):` becomes `except A, B:`.
That last one makes the source 3.14-only at the syntax level, which is what
`requires-python = ">=3.14"` already promised; kuhy chose it deliberately over
holding ruff a release back (2026-08-29).

These two are libraries the apps install, so the floor matters more here than
anywhere else in the fleet -- every consumer already pins >=3.14.

Per project: ruff, ruff-format, mypy --strict and pylint clean, crdt-sync 432
tests and gatelock 389 tests, both at 100% line and branch coverage.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SfnJmxxsZ534AKk16rC2Gr
2026-08-29 11:47:21 +02:00

71 lines
2.3 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)