"""Small JSON read/write helpers for the state files under DATA_DIR. Every file is written via a temp-file + os.replace so a crash mid-write never leaves a half-written JSON file behind for the next read. """ import json import os import threading DATA_DIR = os.environ.get("DATA_DIR", "/data") _lock = threading.Lock() def _path(name): return os.path.join(DATA_DIR, name) def load(name, default): path = _path(name) with _lock: if not os.path.exists(path): return default with open(path) as f: return json.load(f) def save(name, data): path = _path(name) with _lock: os.makedirs(DATA_DIR, exist_ok=True) tmp = path + ".tmp" with open(tmp, "w") as f: json.dump(data, f, indent=2) os.replace(tmp, path)