Files
FabledGrimoire/src/grimoire/services/backup_file.py
T
bvandeusenandClaude Opus 5.5 0f5ef0be63
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / TypeScript typecheck (push) Successful in 56s
CI & Build / integration (push) Successful in 1m4s
CI & Build / Python tests (push) Successful in 1m55s
CI & Build / Build & push image (push) Successful in 44s
rename(547): the server is grimoire — package, image, DB defaults, backups
Step 2 of the Scribe -> Grimoire rename.

- src/scribe -> src/grimoire, and every import, patch target, module path,
  hypercorn entry point and `python -m grimoire.restore` with it; pyproject,
  uv.lock and the frontend package are named grimoire.
- Image git.fabledsword.com/bvandeusen/fabledgrimoire; CI's Postgres service
  runs as grimoire / grimoire_test.
- Compose files default the DB user, database and (prod) volume to grimoire,
  each overridable from .env, so an install created as Scribe keeps its data
  by setting POSTGRES_USER, POSTGRES_DB and PGDATA_VOLUME.
- Backups are written as grimoire-<ts>.tar with format grimoire-backup-tar.
  Archives named scribe-* with the scribe-backup-tar manifest still restore
  and are still counted at the destination (folder and S3), with tests.
- Exports, the MCP auth realm, the ASGI scope key and the persistent logger
  carry the new name.

Kept on purpose: the secret-sealing key label stays "scribe.secrets.v1",
because every stored secret was derived under it.

Plugin identity (plugin name, hooks, env vars, .scribe marker, skills) is
step 3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 10:50:45 -04:00

226 lines
8.5 KiB
Python

