Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/object_backup_index.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 8 minutes ago History
object_backup_index.py · 18.3 KB · 479 lines
1"""Read-only inventory and on-demand creation for runtime backups.
2
3Backups are the tar/gzip archives written by ``object_backup`` under the
4configured backups directory. This module lists them, creates a new
5full-runtime backup on demand, and resolves a backup id to a safe path
6for download. It is the data layer behind the admin backup endpoints.
7
8A backup contains the runtime data directory — every record, file and
9user, though not password hashes, sessions, API keys or service keys
10(object_backup.RUNTIME_DATA_FILES) — so the HTTP surface that uses this
11module is strictly admin-gated. Nothing here is public.
12"""
13
14from __future__ import annotations
15
16import csv
17import hashlib
18import io
19import json
20import re
21from datetime import datetime, timedelta, timezone
22from pathlib import Path
23
24import object_backup
25import object_collections
26import object_records
27
28MANUAL_LABEL = "manual"
29_ID_RE = re.compile(r"^[0-9A-Za-z][0-9A-Za-z._-]{0,255}\.tar\.gz$")
30
31
32def backups_dir(data_dir: Path | str | None = None) -> Path:
33 """Return the configured backups directory (honors DBBASIC_BACKUPS_DIR)."""
34 return object_backup._backups_dir(None, data_dir=data_dir)
35
36
37def validate_backup_id(backup_id: str) -> bool:
38 """Return True when a backup id is a safe archive filename (no traversal)."""
39 if not isinstance(backup_id, str) or "/" in backup_id or "\\" in backup_id:
40 return False
41 return bool(_ID_RE.fullmatch(backup_id))
42
43
44def backup_path(backup_id: str, *, data_dir: Path | str | None = None) -> Path:
45 """Resolve a backup id to its path, refusing anything outside the dir."""
46 if not validate_backup_id(backup_id):
47 raise ValueError(f"invalid backup id: {backup_id!r}")
48 root = backups_dir(data_dir).resolve(strict=False)
49 path = (backups_dir(data_dir) / backup_id).resolve(strict=False)
50 try:
51 path.relative_to(root)
52 except ValueError as exc:
53 raise ValueError("backup path escapes the backups directory") from exc
54 return path
55
56
57def list_backups(*, data_dir: Path | str | None = None) -> list[dict[str, object]]:
58 """Return backup metadata, newest first — never the archive contents."""
59 directory = backups_dir(data_dir)
60 if not directory.is_dir():
61 return []
62 entries = [
63 _entry(path)
64 for path in directory.glob("*.tar.gz")
65 if path.is_file() and validate_backup_id(path.name)
66 ]
67 entries.sort(key=lambda entry: entry["created_at"], reverse=True)
68 return entries
69
70
71def create_backup(*, data_dir: Path | str | None = None) -> dict[str, object]:
72 """Create a full-runtime backup now and return its metadata."""
73 summary = object_backup.create_runtime_restore_point(MANUAL_LABEL, data_dir=data_dir)
74 return _entry(Path(summary.path))
75
76
77def _entry(path: Path) -> dict[str, object]:
78 stat = path.stat()
79 name = path.name
80 stem = name[: -len(".tar.gz")] if name.endswith(".tar.gz") else name
81 parts = stem.split("-", 1)
82 label = parts[1] if len(parts) == 2 else stem
83 if label.startswith("package-"):
84 kind, scope = "package", label[len("package-"):]
85 elif label == MANUAL_LABEL:
86 kind, scope = "manual", "runtime"
87 else:
88 kind, scope = "restore-point", label
89 created_at = (
90 datetime.fromtimestamp(stat.st_mtime, tz=timezone.utc)
91 .isoformat()
92 .replace("+00:00", "Z")
93 )
94 return {
95 "id": name,
96 "created_at": created_at,
97 "size": stat.st_size,
98 "kind": kind,
99 "scope": scope,
100 }
101
102
103# Append-mode physical format (docs/storage-modes.md "Append"; the
104# authoritative implementation is object_records.py's OP_FIELD/OP_UPSERT/
105# OP_DELETE and _fold_append_rows). Kept as plain local constants rather
106# than importing object_records's, so this module's read of a records.tsv
107# stays independent of that module's private helpers.
108_OP_FIELD = "_op"
109_OP_DELETE = "del"
110
111
112def _drop_torn_tail(text: str) -> str:
113 """Drop an unterminated final physical line (a write caught mid-append).
114
115 Append-mode writers only consider a row committed once it is followed
116 by a row-terminating "\\n" (see docs/append-only-storage-design.md,
117 Crash Safety), so anything after the last one is an in-flight write --
118 not data -- on either the backup or the live side.
119
120 QUOTE-AWARE, via the shared `object_records.committed_prefix_len`: a
121 "\\n" INSIDE a quoted multi-line field is content, never a row
122 boundary.
123
124 THIS WAS THE BUG, and it is worth naming because of how it survived.
125 The body used to be `endswith("\\n") or rfind("\\n")` under a docstring
126 claiming it "mirrors object_records._drop_torn_tail" -- which had been
127 upgraded to be quote-aware while this copy was not, silently, for
128 months. Worse than the read-side original: a file ending with a "\\n"
129 that sits INSIDE an unclosed quote was returned untouched, so a
130 restored backup could resurrect a garbled row that a live read of the
131 same bytes handles correctly. It carried no test at all, which is
132 precisely why nothing caught the drift.
133
134 It now CALLS the shared implementation instead of mirroring it. That is
135 a deliberate exception to this module's usual independence from
136 object_records' internals: keeping a private copy is exactly what
137 failed, `committed_prefix_len` is exported for this reason, and two
138 implementations of one invariant drift while one cannot.
139 """
140 if text == "":
141 return text
142 return text[: object_records.committed_prefix_len(text)]
143
144
145def _fold_append_rows(rows: list[dict[str, str]]) -> dict[str, dict[str, str]]:
146 """Fold physical append-mode rows into live records, last-wins per id.
147
148 Minimal local replica of object_records._fold_append_rows's id
149 semantics, for backup preview/diff purposes only (docs/storage-modes.md
150 "Append"): a delete (`_op == "del"`) removes the id; any other row is
151 an upsert that (re)sets it — so an id updated multiple times, or
152 deleted and later re-created, ends up holding just its final live
153 values. `_op` itself is stripped from every returned row. Unlike
154 object_records's fold, this doesn't need to preserve list order (the
155 callers here only ever look records up by id for a diff), so it
156 returns a plain dict rather than an OrderedDict-backed list.
157 """
158 folded: dict[str, dict[str, str]] = {}
159 for row in rows:
160 record_id = row.get("id")
161 if not record_id:
162 continue
163 if row.get(_OP_FIELD) == _OP_DELETE:
164 folded.pop(record_id, None)
165 continue
166 folded[record_id] = {key: value for key, value in row.items() if key != _OP_FIELD}
167 return folded
168
169
170def _parse_append_tsv_by_id(text: str, header: list[str]) -> dict[str, dict[str, str]]:
171 """Parse+fold an append-mode records.tsv body into a dict keyed by id.
172
173 `header` is the already-inspected physical header (first column
174 `_op`). A torn final line is dropped first (_drop_torn_tail); a row
175 that still fails to tokenize stops consumption at that point rather
176 than raising, matching object_records._parse_append_body's tolerance
177 of an in-flight write.
178 """
179 field_count = len(header)
180 reader = csv.reader(io.StringIO(_drop_torn_tail(text)), delimiter="\t")
181 next(reader, None) # header, already parsed by the caller
182
183 physical_rows: list[dict[str, str]] = []
184 while True:
185 try:
186 row = next(reader)
187 except StopIteration:
188 break
189 except csv.Error:
190 break
191 if not row:
192 continue
193 physical_rows.append(
194 {header[i]: (row[i] if i < len(row) else "") for i in range(field_count)}
195 )
196
197 return _fold_append_rows(physical_rows)
198
199
200def _parse_tsv_by_id(raw: bytes | None) -> dict[str, dict[str, str]]:
201 """Parse a records.tsv payload into a dict keyed by the "id" column.
202
203 Dispatches on the physical header, exactly like object_records does
204 (docs/append-only-storage-design.md): a file whose first column is
205 `_op` is an append-mode log and is folded last-wins-by-id first (see
206 _fold_append_rows), so callers only ever see LIVE logical records —
207 never raw log rows, superseded values, or tombstoned ids. Classic
208 files (no `_op` header) go through the original DictReader-based
209 parse, unchanged.
210 """
211 if not raw:
212 return {}
213 text = raw.decode("utf-8")
214
215 header_row = next(csv.reader(io.StringIO(text), delimiter="\t"), None)
216 if header_row and header_row[0] == _OP_FIELD:
217 return _parse_append_tsv_by_id(text, header_row)
218
219 reader = csv.DictReader(io.StringIO(text), delimiter="\t")
220 rows: dict[str, dict[str, str]] = {}
221 for row in reader:
222 record_id = row.get("id")
223 if record_id is None:
224 continue
225 rows[record_id] = dict(row)
226 return rows
227
228
229def _records_tsv_member(collection: str) -> str:
230 return f"data/collections/{collection}/records.tsv"
231
232
233def _live_records_tsv(collection: str, *, data_dir: Path | str | None) -> bytes | None:
234 path = object_backup._data_dir(data_dir) / "collections" / collection / "records.tsv"
235 if not path.is_file():
236 return None
237 return path.read_bytes()
238
239
240def _diff_records(
241 backup_rows: dict[str, dict[str, str]],
242 live_rows: dict[str, dict[str, str]],
243) -> dict[str, object]:
244 """Diff two id->row maps with the semantics "restoring makes live == backup"."""
245 added = sorted(set(backup_rows) - set(live_rows))
246 removed = sorted(set(live_rows) - set(backup_rows))
247 changed = []
248 unchanged = 0
249 for record_id in sorted(set(backup_rows) & set(live_rows)):
250 backup_row = backup_rows[record_id]
251 live_row = live_rows[record_id]
252 if backup_row == live_row:
253 unchanged += 1
254 continue
255 fields = sorted(
256 field
257 for field in set(backup_row) | set(live_row)
258 if backup_row.get(field) != live_row.get(field)
259 )
260 changed.append({"id": record_id, "fields": fields})
261
262 diff_hash = hashlib.sha256(
263 json.dumps({"added": added, "removed": removed, "changed": changed}, sort_keys=True).encode(
264 "utf-8"
265 )
266 ).hexdigest()
267
268 return {
269 "diff_hash": diff_hash,
270 "added": added,
271 "removed": removed,
272 "changed": changed,
273 "unchanged": unchanged,
274 }
275
276
277def preview_collection(
278 backup_id: str,
279 collection: str,
280 *,
281 data_dir: Path | str | None = None,
282) -> dict[str, object]:
283 """Diff a collection's records between a backup and the live data dir.
284
285 The semantics are "if you restore, live becomes the backup's version":
286 added ids would reappear, removed ids would be dropped, changed ids
287 would have the listed fields overwritten. Either side (or both) may be
288 an append-mode file, a classic file, or missing; _parse_tsv_by_id folds
289 append-mode logs to live records first, so this always diffs live
290 logical content regardless of physical storage mode.
291 """
292 if not object_collections.validate_collection_name(collection):
293 raise ValueError(f"Invalid collection name: {collection}")
294
295 archive_path = backup_path(backup_id, data_dir=data_dir)
296 member_name = _records_tsv_member(collection)
297 archived_raw = object_backup.read_backup_member(archive_path, member_name)
298 live_raw = _live_records_tsv(collection, data_dir=data_dir)
299
300 backup_rows = _parse_tsv_by_id(archived_raw)
301 live_rows = _parse_tsv_by_id(live_raw)
302 diff = _diff_records(backup_rows, live_rows)
303
304 return {
305 "target": {"kind": "collection", "name": collection},
306 "backup_id": backup_id,
307 "present_in_backup": archived_raw is not None,
308 "diff_hash": diff["diff_hash"],
309 "added": diff["added"],
310 "removed": diff["removed"],
311 "changed": diff["changed"],
312 "unchanged": diff["unchanged"],
313 }
314
315
316def preview_record(
317 backup_id: str,
318 collection: str,
319 record_id: str,
320 *,
321 data_dir: Path | str | None = None,
322) -> dict[str, object]:
323 """Return one record's backup vs. live presence, without diffing all rows.
324
325 `record` is the FOLDED record when the source is append-mode: a
326 tombstoned id reports record=None/present_in_*=False exactly like an
327 id that was never written.
328 """
329 if not object_collections.validate_collection_name(collection):
330 raise ValueError(f"Invalid collection name: {collection}")
331
332 archive_path = backup_path(backup_id, data_dir=data_dir)
333 member_name = _records_tsv_member(collection)
334 archived_raw = object_backup.read_backup_member(archive_path, member_name)
335 live_raw = _live_records_tsv(collection, data_dir=data_dir)
336
337 backup_rows = _parse_tsv_by_id(archived_raw)
338 live_rows = _parse_tsv_by_id(live_raw)
339
340 return {
341 "collection": collection,
342 "id": record_id,
343 "record": backup_rows.get(record_id),
344 "present_in_backup": record_id in backup_rows,
345 "present_in_live": record_id in live_rows,
346 }
347
348
349# === retention ==============================================================
350#
351# A restore point is created automatically before EVERY package install
352# (object_server's create_restore_point, passed to install_package as
353# before_write). Nothing ever removed them. On the box that motivated this
354# there were 157 of them at ~91MB each -- 14.3GB against 4.0GB free, on a
355# machine that also serves production, growing by one archive per install.
356# 93 of them had been written in the preceding two days.
357#
358# That is the fourth instance of one pattern here: page_views, restore
359# points, change logs, and now restore points again. A log nobody told how
360# big it may get fails on the worst day rather than an ordinary one.
361#
362# WHAT MAKES A DEFAULT SAFE HERE, and why this differs from the change-log
363# pass (which is off unless an operator asks): those archives are not the
364# operator's data. Nobody asked for 157 of them; they are scaffolding the
365# server produced on its own behalf, and the value of the hundredth-oldest
366# one from three weeks ago is indistinguishable from zero. A change log,
367# by contrast, IS the audit trail, which is why deciding how much of it to
368# keep is not a decision a daemon makes for somebody.
369#
370# So the split is by KIND, which `_entry` already computes:
371#
372# package automatic, one per install -> prunable
373# manual a person pressed a button -> NEVER touched
374# restore-point a named point somebody chose -> NEVER touched
375#
376# Anything a human asked for survives forever regardless of policy. Only
377# the machine's own scaffolding is swept.
378
379PRUNABLE_KINDS = ("package",)
380
381# Below this many prunable archives, do nothing at all. A handful of
382# restore points is the feature working; sweeping down to the bone would
383# remove the safety net this exists to provide.
384MIN_KEEP = 5
385
386# The ceiling that actually matters. A first cut of this used only
387# keep_last plus an age window, and a dry run on the real box showed it
388# freeing 78MB out of 14.3GB: 93 archives had been written in two days, so
389# the age window protected nearly all of them -- and because the data
390# directory grows, the RECENT ones are the large ones (~91MB each against
391# ~1.7MB for the oldest). A policy expressed in COUNT and AGE cannot bound
392# a quantity measured in BYTES.
393#
394# So the budget is the primary control and the window is a courtesy inside
395# it: newest-first, keep while there is room. 2GB holds roughly the last
396# twenty snapshots of a mid-size box and is a rounding error next to the
397# disk it protects.
398DEFAULT_MAX_TOTAL_BYTES = 2 * 1024 * 1024 * 1024
399
400
401def prune_backups(
402 *,
403 data_dir: Path | str | None = None,
404 keep_last: int = 20,
405 keep_newer_than_days: int = 0,
406 max_total_bytes: int = DEFAULT_MAX_TOTAL_BYTES,
407 dry_run: bool = False,
408) -> dict[str, object]:
409 """Remove old AUTOMATIC restore points. Never touches manual backups.
410
411 `keep_last` -- how many of the newest automatic archives always
412 survive, whatever they weigh. The safety floor.
413 `max_total_bytes` -- the ceiling on everything kept. THE control that
414 actually bounds a disk; see DEFAULT_MAX_TOTAL_BYTES for why count and
415 age alone provably do not. 0 disables it.
416 `keep_newer_than_days` -- inside the budget, prefer keeping anything
417 younger than this, so a burst of installs in one afternoon does not
418 evict the morning's safety net. It can never push the total past the
419 ceiling. 0 disables the window.
420
421 Returns what it did (or would do, with `dry_run`), never raising for
422 an individual file it cannot delete: a backup directory that is
423 partially unwritable should still be swept as far as it can be, and
424 the caller gets the errors rather than an exception mid-loop.
425 """
426 keep_last = max(MIN_KEEP, int(keep_last))
427 entries = list_backups(data_dir=data_dir) # newest first
428
429 prunable = [e for e in entries if e["kind"] in PRUNABLE_KINDS]
430 protected = [e for e in entries if e["kind"] not in PRUNABLE_KINDS]
431
432 cutoff = ""
433 if keep_newer_than_days and int(keep_newer_than_days) > 0:
434 cutoff = (
435 datetime.now(tz=timezone.utc)
436 - timedelta(days=int(keep_newer_than_days))
437 ).isoformat().replace("+00:00", "Z")
438
439 # Newest-first: the floor is unconditional, then the window is honoured
440 # only while the running total stays under the ceiling.
441 kept_bytes = sum(int(e["size"]) for e in prunable[:keep_last])
442 budget = int(max_total_bytes)
443 doomed = []
444 for entry in prunable[keep_last:]:
445 size = int(entry["size"])
446 in_window = bool(cutoff) and str(entry["created_at"]) >= cutoff
447 room = (not budget) or (kept_bytes + size <= budget)
448 if in_window and room:
449 kept_bytes += size
450 continue
451 doomed.append(entry)
452
453 removed, freed, errors = [], 0, []
454 if not dry_run:
455 directory = backups_dir(data_dir)
456 for entry in doomed:
457 path = directory / str(entry["id"])
458 try:
459 size = path.stat().st_size
460 path.unlink()
461 except OSError as exc:
462 errors.append(f"{entry['id']}: {exc}")
463 continue
464 removed.append(str(entry["id"]))
465 freed += size
466 else:
467 removed = [str(entry["id"]) for entry in doomed]
468 freed = sum(int(entry["size"]) for entry in doomed)
469
470 return {
471 "removed": len(removed),
472 "removed_ids": removed,
473 "freed_bytes": freed,
474 "kept": len(prunable) - len(removed),
475 "kept_bytes": kept_bytes,
476 "protected": len(protected),
477 "errors": errors,
478 "dry_run": bool(dry_run),
479 }