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

0 downloads

dbbasic-object-server/object_package_baselines.py
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.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
object_package_baselines.py · 4.4 KB · 134 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, 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 record_baseline(
50 package_id: str,
51 *,
52 version: str,
53 objects: Mapping[str, str],
54 schemas: Mapping[str, str],
55 schema_bodies: Mapping[str, Any] | None = None,
56 installed_at: str | None = None,
57 base_dir: Path | str = DEFAULT_DATA_DIR,
58) -> dict[str, Any]:
59 """Stamp a package's baseline (shipped object/schema hashes) and return it.
60
61 `schema_bodies` additionally stores the normalized schema body (not just
62 its hash) per collection, so a later upgrade can three-way *merge* field
63 lists instead of only detecting a hash mismatch (see
64 docs/upgrade-and-customization.md, Rule 3: Data Fields That Survive
65 Schema Upgrades).
66 """
67 baseline = {
68 "package": package_id,
69 "version": version,
70 "installed_at": installed_at,
71 "objects": dict(objects),
72 "schemas": dict(schemas),
73 "schema_bodies": {k: v for k, v in (schema_bodies or {}).items()},
74 }
75 _write_baseline(baseline, baseline_path(package_id, base_dir=base_dir))
76 return baseline
77
78
79def update_artifact(
80 package_id: str,
81 *,
82 kind: str,
83 key: str,
84 sha: str,
85 version: str,
86 schema_body: Mapping[str, Any] | None = None,
87 base_dir: Path | str = DEFAULT_DATA_DIR,
88) -> dict[str, Any]:
89 """Stamp a single artifact's baseline hash (used by reconcile resolution).
90
91 When `kind == "schema"` and `schema_body` is given, also stamps the
92 baseline's stored schema body for `key`, so future upgrades can merge
93 against it (see `record_baseline`).
94 """
95 baseline = load_baseline(package_id, base_dir=base_dir) or {
96 "package": package_id,
97 "version": version,
98 "installed_at": None,
99 "objects": {},
100 "schemas": {},
101 "schema_bodies": {},
102 }
103 section = "objects" if kind == "object" else "schemas"
104 baseline.setdefault("objects", {})
105 baseline.setdefault("schemas", {})
106 baseline.setdefault("schema_bodies", {})
107 baseline[section][key] = sha
108 baseline["version"] = version
109 baseline["package"] = package_id
110
111 if kind == "schema" and schema_body is not None:
112 baseline["schema_bodies"][key] = schema_body
113
114 _write_baseline(baseline, baseline_path(package_id, base_dir=base_dir))
115 return baseline
116
117
118def _write_baseline(baseline: Mapping[str, Any], path: Path) -> None:
119 path.parent.mkdir(parents=True, exist_ok=True)
120
121 fd, tmp_name = tempfile.mkstemp(
122 prefix=f".{path.name}.",
123 suffix=".tmp",
124 dir=path.parent,
125 )
126 try:
127 with os.fdopen(fd, "w", encoding="utf-8") as handle:
128 json.dump(baseline, handle, indent=2, sort_keys=True)
129 os.replace(tmp_name, path)
130 finally:
131 try:
132 Path(tmp_name).unlink()
133 except FileNotFoundError:
134 pass