"""The full backup as a file on disk: one uncompressed tar per run.
The scheduled backup lands somewhere that keeps a history of it — a folder a
backup service watches, an S3 bucket — and from there it is usually copied
off-site by a deduplicating tool such as restic. Everything about the layout
serves that copy: restic cuts a file into chunks at boundaries chosen by the
content, so a chunk it has seen before costs nothing to store again. The file
is therefore laid out so that what did not change between two runs is the
same bytes, in the same place, both times.
- **Never compressed.** Compression rewrites every byte after the first
change, so no chunk would ever match. restic compresses its own repository
after deduplicating.
- **One member per payload section**, `<section>.jsonl`, one row per line.
Rows arrive in primary-key order (export_full_backup orders every query)
and each is written with sorted keys and no spacing, so an unchanged row is
identical bytes, an edit changes one line, and rows appended to a growing
table land at the end of its member. A busy table never shifts the bytes of
a quiet one.
- **The parts that change every run live in `manifest.json` only**: the
export time, the app version and the row counts. The member headers are
fixed (mtime 0, owner 0, mode 0644) and the members come in one order: the
manifest, then the sections by name.
- **One file per run, under a new dated name**, so a service that keeps one
file per backup can thin the history on its own schedule.
The payload inside is exactly `export_full_backup()`'s, so the coverage
guards on that payload (tests/test_services_backup.py) cover this file too,
and `read_archive` hands `restore_full_backup` the same dict it always took.
"""
from __future__ import annotations
import io
import json
import os
import tarfile
from datetime import datetime, timezone
from pathlib import Path
from typing import IO
ARCHIVE_FORMAT = "grimoire-backup-tar"
ARCHIVE_FORMAT_VERSION = 1
MANIFEST_NAME = "manifest.json"
SECTION_SUFFIX = ".jsonl"
NAME_PREFIX = "grimoire-"
NAME_SUFFIX = ".tar"
# Grimoire was called Scribe, and archives it wrote carry that name in their
# manifest and file name. They are read and counted like any other, so a
# backup taken before the rename still restores.
READABLE_FORMATS = (ARCHIVE_FORMAT, "scribe-backup-tar")
NAME_PREFIXES = (NAME_PREFIX, "scribe-")
def is_backup_name(name: str) -> bool:
"""A file or object name this app's scheduled backup wrote."""
return name.endswith(NAME_SUFFIX) and name.startswith(NAME_PREFIXES)
def archive_name(at: datetime) -> str:
"""`grimoire-20261015T030000Z.tar` — UTC, sortable, one per run."""
return f"{NAME_PREFIX}{at.astimezone(timezone.utc):%Y%m%dT%H%M%SZ}{NAME_SUFFIX}"
def _encode(value) -> str:
# default=str matches the admin download's json.dumps, so a datetime that
# reaches the payload unconverted reads back the same way on restore.
return json.dumps(
value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str,
)
def _split(payload: dict) -> tuple[dict, dict[str, list]]:
"""Separate the row sections from the header (version, scope, notices).
A section is a list of rows under a plain name. `_not_included` is a list
too, but of table names: it is a notice, so it stays in the header.
"""
header: dict = {}
sections: dict[str, list] = {}
for key, value in payload.items():
if isinstance(value, list) and not key.startswith("_"):
sections[key] = value
else:
header[key] = value
return header, sections
def _member(name: str, data: bytes) -> tuple[tarfile.TarInfo, io.BytesIO]:
info = tarfile.TarInfo(name)
info.size = len(data)
info.mtime = 0
info.mode = 0o644
info.uid = info.gid = 0
info.uname = info.gname = ""
return info, io.BytesIO(data)
def write_archive_to(payload: dict, out: IO[bytes], *, app_version: str) -> dict:
"""Write `payload` as the backup tar to an open binary file.
Returns the manifest, so the caller can report row counts without
reading the file back.
"""
header, sections = _split(payload)
names = sorted(sections)
manifest = {
"format": ARCHIVE_FORMAT,
"format_version": ARCHIVE_FORMAT_VERSION,
"app_version": app_version,
"header": header,
"sections": {name: len(sections[name]) for name in names},
}
with tarfile.open(fileobj=out, mode="w", format=tarfile.USTAR_FORMAT) as tar:
tar.addfile(*_member(
MANIFEST_NAME, (json.dumps(manifest, sort_keys=True, indent=2,
default=str) + "\n").encode(),
))
for name in names:
data = b"".join(
_encode(row).encode() + b"\n" for row in sections[name]
)
tar.addfile(*_member(name + SECTION_SUFFIX, data))
return manifest
def write_archive(
payload: dict, directory: Path, at: datetime, *, app_version: str,
) -> Path:
"""Write the backup tar into `directory` under its dated name, atomically.
The bytes go to a dot-prefixed `.part` file first, are fsync'd, and only
then renamed to the final name. A watcher of the folder (or anything else
listing it) never sees half a backup under a backup's name, and a run that
fails leaves nothing behind but the error.
"""
directory.mkdir(parents=True, exist_ok=True)
final = directory / archive_name(at)
part = directory / f".{final.name}.part"
try:
with open(part, "wb") as f:
write_archive_to(payload, f, app_version=app_version)
f.flush()
os.fsync(f.fileno())
os.replace(part, final)
except BaseException:
part.unlink(missing_ok=True)
raise
_fsync_dir(directory)
return final
def _fsync_dir(directory: Path) -> None:
"""Make the rename itself durable. Some filesystems (and NFS mounts)
refuse a directory fsync; the file's own fsync already happened, so that
refusal is not a failure of the backup."""
try:
fd = os.open(directory, os.O_RDONLY)
except OSError:
return
try:
os.fsync(fd)
except OSError:
pass
finally:
os.close(fd)
class ArchiveError(ValueError):
"""The file is not a backup tar this version can read, or is damaged."""
def is_archive(fileobj: IO[bytes]) -> bool:
"""True when `fileobj` (seekable, at its start) holds a tar. Leaves the
position where it was, so the caller can fall back to reading JSON."""
pos = fileobj.tell()
try:
head = fileobj.read(tarfile.BLOCKSIZE)
finally:
fileobj.seek(pos)
return len(head) == tarfile.BLOCKSIZE and head[257:262] == b"ustar"
def read_archive(fileobj: IO[bytes]) -> dict:
"""Read a backup tar back into the payload `restore_full_backup` takes.
Every section the manifest names must be present with the row count it
names: a member that went missing or was cut short is an error here, not
a restore that reports success with less than it was given.
"""
try:
tar = tarfile.open(fileobj=fileobj, mode="r:")
except tarfile.TarError as exc:
raise ArchiveError(f"not a backup archive: {exc}") from exc
with tar:
manifest = json.loads(_read_member(tar, MANIFEST_NAME))
if manifest.get("format") not in READABLE_FORMATS:
raise ArchiveError("not a Grimoire backup archive (no Grimoire manifest)")
if manifest.get("format_version", 0) > ARCHIVE_FORMAT_VERSION:
raise ArchiveError(
f"archive format {manifest['format_version']} is newer than "
f"this Grimoire reads ({ARCHIVE_FORMAT_VERSION}); upgrade first"
)
payload = dict(manifest.get("header") or {})
for name, count in (manifest.get("sections") or {}).items():
raw = _read_member(tar, name + SECTION_SUFFIX)
rows = [json.loads(line) for line in raw.splitlines() if line]
if len(rows) != count:
raise ArchiveError(
f"{name}{SECTION_SUFFIX} holds {len(rows)} rows; "
f"the manifest says {count}"
)
payload[name] = rows
return payload
def _read_member(tar: tarfile.TarFile, name: str) -> bytes:
try:
member = tar.getmember(name)
except KeyError as exc:
raise ArchiveError(f"the archive has no {name}") from exc
f = tar.extractfile(member)
if f is None:
raise ArchiveError(f"{name} in the archive is not a file")
return f.read()