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

2 downloads

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

Dan Quellhorst One-click installs: the starting apps in dependency order, a readable owner id, cloud-init at the release 9ea1fef 1 hour, 34 minutes ago History
object_reconciles.py · 7.5 KB · 221 lines
1"""Pending-reconcile records for DBBASIC package upgrades.
2
3Phase 1 (object_package_baselines) makes "is this customized?" a computable
4question. Phase 2 uses that answer on upgrade: per object/schema, a
5three-way compare of the old baseline, the live artifact, and the newly
6shipped artifact decides whether to fast-forward, keep the customization, or
7park a conflict. This module is the park: a JSON-file store of
8pending-reconcile records that hold both versions until a human (or script)
9picks "keep mine" or "take theirs". See docs/upgrade-and-customization.md
10(Rule 1: Reconcile, Don't Replace).
11
12The engine that produces these records lives in object_packages.py
13(install_package); this module only stores and resolves them.
14"""
15
16from __future__ import annotations
17
18import json
19import os
20import re
21import tempfile
22import uuid
23from pathlib import Path
24from typing import Any, Iterable, Mapping
25
26import object_package_baselines
27import object_schemas
28import object_source
29import object_versions
30from object_versions import DEFAULT_DATA_DIR
31
32RECONCILES_DIR = "reconciles"
33RECONCILE_CHOICES = ("keep_mine", "take_theirs")
34
35_RECONCILE_ID_RE = re.compile(r"^[0-9a-f]{32}$")
36
37
38def _new_id() -> str:
39 return uuid.uuid4().hex
40
41
42def validate_reconcile_id(reconcile_id: Any) -> bool:
43 """Return True when reconcile_id is a safe, traversal-proof identifier."""
44 if not isinstance(reconcile_id, str):
45 return False
46 return bool(_RECONCILE_ID_RE.fullmatch(reconcile_id))
47
48
49def reconcile_path(reconcile_id: str, *, base_dir: Path | str = DEFAULT_DATA_DIR) -> Path:
50 """Return the path to a reconcile record file, or raise on an invalid id."""
51 if not validate_reconcile_id(reconcile_id):
52 raise ValueError(f"Invalid reconcile id: {reconcile_id}")
53 return Path(base_dir) / RECONCILES_DIR / f"{reconcile_id}.json"
54
55
56def create_reconcile(
57 *,
58 package: str,
59 target_version: str,
60 baseline_version: str | None,
61 artifact: Mapping[str, Any],
62 mine: str,
63 theirs: str,
64 base_sha: str | None,
65 created_at: str | None = None,
66 collisions: list[str] | None = None,
67 base_dir: Path | str = DEFAULT_DATA_DIR,
68) -> dict[str, Any]:
69 """Park a conflict: build, atomic-write, and return a pending-reconcile record.
70
71 `collisions`, when given, names the specific fields (for a schema
72 artifact) that could not be auto-merged -- see
73 `object_schemas.merge_schema_fields` and
74 docs/upgrade-and-customization.md (Rule 3). It lets a reconcile inbox
75 show exactly what needs a human decision instead of the whole artifact.
76 """
77 record = {
78 "id": _new_id(),
79 "package": package,
80 "target_version": target_version,
81 "baseline_version": baseline_version,
82 "artifact": dict(artifact),
83 "created_at": created_at,
84 "status": "pending",
85 "resolution": None,
86 "base_sha": base_sha,
87 "mine": mine,
88 "theirs": theirs,
89 "collisions": list(collisions) if collisions else [],
90 }
91 _write_reconcile(record, reconcile_path(record["id"], base_dir=base_dir))
92 return record
93
94
95def get_reconcile(reconcile_id: str, *, base_dir: Path | str = DEFAULT_DATA_DIR) -> dict[str, Any] | None:
96 """Return one reconcile record, or None if absent/invalid/unreadable."""
97 if not validate_reconcile_id(reconcile_id):
98 return None
99 path = reconcile_path(reconcile_id, base_dir=base_dir)
100 try:
101 return json.loads(path.read_text(encoding="utf-8"))
102 except (json.JSONDecodeError, OSError):
103 return None
104
105
106def list_reconciles(
107 *,
108 base_dir: Path | str = DEFAULT_DATA_DIR,
109 status: str | None = None,
110 package: str | None = None,
111) -> list[dict[str, Any]]:
112 """Return reconcile records, optionally filtered, sorted by created_at then id."""
113 root = Path(base_dir) / RECONCILES_DIR
114 if not root.is_dir():
115 return []
116
117 records: list[dict[str, Any]] = []
118 for path in root.glob("*.json"):
119 if not validate_reconcile_id(path.stem):
120 continue
121 try:
122 record = json.loads(path.read_text(encoding="utf-8"))
123 except (json.JSONDecodeError, OSError):
124 continue
125 if status is not None and record.get("status") != status:
126 continue
127 if package is not None and record.get("package") != package:
128 continue
129 records.append(record)
130
131 records.sort(key=lambda record: (record.get("created_at") or "", record.get("id") or ""))
132 return records
133
134
135def count_pending(*, base_dir: Path | str = DEFAULT_DATA_DIR, package: str | None = None) -> int:
136 """Return the number of pending reconciles, optionally scoped to a package."""
137 return len(list_reconciles(base_dir=base_dir, status="pending", package=package))
138
139
140def resolve_reconcile(
141 reconcile_id: str,
142 choice: str,
143 *,
144 base_dir: Path | str = DEFAULT_DATA_DIR,
145 object_roots: Iterable[Path] | None = None,
146 resolved_at: str | None = None,
147) -> dict[str, Any]:
148 """Resolve a pending reconcile by keeping the live artifact or taking the shipped one."""
149 if choice not in RECONCILE_CHOICES:
150 raise ValueError(f"Invalid reconcile choice: {choice}")
151
152 record = get_reconcile(reconcile_id, base_dir=base_dir)
153 if record is None:
154 raise ValueError(f"Reconcile not found: {reconcile_id}")
155 if record.get("status") != "pending":
156 raise ValueError(f"Reconcile already resolved: {reconcile_id}")
157
158 base = Path(base_dir)
159 artifact = record["artifact"]
160 kind = artifact.get("kind")
161
162 if kind == "object":
163 sha_theirs = object_package_baselines.sha256_text(record["theirs"])
164 elif kind == "schema":
165 sha_theirs = object_package_baselines.canonical_schema_hash(json.loads(record["theirs"]))
166 else:
167 raise ValueError(f"Unknown reconcile artifact kind: {kind}")
168
169 if choice == "take_theirs":
170 if kind == "object":
171 object_source.update_object_source(
172 object_id=artifact["id"],
173 new_code=record["theirs"],
174 author="reconcile",
175 message=f"take-theirs from {record['package']} {record['target_version']}",
176 roots=object_roots,
177 version_manager=object_versions.VersionManager(base),
178 )
179 else:
180 object_schemas.replace_schema(
181 artifact["collection"],
182 json.loads(record["theirs"]),
183 base_dir=base,
184 )
185
186 key = artifact["id"] if kind == "object" else artifact["collection"]
187 schema_body = json.loads(record["theirs"]) if kind == "schema" else None
188 object_package_baselines.update_artifact(
189 record["package"],
190 kind=kind,
191 key=key,
192 sha=sha_theirs,
193 version=record["target_version"],
194 schema_body=schema_body,
195 base_dir=base,
196 )
197
198 resolved = dict(record)
199 resolved["status"] = "resolved"
200 resolved["resolution"] = {"choice": choice, "resolved_at": resolved_at}
201 _write_reconcile(resolved, reconcile_path(reconcile_id, base_dir=base_dir))
202 return resolved
203
204
205def _write_reconcile(record: Mapping[str, Any], path: Path) -> None:
206 path.parent.mkdir(parents=True, exist_ok=True)
207
208 fd, tmp_name = tempfile.mkstemp(
209 prefix=f".{path.name}.",
210 suffix=".tmp",
211 dir=path.parent,
212 )
213 try:
214 with os.fdopen(fd, "w", encoding="utf-8") as handle:
215 json.dump(record, handle, indent=2, sort_keys=True)
216 os.replace(tmp_name, path)
217 finally:
218 try:
219 Path(tmp_name).unlink()
220 except FileNotFoundError:
221 pass