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_package_baselines.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, 7 minutes ago History
object_package_baselines.py · 7.4 KB · 192 lines
1"""Package provenance baselines for DBBASIC.
2
3Records what a package shipped — a content hash per object and per schema —
4at install time, so "is this customized?" becomes a computable question:
5hash the live source/schema and compare to the stamp. Without this stamp a
6human's edit cannot be distinguished from the shipped file, and every
7upgrade is a coin flip. See docs/upgrade-and-customization.md (Rule 0:
8Provenance Baselines), which this module implements.
9"""
10
11from __future__ import annotations
12
13import hashlib
14import json
15import os
16import tempfile
17from pathlib import Path
18from typing import Any, Iterable, Mapping
19
20from object_versions import DEFAULT_DATA_DIR
21
22BASELINES_DIR = "package_baselines"
23
24
25def sha256_text(text: str) -> str:
26 """Return the hex sha256 digest of text, encoded as UTF-8."""
27 return hashlib.sha256(text.encode("utf-8")).hexdigest()
28
29
30def canonical_schema_hash(schema: Mapping[str, Any]) -> str:
31 """Return a stable hash for a schema dict regardless of key order."""
32 return sha256_text(json.dumps(schema, sort_keys=True, separators=(",", ":")))
33
34
35def baseline_path(package_id: str, *, base_dir: Path | str = DEFAULT_DATA_DIR) -> Path:
36 """Return the path to the baseline file for a package."""
37 return Path(base_dir) / BASELINES_DIR / f"{package_id}.json"
38
39
40def load_baseline(package_id: str, *, base_dir: Path | str = DEFAULT_DATA_DIR) -> dict[str, Any] | None:
41 """Return the recorded baseline for a package, or None if absent/unreadable."""
42 path = baseline_path(package_id, base_dir=base_dir)
43 try:
44 return json.loads(path.read_text(encoding="utf-8"))
45 except (json.JSONDecodeError, OSError):
46 return None
47
48
49def list_baselines(*, base_dir: Path | str = DEFAULT_DATA_DIR) -> dict[str, dict[str, Any]]:
50 """Every readable recorded baseline, keyed by package id.
51
52 A package with a baseline is an installed package: this directory is the
53 only record of that. Unreadable files are skipped, as load_baseline does.
54 """
55 root = Path(base_dir) / BASELINES_DIR
56 if not root.is_dir():
57 return {}
58 baselines: dict[str, dict[str, Any]] = {}
59 for path in sorted(root.glob("*.json")):
60 baseline = load_baseline(path.stem, base_dir=base_dir)
61 if isinstance(baseline, dict):
62 baselines[path.stem] = baseline
63 return baselines
64
65
66def record_baseline(
67 package_id: str,
68 *,
69 version: str,
70 objects: Mapping[str, str],
71 schemas: Mapping[str, str],
72 schema_bodies: Mapping[str, Any] | None = None,
73 permissions: Iterable[Mapping[str, Any]] | None = None,
74 seed_rows: Mapping[str, Any] | None = None,
75 nav: Iterable[Mapping[str, Any]] | None = None,
76 attention: Iterable[Mapping[str, Any]] | None = None,
77 installed_at: str | None = None,
78 base_dir: Path | str = DEFAULT_DATA_DIR,
79) -> dict[str, Any]:
80 """Stamp a package's baseline (shipped object/schema hashes) and return it.
81
82 `schema_bodies` additionally stores the normalized schema body (not just
83 its hash) per collection, so a later upgrade can three-way *merge* field
84 lists instead of only detecting a hash mismatch (see
85 docs/upgrade-and-customization.md, Rule 3: Data Fields That Survive
86 Schema Upgrades).
87
88 `permissions` is the list of permission rules the package shipped, as
89 rule dicts. It is what lets the NEXT install tell "a rule this package
90 used to ship and no longer does" (retire it) from "a rule somebody else
91 wrote" (leave it): the `package` tag on a live rule says who added it,
92 not whether it is still the rule that was shipped. The key is written
93 only when the caller passes a list, and its ABSENCE is meaningful -- a
94 baseline stamped before permissions were recorded says nothing about
95 what was shipped, which is not the same as "shipped no rules" (see
96 object_packages._permission_retractions).
97
98 `seed_rows` is `{collection: {record_id: {"shipped": {column: sha},
99 "live": {column: sha}}}}`: per seeded row and column, the hash of what
100 the package shipped and of what the row held right after the install
101 wrote it. It is what lets a LATER install tell a column nobody has
102 touched (replace it with the new version's) from one an operator edited
103 (keep it), without ever storing the values themselves. Absent for a
104 baseline stamped before rows were tracked; such a row can only be
105 adopted, never replaced (object_packages._reconcile_seed_rows).
106
107 `nav` and `attention` are the normalized `nav` / `attention` entries the
108 installed version declared. They are what lets a LATER install of app-nav
109 register the doors and queues of packages installed before it
110 (object_packages._register_installed_declarations), from what was really
111 installed rather than whatever version of the manifest is on disk now.
112 Written only when passed; absent on a baseline stamped before they were.
113 """
114 baseline = {
115 "package": package_id,
116 "version": version,
117 "installed_at": installed_at,
118 "objects": dict(objects),
119 "schemas": dict(schemas),
120 "schema_bodies": {k: v for k, v in (schema_bodies or {}).items()},
121 }
122 if permissions is not None:
123 baseline["permissions"] = [dict(rule) for rule in permissions]
124 if seed_rows is not None:
125 baseline["seed_rows"] = {
126 collection: {rid: dict(entry) for rid, entry in rows.items()}
127 for collection, rows in seed_rows.items()
128 }
129 if nav is not None:
130 baseline["nav"] = [dict(entry) for entry in nav]
131 if attention is not None:
132 baseline["attention"] = [dict(entry) for entry in attention]
133 _write_baseline(baseline, baseline_path(package_id, base_dir=base_dir))
134 return baseline
135
136
137def update_artifact(
138 package_id: str,
139 *,
140 kind: str,
141 key: str,
142 sha: str,
143 version: str,
144 schema_body: Mapping[str, Any] | None = None,
145 base_dir: Path | str = DEFAULT_DATA_DIR,
146) -> dict[str, Any]:
147 """Stamp a single artifact's baseline hash (used by reconcile resolution).
148
149 When `kind == "schema"` and `schema_body` is given, also stamps the
150 baseline's stored schema body for `key`, so future upgrades can merge
151 against it (see `record_baseline`).
152 """
153 baseline = load_baseline(package_id, base_dir=base_dir) or {
154 "package": package_id,
155 "version": version,
156 "installed_at": None,
157 "objects": {},
158 "schemas": {},
159 "schema_bodies": {},
160 }
161 section = "objects" if kind == "object" else "schemas"
162 baseline.setdefault("objects", {})
163 baseline.setdefault("schemas", {})
164 baseline.setdefault("schema_bodies", {})
165 baseline[section][key] = sha
166 baseline["version"] = version
167 baseline["package"] = package_id
168
169 if kind == "schema" and schema_body is not None:
170 baseline["schema_bodies"][key] = schema_body
171
172 _write_baseline(baseline, baseline_path(package_id, base_dir=base_dir))
173 return baseline
174
175
176def _write_baseline(baseline: Mapping[str, Any], path: Path) -> None:
177 path.parent.mkdir(parents=True, exist_ok=True)
178
179 fd, tmp_name = tempfile.mkstemp(
180 prefix=f".{path.name}.",
181 suffix=".tmp",
182 dir=path.parent,
183 )
184 try:
185 with os.fdopen(fd, "w", encoding="utf-8") as handle:
186 json.dump(baseline, handle, indent=2, sort_keys=True)
187 os.replace(tmp_name, path)
188 finally:
189 try:
190 Path(tmp_name).unlink()
191 except FileNotFoundError:
192 pass