Files
we_monitor/server/storage_helpers.py
T
jensandClaude Sonnet 4.6 9d2d742368 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>
2026-05-25 21:21:17 +02:00

51 lines
1.8 KiB
Python

import json
import logging
from datetime import datetime, timezone
from pathlib import Path
log = logging.getLogger(__name__)
def auto_out_path(logs_dir: Path, vin: str) -> Path:
stamp = datetime.now(timezone.utc).strftime("%Y_%m_%d_%H_%M_%S")
return logs_dir / f"{stamp}_{vin}.json"
def load_store(path: Path, vin: str, interval: int) -> dict:
if path.exists():
try:
data = json.loads(path.read_text())
if isinstance(data, dict) and "records" in data:
return data
except json.JSONDecodeError:
log.warning("Output file is corrupt — starting fresh")
return {
"meta": {
"vin": vin,
"created_at": datetime.now(timezone.utc).isoformat(),
"interval_seconds": interval,
},
"records": [],
}
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))
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