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_changes.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_changes.py · 10.2 KB · 318 lines
1"""Append-only change logs for DBBASIC packages.
2
3Package changes are the durable package manager facts behind dry-run, install,
4failure, restore, and rollback screens. The public server records dry-run plans
5and gated package operations, including failed operations.
6"""
7
8from __future__ import annotations
9
10import json
11import threading
12from datetime import datetime, timezone
13from pathlib import Path
14from typing import Any, Mapping
15
16import object_ids
17import object_packages
18from object_versions import DEFAULT_DATA_DIR
19
20PACKAGE_CHANGES_DIR = "package_changes"
21CHANGES_FILE = "changes.jsonl"
22DEFAULT_CHANGE_LIMIT = 100
23MAX_CHANGE_LIMIT = 1000
24VALID_ACTIONS = {
25 "dry_run",
26 "install_requested",
27 "installed",
28 "restore_requested",
29 "failed",
30 "rolled_back",
31}
32
33_LOCKS: dict[str, threading.Lock] = {}
34_LOCKS_GUARD = threading.Lock()
35
36
37class InvalidPackageChangeError(ValueError):
38 """Raised when a package change entry is not safe to write or read."""
39
40
41def append_package_change(
42 *,
43 package_id: str,
44 action: str,
45 package_version: str | None = None,
46 actor: str = "api",
47 message: str = "",
48 details: Mapping[str, Any] | None = None,
49 base_dir: Path | str = DEFAULT_DATA_DIR,
50) -> dict[str, Any]:
51 """Append one package change and return the stored entry."""
52 path = package_changes_file(package_id, base_dir=base_dir)
53 if action not in VALID_ACTIONS:
54 raise InvalidPackageChangeError(f"Invalid package change action: {action}")
55
56 timestamp = _utc_timestamp()
57 entry = {
58 "change_id": _change_id(timestamp, package_id, action),
59 "timestamp": timestamp,
60 "package_id": package_id,
61 "package_version": _clean_optional_text(package_version),
62 "action": action,
63 "actor": _clean_text(actor, default="api"),
64 "message": _clean_text(message, default=_default_message(action)),
65 "details": _normalize_details(details),
66 }
67
68 with _file_lock(path):
69 path.parent.mkdir(parents=True, exist_ok=True)
70 with path.open("a", encoding="utf-8") as handle:
71 handle.write(json.dumps(entry, sort_keys=True, separators=(",", ":")))
72 handle.write("\n")
73
74 return entry
75
76
77def list_package_changes(
78 package_id: str,
79 *,
80 base_dir: Path | str = DEFAULT_DATA_DIR,
81 limit: int = DEFAULT_CHANGE_LIMIT,
82 offset: int = 0,
83) -> dict[str, Any]:
84 """Return newest-first package changes."""
85 path = package_changes_file(package_id, base_dir=base_dir)
86 _validate_page(limit=limit, offset=offset)
87
88 changes = _read_changes(path)
89 total = len(changes)
90 window = changes[offset:offset + limit]
91 return {
92 "package_id": package_id,
93 "changes": window,
94 "count": len(window),
95 "total": total,
96 "limit": limit,
97 "offset": offset,
98 "has_more": offset + len(window) < total,
99 }
100
101
102def get_package_change(
103 package_id: str,
104 change_id: str,
105 *,
106 base_dir: Path | str = DEFAULT_DATA_DIR,
107) -> dict[str, Any] | None:
108 """Return one package change by id, or None when it is not in the log."""
109 clean_change_id = _clean_change_id(change_id)
110 path = package_changes_file(package_id, base_dir=base_dir)
111 for change in _read_changes(path):
112 if change.get("change_id") == clean_change_id:
113 return change
114 return None
115
116
117def package_changes_file(package_id: str, base_dir: Path | str = DEFAULT_DATA_DIR) -> Path:
118 """Return the validated JSONL package change-log path."""
119 if not object_packages.validate_package_id(package_id):
120 raise object_packages.InvalidPackageIdError(f"Invalid package id: {package_id}")
121
122 root = Path(base_dir) / PACKAGE_CHANGES_DIR
123 path = root / package_id / CHANGES_FILE
124 resolved_root = root.resolve(strict=False)
125 resolved_path = path.resolve(strict=False)
126
127 try:
128 resolved_path.relative_to(resolved_root)
129 except ValueError as exc:
130 raise object_packages.InvalidPackageIdError(
131 f"Package change path escapes change directory: {package_id}"
132 ) from exc
133
134 return path
135
136
137def dry_run_change_details(plan: Mapping[str, Any]) -> dict[str, Any]:
138 """Return compact dry-run details safe for package change history."""
139 package = plan.get("package")
140 summary = package if isinstance(package, Mapping) else {}
141 details = _plan_counts(plan, summary)
142 details.update(_permission_retraction_details(plan.get("permission_retractions")))
143 return details
144
145
146def _permission_retraction_details(entries: Any) -> dict[str, Any]:
147 """What an install did (or a dry run would do) to rules already in the
148 policy, for the durable record.
149
150 Everything else in these details is a count, because the artifact can be
151 read back from the package. A removed permission rule cannot: once it is
152 out of the policy this log is the only place that says what it was, and
153 "an upgrade took a grant away" is exactly the event an operator comes
154 here to reconstruct. So a rule that is removed or changes hands is kept
155 whole. That happens once per rule, so it is bounded by the number of
156 rules packages ever retire. A rule that was only LEFT in place is
157 reported again by every install until somebody deals with it, so those
158 are counted, not copied (GET /permissions/unshipped lists them in full).
159
160 Both keys are absent when there is nothing to say, which is every
161 install that retires nothing.
162 """
163 if not isinstance(entries, list):
164 return {}
165 changed = []
166 kept: dict[str, int] = {}
167 for entry in entries:
168 if not isinstance(entry, Mapping):
169 continue
170 if entry.get("action") == "keep":
171 because = str(entry.get("because") or "kept")
172 kept[because] = kept.get(because, 0) + 1
173 else:
174 changed.append(_json_safe_value(dict(entry)))
175 details: dict[str, Any] = {}
176 if changed:
177 details["permission_retractions"] = changed
178 if kept:
179 details["permission_rules_kept"] = kept
180 return details
181
182
183def _plan_counts(plan: Mapping[str, Any], summary: Mapping[str, Any]) -> dict[str, Any]:
184 return {
185 "package": {
186 "id": summary.get("id"),
187 "name": summary.get("name"),
188 "version": summary.get("version"),
189 },
190 "safe_to_install": bool(plan.get("safe_to_install")),
191 "install_enabled": bool(plan.get("install_enabled")),
192 "objects": _action_counts(plan.get("objects")),
193 "schemas": _action_counts(plan.get("schemas")),
194 "permissions": _action_counts(plan.get("permissions")),
195 "seed": _action_counts(plan.get("seed")),
196 "migrations": _action_counts(plan.get("migrations")),
197 "schedules": _action_counts(plan.get("schedules")),
198 "nav": _action_counts(plan.get("nav")),
199 "attention": _action_counts(plan.get("attention")),
200 "warnings": _string_list(plan.get("warnings")),
201 }
202
203
204def _read_changes(path: Path) -> list[dict[str, Any]]:
205 if not path.exists():
206 return []
207
208 changes: list[dict[str, Any]] = []
209 with _file_lock(path):
210 for line in path.read_text(encoding="utf-8").splitlines():
211 if not line.strip():
212 continue
213 try:
214 entry = json.loads(line)
215 except json.JSONDecodeError:
216 continue
217 if isinstance(entry, dict):
218 changes.append(entry)
219
220 changes.reverse()
221 return changes
222
223
224def _action_counts(entries: Any) -> dict[str, int]:
225 counts: dict[str, int] = {}
226 if not isinstance(entries, list):
227 return counts
228 for entry in entries:
229 if not isinstance(entry, Mapping):
230 continue
231 action = entry.get("action")
232 if not isinstance(action, str) or not action:
233 continue
234 counts[action] = counts.get(action, 0) + 1
235 return counts
236
237
238def _normalize_details(details: Mapping[str, Any] | None) -> dict[str, Any]:
239 if details is None:
240 return {}
241 if not isinstance(details, Mapping):
242 raise InvalidPackageChangeError("Package change details must be an object")
243 return {str(key): _json_safe_value(value) for key, value in details.items()}
244
245
246def _json_safe_value(value: Any) -> Any:
247 if value is None or isinstance(value, str | int | float | bool):
248 return value
249 if isinstance(value, Mapping):
250 return {str(key): _json_safe_value(item) for key, item in value.items()}
251 if isinstance(value, list | tuple):
252 return [_json_safe_value(item) for item in value]
253 return str(value)
254
255
256def _string_list(value: Any) -> list[str]:
257 if not isinstance(value, list):
258 return []
259 return [str(item) for item in value]
260
261
262def _validate_page(*, limit: int, offset: int) -> None:
263 if limit < 1:
264 raise ValueError("limit must be at least 1")
265 if limit > MAX_CHANGE_LIMIT:
266 raise ValueError(f"limit must be at most {MAX_CHANGE_LIMIT}")
267 if offset < 0:
268 raise ValueError("offset must be at least 0")
269
270
271def _clean_optional_text(value: str | None) -> str | None:
272 if value is None:
273 return None
274 text = str(value).strip()
275 return text or None
276
277
278def _clean_text(value: str, *, default: str) -> str:
279 text = str(value).strip()
280 return text or default
281
282
283def _clean_change_id(value: str) -> str:
284 text = str(value).strip()
285 if not text:
286 raise InvalidPackageChangeError("Package change id must not be empty")
287 if len(text) > 256 or any(ord(character) < 32 for character in text):
288 raise InvalidPackageChangeError("Package change id is not safe")
289 return text
290
291
292def _default_message(action: str) -> str:
293 return {
294 "dry_run": "Dry run package install",
295 "install_requested": "Requested package install",
296 "installed": "Installed package",
297 "restore_requested": "Requested package restore",
298 "failed": "Package operation failed",
299 "rolled_back": "Rolled back package",
300 }[action]
301
302
303def _change_id(timestamp: str, package_id: str, action: str) -> str:
304 return object_ids.new_uuid4()
305
306
307def _utc_timestamp() -> str:
308 return datetime.now(timezone.utc).isoformat()
309
310
311def _file_lock(path: Path) -> threading.Lock:
312 key = str(path.resolve(strict=False))
313 with _LOCKS_GUARD:
314 lock = _LOCKS.get(key)
315 if lock is None:
316 lock = threading.Lock()
317 _LOCKS[key] = lock
318 return lock