Fall back to disk when in-memory store is empty on client connect

storage_helpers: load_today_records() scans logs/ for all files
matching today's UTC date and VIN, merges and sorts their records.

network: _accept_loop receives an optional load_today callable;
if store_ref["current"] has no records it calls load_today() to
replay the day's history from disk before adding the client.

collect: passes a load_today lambda (None when -o is used).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-05-25 21:21:17 +02:00
co-authored by Claude Sonnet 4.6
parent b38f8d052e
commit 9d2d742368
3 changed files with 51 additions and 19 deletions
+17 -1
View File
@@ -32,4 +32,20 @@ def load_store(path: Path, vin: str, interval: int) -> dict:
def save_store(path: Path, store: dict, max_records: int | None) -> None:
if max_records and len(store["records"]) > max_records:
store["records"] = store["records"][-max_records:]
path.write_text(json.dumps(store, indent=2, default=str))
path.write_text(json.dumps(store, indent=2, default=str))
def load_today_records(logs_dir: Path, vin: str) -> list:
"""Load and merge all records from today's log files for this VIN."""
today_prefix = datetime.now(timezone.utc).strftime("%Y_%m_%d_")
records = []
for path in sorted(logs_dir.glob(f"{today_prefix}*_{vin}.json")):
try:
data = json.loads(path.read_text())
if isinstance(data, dict) and "records" in data:
records.extend(data["records"])
log.debug("Loaded %d records from %s", len(data["records"]), path.name)
except (json.JSONDecodeError, OSError):
log.warning("Could not load %s", path)
records.sort(key=lambda r: r.get("ts", ""))
return records