"""Keep a copy of the SQLite database somewhere durable (the cloud site's Volume). The cloud container's own disk is wiped whenever it stops, and the Volume can't hold a live SQLite database (no file locks). So the database lives on the container disk, is copied to the Volume after each change (a few seconds' delay) and when the container stops, and is copied back when the next container starts. """ from __future__ import annotations import logging import os import shutil import sqlite3 import threading from pathlib import Path log = logging.getLogger(__name__) Signature = tuple[tuple[int, int], ...] class DbSnapshots: def __init__(self, local: Path, snapshot: Path) -> None: self.local, self.snapshot = local, snapshot self._last: Signature | None = None self._lock = threading.Lock() def restore(self) -> bool: """Copy the snapshot to the local path when there is no local database yet. True if it did.""" self.local.parent.mkdir(parents=True, exist_ok=True) restored = self.snapshot.exists() and not self.local.exists() if restored: shutil.copyfile(self.snapshot, self.local) log.info("restored the database from %s", self.snapshot) self._last = self._signature() return restored def _signature(self) -> Signature: files = (self.local, self.local.with_name(self.local.name + "-wal")) return tuple((p.stat().st_mtime_ns, p.stat().st_size) for p in files if p.exists()) def save(self) -> bool: """Write a consistent copy of the database to the snapshot path if it changed. True if it did.""" with self._lock: signature = self._signature() if not self.local.exists() or signature == self._last: return False self.snapshot.parent.mkdir(parents=True, exist_ok=True) tmp = self.snapshot.with_name(self.snapshot.name + ".tmp") tmp.unlink(missing_ok=True) source, target = sqlite3.connect(self.local), sqlite3.connect(tmp) try: source.backup(target) # consistent even while the API or a worker is writing target.execute("PRAGMA journal_mode=DELETE") # one self-contained file, no -wal next to it finally: source.close() target.close() os.replace(tmp, self.snapshot) self._last = signature return True