askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
object_packages.py · 147.2 KB · 3421 lines
| 1 | """DBBASIC package manifest discovery, dry-run planning, and gated installs. |
| 2 | |
| 3 | Packages are installable bundles of objects, schemas, permissions, seed data, |
| 4 | and migrations. Installs are intentionally conservative: object and schema files |
| 5 | can be created or replaced, seed files can be created, and permissions/migrations |
| 6 | wait for explicit merge/run semantics. |
| 7 | """ |
| 8 | |
| 9 | from __future__ import annotations |
| 10 | |
| 11 | import csv |
| 12 | import io |
| 13 | import json |
| 14 | import os |
| 15 | import re |
| 16 | import tempfile |
| 17 | from dataclasses import replace |
| 18 | from pathlib import Path |
| 19 | from typing import Any, Callable, Iterable, Mapping |
| 20 | |
| 21 | import object_attention |
| 22 | import object_collections |
| 23 | import object_namespace |
| 24 | import object_package_baselines |
| 25 | import object_permission_store |
| 26 | import object_permissions |
| 27 | import object_reconciles |
| 28 | import object_record_changes |
| 29 | import object_records |
| 30 | import object_schemas |
| 31 | import object_source |
| 32 | import object_state |
| 33 | from object_namespace import get_object_roots, object_id_from_path, resolve_object_id, validate_object_id |
| 34 | from object_versions import DEFAULT_DATA_DIR |
| 35 | |
| 36 | PACKAGES_DIR = "packages" |
| 37 | MANIFEST_FILE = "dbbasic-package.json" |
| 38 | # The DRON this server reads (docs/dron.md, "Versioning"): a manifest's |
| 39 | # optional `dron` key may name this version or an earlier minor of the same |
| 40 | # major. Raise it with every change to the files in dron/. |
| 41 | DRON_VERSION = "0.2" |
| 42 | _DRON_VERSION_RE = re.compile(r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)") |
| 43 | PACKAGE_MIGRATIONS_DIR = "package_migrations" |
| 44 | |
| 45 | _PACKAGE_ID_RE = re.compile(r"^[a-z][a-z0-9_-]{0,63}$") |
| 46 | _VERSION_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$") |
| 47 | _MIGRATION_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$") |
| 48 | |
| 49 | # A package's `schedules` become task_* rows in the scheduler trigger's |
| 50 | # state, which is where object_daemon.process_scheduler reads them from. |
| 51 | # Before this existed, every recurring pass on a running server had been |
| 52 | # hand-entered into that state and appeared NOWHERE in the repository, so |
| 53 | # rebuilding a box silently lost its daily work -- exactly what the |
| 54 | # scheduler object's own docstring warns about. A schedule is part of what |
| 55 | # an app IS, so it ships with the app. |
| 56 | SCHEDULER_OBJECT_ID = "scheduler" |
| 57 | _TASK_KEY_PREFIX = "task_" |
| 58 | _SCHEDULE_ID_RE = re.compile(r"^[a-z][a-z0-9_]{0,63}$") |
| 59 | _SCHEDULE_TYPES = ("cron", "onetime") |
| 60 | _SCHEDULE_METHODS = ("POST", "GET", "PUT", "DELETE") |
| 61 | # Fields the daemon stamps back onto a task as it runs. An install must |
| 62 | # never touch them: they are the record of what actually happened, and a |
| 63 | # package upgrade is not a reason to forget it (doctrine #8 -- independent |
| 64 | # evidence is never edited). |
| 65 | _SCHEDULE_RUNTIME_FIELDS = ("next_run", "last_run", "run_count") |
| 66 | |
| 67 | # A package's `nav` entries become rows in the `nav_entries` collection, |
| 68 | # which is where every navigation surface reads its doors from. |
| 69 | # Before this existed there were THREE hand-maintained lists of the same |
| 70 | # apps -- a JS array in site_nav, a Python tuple in site_home, and a |
| 71 | # collection->URL map for search hits -- and they had already drifted: |
| 72 | # 25 entries, 21 entries, and no mention at all of shop, intake, billing, |
| 73 | # timers, banking, shipping, receiving or payments. A door is part of what |
| 74 | # an app IS, so it ships with the app, exactly like its schedule. |
| 75 | NAV_COLLECTION = "nav_entries" |
| 76 | _NAV_ID_RE = re.compile(r"^[a-z][a-z0-9_]{0,63}$") |
| 77 | _NAV_SURFACES = ("public", "member", "operator", "hidden") |
| 78 | _NAV_DEFAULT_GROUP = "Apps" |
| 79 | _NAV_DEFAULT_ORDER = 100 |
| 80 | # What the package OWNS: reinstalling restates every one of these. |
| 81 | _NAV_PACKAGE_FIELDS = ("label", "path", "blurb", "group", "surface", "order") |
| 82 | # What the OPERATOR owns. The package says what an app is; the operator |
| 83 | # says what they want to see. An install never touches this column, for |
| 84 | # the same reason it never restarts a paused schedule (doctrine #8 -- |
| 85 | # somebody else's deliberate decision is not an install's to revert). |
| 86 | _NAV_OPERATOR_FIELDS = ("operator_hidden",) |
| 87 | |
| 88 | # A package's `attention` entries become rows in the `attention_sources` |
| 89 | # collection, which is where the daemon's rollup pass reads its list of |
| 90 | # providers from and how a surface learns that a queue exists at all. |
| 91 | # Third use of the pattern that fixed cron (`schedules`) and navigation |
| 92 | # (`nav`), and for the same reason: this server is built out of gates and |
| 93 | # derived states, every one of which produces a queue of things a machine |
| 94 | # deliberately refused to decide -- scans `extracted`, time `submitted`, |
| 95 | # invoices overdue, bank lines unmatched. It has been computing those |
| 96 | # queues all along and throwing them away at the end of each pass; |
| 97 | # `system_scan_processor` literally returns a field named |
| 98 | # `needing_a_human` and nothing reads it. Only the package that owns a |
| 99 | # domain can honestly say what "needs a human" means in it, so the |
| 100 | # declaration ships with the app. |
| 101 | ATTENTION_COLLECTION = "attention_sources" |
| 102 | _ATTENTION_ID_RE = re.compile(r"^[a-z][a-z0-9_]{0,63}$") |
| 103 | _ATTENTION_COLLECTION_RE = re.compile(r"^[a-z][a-z0-9_]{0,63}$") |
| 104 | _ATTENTION_SEVERITIES = ("normal", "warning", "urgent") |
| 105 | _ATTENTION_DEFAULT_GROUP = "Apps" |
| 106 | _ATTENTION_DEFAULT_SEVERITY = "normal" |
| 107 | # What the package OWNS: reinstalling restates every one of these. |
| 108 | _ATTENTION_PACKAGE_FIELDS = ("object_id", "collection", "where", "detail", "reads", |
| 109 | "label", "path", "nav_id", "group", "severity") |
| 110 | # Written (and shown in a plan) only when set, or when clearing a value a |
| 111 | # previous version set: a provider entry with no `reads` plans and writes |
| 112 | # exactly as it always has. |
| 113 | _ATTENTION_OPTIONAL_FIELDS = ("collection", "where", "detail", "reads") |
| 114 | # What the OPERATOR owns. A deployment that does not care about a queue |
| 115 | # silences it here rather than by editing somebody else's manifest, and an |
| 116 | # install never writes this column -- same posture as nav's |
| 117 | # `operator_hidden` and a paused schedule (doctrine #8). |
| 118 | _ATTENTION_OPERATOR_FIELDS = ("operator_muted",) |
| 119 | |
| 120 | |
| 121 | class InvalidPackageIdError(ValueError): |
| 122 | """Raised when a package id is not safe for routes or storage.""" |
| 123 | |
| 124 | |
| 125 | class PackageNotFoundError(LookupError): |
| 126 | """Raised when a package directory or manifest is missing.""" |
| 127 | |
| 128 | |
| 129 | class InvalidPackageManifestError(ValueError): |
| 130 | """Raised when a package manifest is invalid.""" |
| 131 | |
| 132 | |
| 133 | class PackageInstallError(RuntimeError): |
| 134 | """Raised when a package install would be unsafe or unsupported.""" |
| 135 | |
| 136 | |
| 137 | def validate_package_id(package_id: str) -> bool: |
| 138 | """Return True when a package id is route-safe.""" |
| 139 | if not isinstance(package_id, str): |
| 140 | return False |
| 141 | return bool(_PACKAGE_ID_RE.fullmatch(package_id)) |
| 142 | |
| 143 | |
| 144 | def list_packages( |
| 145 | *, |
| 146 | root: Path | str = PACKAGES_DIR, |
| 147 | ) -> list[dict[str, Any]]: |
| 148 | """Return package summaries for all package manifests under root.""" |
| 149 | packages_root = Path(root) |
| 150 | if not packages_root.exists() or not packages_root.is_dir(): |
| 151 | return [] |
| 152 | |
| 153 | packages = [] |
| 154 | for path in sorted(packages_root.iterdir(), key=lambda item: item.name): |
| 155 | if not path.is_dir() or not validate_package_id(path.name): |
| 156 | continue |
| 157 | manifest_path = path / MANIFEST_FILE |
| 158 | if manifest_path.is_file(): |
| 159 | packages.append(_package_summary(_load_package(path.name, path))) |
| 160 | return packages |
| 161 | |
| 162 | |
| 163 | def get_package( |
| 164 | package_id: str, |
| 165 | *, |
| 166 | root: Path | str = PACKAGES_DIR, |
| 167 | ) -> dict[str, Any]: |
| 168 | """Return one normalized package manifest.""" |
| 169 | package_dir = _package_dir(package_id, root) |
| 170 | return _load_package(package_id, package_dir) |
| 171 | |
| 172 | |
| 173 | DATA_DIR_ENV = "DBBASIC_DATA_DIR" |
| 174 | |
| 175 | |
| 176 | def resolve_base_dir(base_dir: Path | str | None = None) -> Path: |
| 177 | """The data directory an install should write to. |
| 178 | |
| 179 | An explicit `base_dir` always wins. Otherwise the ENVIRONMENT decides, |
| 180 | because `DBBASIC_DATA_DIR` is the one authoritative statement of where |
| 181 | this server's data lives -- it is what the server itself reads, what |
| 182 | every package object reads, and what the systemd unit sets. |
| 183 | |
| 184 | This used to fall straight through to the literal "data", ignoring the |
| 185 | environment even when it was set to somewhere else entirely. The result |
| 186 | was the worst shape a bug can take: an install that reported |
| 187 | `"status": "written"` for every schema and seed, having written them |
| 188 | into a freshly created `./data` beside the checkout that nothing reads. |
| 189 | Nothing failed, nothing warned, and the package was simply absent from |
| 190 | the running server. Hit twice in one afternoon on a box whose layout was |
| 191 | well understood, which is the argument for fixing the default rather |
| 192 | than remembering harder. |
| 193 | |
| 194 | Callers that genuinely want a relative "data" can still ask for it by |
| 195 | name; what they can no longer do is get it by accident. |
| 196 | """ |
| 197 | if base_dir is not None: |
| 198 | return Path(base_dir) |
| 199 | return Path(os.environ.get(DATA_DIR_ENV) or DEFAULT_DATA_DIR) |
| 200 | |
| 201 | |
| 202 | def dry_run_package( |
| 203 | package_id: str, |
| 204 | *, |
| 205 | root: Path | str = PACKAGES_DIR, |
| 206 | base_dir: Path | str | None = None, |
| 207 | object_roots: Iterable[Path] | None = None, |
| 208 | ) -> dict[str, Any]: |
| 209 | """Return a non-mutating package install plan.""" |
| 210 | package_dir = _package_dir(package_id, root) |
| 211 | package = _load_package(package_id, package_dir) |
| 212 | base = resolve_base_dir(base_dir) |
| 213 | |
| 214 | warnings: list[str] = [] |
| 215 | objects = [ |
| 216 | _object_change(entry, package_dir=package_dir, object_roots=object_roots, warnings=warnings) |
| 217 | for entry in package["objects"] |
| 218 | ] |
| 219 | schemas = [ |
| 220 | _schema_change(entry, package_dir=package_dir, base_dir=base, warnings=warnings) |
| 221 | for entry in package["schemas"] |
| 222 | ] |
| 223 | permissions = [ |
| 224 | _permission_change( |
| 225 | entry, |
| 226 | package_id=package_id, |
| 227 | package_dir=package_dir, |
| 228 | base_dir=base, |
| 229 | warnings=warnings, |
| 230 | ) |
| 231 | for entry in package["permissions"] |
| 232 | ] |
| 233 | # What the install would do to rules ALREADY in the policy: the ones this |
| 234 | # package no longer ships (see _permission_retractions). A fragment that |
| 235 | # cannot be read has already put its warning above; an unreadable policy |
| 236 | # is the install's error to raise, as it is for the merge counts. |
| 237 | permission_retractions: list[dict[str, Any]] = [] |
| 238 | try: |
| 239 | shipped_rules, retracted_rules = _package_permission_rules( |
| 240 | package, package_dir, package_id=package_id) |
| 241 | permission_retractions, _ = _plan_permission_retractions( |
| 242 | package_id, |
| 243 | shipped=shipped_rules, |
| 244 | retracted=retracted_rules, |
| 245 | baseline=object_package_baselines.load_baseline(package_id, base_dir=base), |
| 246 | policy=object_permission_store.load_policy(base), |
| 247 | base_dir=base, |
| 248 | ) |
| 249 | except PackageInstallError as exc: |
| 250 | if str(exc) not in warnings: |
| 251 | warnings.append(str(exc)) |
| 252 | except ValueError: |
| 253 | pass |
| 254 | seed = [ |
| 255 | _seed_change(entry, package_dir=package_dir, base_dir=base, warnings=warnings) |
| 256 | for entry in package["seed"] |
| 257 | ] |
| 258 | migrations = [ |
| 259 | _migration_change(entry, package=package_id, package_dir=package_dir, base_dir=base, warnings=warnings) |
| 260 | for entry in package["migrations"] |
| 261 | ] |
| 262 | # A schedule may name an object this same install is about to write, so |
| 263 | # "does the target exist" is asked of the union of what is already |
| 264 | # resolvable and what this package provides -- not of the server as it |
| 265 | # stands right now. |
| 266 | existing_tasks = _load_scheduler_tasks(base) |
| 267 | installable_object_ids = {entry["id"] for entry in package["objects"]} |
| 268 | roots_for_lookup = list(object_roots) if object_roots is not None else get_object_roots() |
| 269 | for entry in package["schedules"] + package["attention"]: |
| 270 | if not entry["object_id"] or entry["object_id"] in installable_object_ids: |
| 271 | continue |
| 272 | if resolve_object_id(entry["object_id"], roots_for_lookup) is not None: |
| 273 | installable_object_ids.add(entry["object_id"]) |
| 274 | schedules = [ |
| 275 | _schedule_change( |
| 276 | entry, |
| 277 | existing=existing_tasks, |
| 278 | installable_object_ids=installable_object_ids, |
| 279 | warnings=warnings, |
| 280 | ) |
| 281 | for entry in package["schedules"] |
| 282 | ] |
| 283 | # Nav entries are compared against what is already registered, which |
| 284 | # is how "two packages claim one door" becomes visible before either |
| 285 | # of them lands. A missing nav_entries collection reads as "nothing |
| 286 | # registered yet", so the plan is create-everything rather than an |
| 287 | # error -- app-nav is not a dependency of being installable. |
| 288 | registered_nav = _load_nav_entries(base, roots=object_roots) or {} |
| 289 | nav = [ |
| 290 | _nav_change(entry, existing=registered_nav, package_id=package_id, warnings=warnings) |
| 291 | for entry in package["nav"] |
| 292 | ] |
| 293 | # Attention sources compare the same way nav entries do, and against |
| 294 | # the same missing-collection posture: app-nav absent reads as |
| 295 | # "nothing declared yet" rather than an error, because a package must |
| 296 | # not fail to install because the home screen is not installed. |
| 297 | registered_attention = _load_attention_sources(base, roots=object_roots) or {} |
| 298 | # A declared count is aimed at a collection the way a provider is aimed |
| 299 | # at an object, and it is asked the same question: will it exist once |
| 300 | # this install is done -- this package's own schemas, or one already |
| 301 | # installed here. |
| 302 | installable_collections = {entry["collection"] for entry in package["schemas"]} |
| 303 | attention = [ |
| 304 | _attention_change( |
| 305 | entry, |
| 306 | existing=registered_attention, |
| 307 | package_id=package_id, |
| 308 | installable_object_ids=installable_object_ids, |
| 309 | installable_collections=installable_collections, |
| 310 | base_dir=base, |
| 311 | warnings=warnings, |
| 312 | ) |
| 313 | for entry in package["attention"] |
| 314 | ] |
| 315 | |
| 316 | return { |
| 317 | "package": _package_summary(package), |
| 318 | "mode": "dry_run", |
| 319 | "install_enabled": False, |
| 320 | "safe_to_install": not warnings, |
| 321 | # WHERE, resolved and absolute. Every entry below reports a |
| 322 | # `destination` relative to this, and a status of "written" means |
| 323 | # nothing at all without knowing which tree it was written into -- |
| 324 | # an install can succeed completely into a directory the running |
| 325 | # server does not read. |
| 326 | "data_dir": str(base.resolve()), |
| 327 | "objects": objects, |
| 328 | "schemas": schemas, |
| 329 | "permissions": permissions, |
| 330 | "permission_retractions": permission_retractions, |
| 331 | "seed": seed, |
| 332 | "migrations": migrations, |
| 333 | "schedules": schedules, |
| 334 | "nav": nav, |
| 335 | "attention": attention, |
| 336 | "warnings": warnings, |
| 337 | } |
| 338 | |
| 339 | |
| 340 | def install_package( |
| 341 | package_id: str, |
| 342 | *, |
| 343 | root: Path | str = PACKAGES_DIR, |
| 344 | base_dir: Path | str | None = None, |
| 345 | object_roots: Iterable[Path] | None = None, |
| 346 | allow_replace: bool = False, |
| 347 | force: bool = False, |
| 348 | before_write: Callable[[Mapping[str, Any]], Mapping[str, Any] | None] | None = None, |
| 349 | ) -> dict[str, Any]: |
| 350 | """Install a package using the conservative public write contract. |
| 351 | |
| 352 | On an upgrade (an object/schema that already exists), writes are no |
| 353 | longer blind: each artifact is three-way compared against its recorded |
| 354 | baseline (see object_package_baselines) and its live content. Pristine |
| 355 | artifacts fast-forward, customized-but-unchanged artifacts are kept, and |
| 356 | genuine conflicts are parked as pending-reconcile records (never |
| 357 | overwritten) unless force=True. See docs/upgrade-and-customization.md |
| 358 | (Rule 1: Reconcile, Don't Replace). |
| 359 | """ |
| 360 | # force implies allow_replace: forcing only makes sense when you may |
| 361 | # touch existing artifacts, so the replace-without-allow_replace blocker |
| 362 | # still applies unless force is also set. |
| 363 | allow_replace = allow_replace or force |
| 364 | roots = list(object_roots) if object_roots is not None else get_object_roots() |
| 365 | if not roots: |
| 366 | raise PackageInstallError("Package installs require at least one object root") |
| 367 | |
| 368 | package_dir = _package_dir(package_id, root) |
| 369 | package = _load_package(package_id, package_dir) |
| 370 | base = resolve_base_dir(base_dir) |
| 371 | plan = dry_run_package(package_id, root=root, base_dir=base, object_roots=roots) |
| 372 | |
| 373 | blockers = _install_blockers(plan, package=package, allow_replace=allow_replace) |
| 374 | if blockers: |
| 375 | raise PackageInstallError("; ".join(blockers)) |
| 376 | |
| 377 | object_writes = [] |
| 378 | for entry, planned in zip(package["objects"], plan["objects"], strict=True): |
| 379 | source = _package_file(package_dir, entry["path"]) |
| 380 | existing = resolve_object_id(entry["id"], roots) |
| 381 | # An object that already exists stays where it lives -- a customized |
| 382 | # object must not be yanked out of the override root by an upgrade. |
| 383 | # |
| 384 | # A NEW object goes to the LAST root, which is the base/system root: |
| 385 | # get_object_roots() returns [override, base] in LOOKUP order, so |
| 386 | # roots[0] is the override root, and installing there was silently |
| 387 | # wrong. object_namespace.get_base_object_roots says so directly -- |
| 388 | # "the root packages install into and reconcile against ... the |
| 389 | # pristine, upgradeable copy" -- but this line used roots[0] and |
| 390 | # contradicted it. The consequence was not cosmetic: iter_object_sources |
| 391 | # labels anything under the override root kind="override", and |
| 392 | # object_handlers.build_index indexes ONLY kind=="system" (Decision 2, |
| 393 | # user-authored handlers deferred). So every package-installed object |
| 394 | # declaring HANDLES installed successfully, reported "written", and |
| 395 | # then never received a single event. |
| 396 | # |
| 397 | # With one root configured (no overrides) this is the same root it |
| 398 | # always was. |
| 399 | destination_root = (_root_for_path(existing, roots) if existing is not None |
| 400 | else roots[-1]) |
| 401 | if destination_root is None: |
| 402 | raise PackageInstallError(f"Existing object is outside configured object roots: {entry['id']}") |
| 403 | destination = existing or _object_destination(entry, destination_root) |
| 404 | _ensure_inside(destination, destination_root, label="object") |
| 405 | try: |
| 406 | mapped_id = object_id_from_path(destination, destination_root) |
| 407 | except ValueError as exc: |
| 408 | raise PackageInstallError( |
| 409 | f"Package object path is not a valid object destination: {entry['path']}" |
| 410 | ) from exc |
| 411 | if mapped_id != entry["id"]: |
| 412 | raise PackageInstallError( |
| 413 | f"Package object path does not map to object id {entry['id']}: {entry['path']}" |
| 414 | ) |
| 415 | object_writes.append((planned, destination, destination_root, source.read_bytes())) |
| 416 | |
| 417 | schema_writes = [] |
| 418 | for entry, planned in zip(package["schemas"], plan["schemas"], strict=True): |
| 419 | source = _package_file(package_dir, entry["path"]) |
| 420 | try: |
| 421 | payload = json.loads(source.read_text(encoding="utf-8")) |
| 422 | except json.JSONDecodeError as exc: |
| 423 | raise PackageInstallError(f"Package schema contains invalid JSON: {entry['path']}") from exc |
| 424 | try: |
| 425 | normalized = object_schemas.normalize_declaration(entry["collection"], payload) |
| 426 | except ValueError as exc: |
| 427 | raise PackageInstallError(f"Package schema is invalid: {entry['path']}: {exc}") from exc |
| 428 | schema_writes.append((entry, planned, normalized)) |
| 429 | |
| 430 | seed_writes = [] |
| 431 | for entry, planned in zip(package["seed"], plan["seed"], strict=True): |
| 432 | source = _package_file(package_dir, entry["path"]) |
| 433 | destination = base / "collections" / entry["collection"] / "records.tsv" |
| 434 | _ensure_inside(destination, base / "collections", label="seed") |
| 435 | seed_writes.append((entry, planned, destination, source.read_bytes())) |
| 436 | |
| 437 | permission_writes = [] |
| 438 | for entry, planned in zip(package["permissions"], plan["permissions"], strict=True): |
| 439 | rules = _load_permission_rules(package_dir, entry, package_id=package_id) |
| 440 | permission_writes.append((planned, rules)) |
| 441 | shipped_rules, retracted_rules = _package_permission_rules( |
| 442 | package, package_dir, package_id=package_id) |
| 443 | |
| 444 | restore_point = before_write(plan) if before_write is not None else None |
| 445 | |
| 446 | existing_baseline = object_package_baselines.load_baseline(package_id, base_dir=base) or {} |
| 447 | base_objects = existing_baseline.get("objects") or {} |
| 448 | base_schemas = existing_baseline.get("schemas") or {} |
| 449 | base_schema_bodies = existing_baseline.get("schema_bodies") or {} |
| 450 | baseline_version = existing_baseline.get("version") |
| 451 | |
| 452 | reconciles: list[str] = [] |
| 453 | new_baseline_objects: dict[str, str] = {} |
| 454 | new_baseline_schemas: dict[str, str] = {} |
| 455 | new_baseline_schema_bodies: dict[str, Any] = {} |
| 456 | |
| 457 | installed_objects = [] |
| 458 | for planned, destination, destination_root, content in object_writes: |
| 459 | object_id = planned["id"] |
| 460 | extra: dict[str, Any] = {} |
| 461 | |
| 462 | if planned["action"] == "create": |
| 463 | _write_file_atomic_bytes(destination, content) |
| 464 | status = "written" |
| 465 | new_baseline_objects[object_id] = object_package_baselines.sha256_text(content.decode("utf-8")) |
| 466 | else: |
| 467 | new_text = content.decode("utf-8") |
| 468 | new_sha = object_package_baselines.sha256_text(new_text) |
| 469 | live_text = object_source.get_object_source(object_id, roots) |
| 470 | live_sha = object_package_baselines.sha256_text(live_text) |
| 471 | old_sha = base_objects.get(object_id) |
| 472 | |
| 473 | if live_sha == new_sha: |
| 474 | status = "unchanged" |
| 475 | new_baseline_objects[object_id] = new_sha |
| 476 | elif old_sha is not None and live_sha == old_sha: |
| 477 | _write_file_atomic_bytes(destination, content) |
| 478 | status = "updated" |
| 479 | new_baseline_objects[object_id] = new_sha |
| 480 | elif old_sha is not None and new_sha == old_sha: |
| 481 | status = "kept" |
| 482 | new_baseline_objects[object_id] = old_sha |
| 483 | elif force: |
| 484 | _write_file_atomic_bytes(destination, content) |
| 485 | status = "forced" |
| 486 | new_baseline_objects[object_id] = new_sha |
| 487 | else: |
| 488 | rec = object_reconciles.create_reconcile( |
| 489 | package=package_id, |
| 490 | target_version=package["version"], |
| 491 | baseline_version=baseline_version, |
| 492 | artifact={"kind": "object", "id": object_id}, |
| 493 | mine=live_text, |
| 494 | theirs=new_text, |
| 495 | base_sha=old_sha, |
| 496 | base_dir=base, |
| 497 | ) |
| 498 | reconciles.append(rec["id"]) |
| 499 | status = "conflict" |
| 500 | extra["reconcile_id"] = rec["id"] |
| 501 | new_baseline_objects[object_id] = old_sha if old_sha is not None else live_sha |
| 502 | |
| 503 | installed_objects.append( |
| 504 | { |
| 505 | **planned, |
| 506 | "status": status, |
| 507 | "destination": _relative_display_path(destination, destination_root), |
| 508 | **extra, |
| 509 | } |
| 510 | ) |
| 511 | |
| 512 | installed_schemas = [] |
| 513 | for entry, planned, normalized in schema_writes: |
| 514 | collection = entry["collection"] |
| 515 | new_sha = object_package_baselines.canonical_schema_hash(normalized) |
| 516 | extra: dict[str, Any] = {} |
| 517 | |
| 518 | live = None |
| 519 | if planned["action"] == "replace": |
| 520 | try: |
| 521 | live = object_schemas.get_schema(collection, base_dir=base, roots=roots) |
| 522 | except object_schemas.SchemaNotFoundError: |
| 523 | live = None |
| 524 | |
| 525 | if live is None: |
| 526 | object_schemas.replace_schema(collection, normalized, base_dir=base) |
| 527 | status = "written" |
| 528 | new_baseline_schemas[collection] = new_sha |
| 529 | new_baseline_schema_bodies[collection] = normalized |
| 530 | else: |
| 531 | live_sha = object_package_baselines.canonical_schema_hash(live) |
| 532 | old_sha = base_schemas.get(collection) |
| 533 | base_body = base_schema_bodies.get(collection) |
| 534 | |
| 535 | if live_sha == new_sha: |
| 536 | status = "unchanged" |
| 537 | new_baseline_schemas[collection] = new_sha |
| 538 | new_baseline_schema_bodies[collection] = normalized |
| 539 | elif old_sha is not None and live_sha == old_sha: |
| 540 | object_schemas.replace_schema(collection, normalized, base_dir=base) |
| 541 | status = "updated" |
| 542 | new_baseline_schemas[collection] = new_sha |
| 543 | new_baseline_schema_bodies[collection] = normalized |
| 544 | elif old_sha is not None and new_sha == old_sha: |
| 545 | status = "kept" |
| 546 | new_baseline_schemas[collection] = old_sha |
| 547 | new_baseline_schema_bodies[collection] = normalized |
| 548 | elif force: |
| 549 | object_schemas.replace_schema(collection, normalized, base_dir=base) |
| 550 | status = "forced" |
| 551 | new_baseline_schemas[collection] = new_sha |
| 552 | new_baseline_schema_bodies[collection] = normalized |
| 553 | elif base_body is not None: |
| 554 | # Customized AND shipped changed: try a field-union merge |
| 555 | # before parking a conflict (Rule 3: schemas are additive, |
| 556 | # so a same-named field changed on both sides is the only |
| 557 | # real conflict -- see docs/upgrade-and-customization.md). |
| 558 | merged, collisions = object_schemas.merge_schema_fields(base_body, live, normalized) |
| 559 | if not collisions: |
| 560 | object_schemas.replace_schema(collection, merged, base_dir=base) |
| 561 | status = "merged" |
| 562 | new_baseline_schemas[collection] = new_sha |
| 563 | new_baseline_schema_bodies[collection] = normalized |
| 564 | else: |
| 565 | rec = object_reconciles.create_reconcile( |
| 566 | package=package_id, |
| 567 | target_version=package["version"], |
| 568 | baseline_version=baseline_version, |
| 569 | artifact={"kind": "schema", "collection": collection}, |
| 570 | mine=json.dumps(live, indent=2, sort_keys=True), |
| 571 | theirs=json.dumps(normalized, indent=2, sort_keys=True), |
| 572 | base_sha=old_sha, |
| 573 | base_dir=base, |
| 574 | collisions=collisions, |
| 575 | ) |
| 576 | reconciles.append(rec["id"]) |
| 577 | status = "conflict" |
| 578 | extra["reconcile_id"] = rec["id"] |
| 579 | extra["collisions"] = collisions |
| 580 | new_baseline_schemas[collection] = old_sha if old_sha is not None else live_sha |
| 581 | new_baseline_schema_bodies[collection] = base_body |
| 582 | else: |
| 583 | # No base schema body on record (baseline predates this |
| 584 | # feature, or was never stamped): fall back to parking a |
| 585 | # conflict, unchanged from prior behavior. |
| 586 | rec = object_reconciles.create_reconcile( |
| 587 | package=package_id, |
| 588 | target_version=package["version"], |
| 589 | baseline_version=baseline_version, |
| 590 | artifact={"kind": "schema", "collection": collection}, |
| 591 | mine=json.dumps(live, indent=2, sort_keys=True), |
| 592 | theirs=json.dumps(normalized, indent=2, sort_keys=True), |
| 593 | base_sha=old_sha, |
| 594 | base_dir=base, |
| 595 | ) |
| 596 | reconciles.append(rec["id"]) |
| 597 | status = "conflict" |
| 598 | extra["reconcile_id"] = rec["id"] |
| 599 | new_baseline_schemas[collection] = old_sha if old_sha is not None else live_sha |
| 600 | if base_body is not None: |
| 601 | new_baseline_schema_bodies[collection] = base_body |
| 602 | |
| 603 | installed_schemas.append( |
| 604 | { |
| 605 | **planned, |
| 606 | "status": status, |
| 607 | "destination": f"schemas/{collection}.json", |
| 608 | **extra, |
| 609 | } |
| 610 | ) |
| 611 | |
| 612 | installed_seed = [] |
| 613 | seed_warnings: list[str] = [] |
| 614 | # Which seed ids each collection already held BEFORE this install wrote |
| 615 | # anything: the rows an upgrade may refresh, as against the rows this |
| 616 | # install just created (see _reconcile_seed_rows). |
| 617 | seed_preexisting: dict[str, set[str]] = {} |
| 618 | for entry, planned, _destination, _content in seed_writes: |
| 619 | if planned.get("installed"): |
| 620 | try: |
| 621 | seed_preexisting.setdefault(entry["collection"], set()).update( |
| 622 | str(row.get("id") or "") |
| 623 | for row in object_records.read_collection_records( |
| 624 | entry["collection"], base_dir=base)) |
| 625 | except Exception: # noqa: BLE001 -- unreadable: nothing is refreshed |
| 626 | seed_preexisting.setdefault(entry["collection"], set()) |
| 627 | for entry, planned, destination, content in seed_writes: |
| 628 | # Seed into a collection that already holds records: MERGE by id rather |
| 629 | # than skip. Add only the seed rows whose id isn't already present; |
| 630 | # existing rows (live data, possibly customized) are never touched. This |
| 631 | # is what lets several packages each seed a SHARED collection |
| 632 | # (views/site_routes) -- previously only the first-installed package's |
| 633 | # seed landed and every later one was skipped (needing manual inserts). |
| 634 | # A fresh collection (no records yet) still takes the whole seed file. |
| 635 | if planned.get("installed"): |
| 636 | added, rejected = _merge_seed_rows( |
| 637 | entry["collection"], content, base_dir=base, package_id=package_id |
| 638 | ) |
| 639 | reason = ( |
| 640 | f"merged {added} new row(s); existing preserved" |
| 641 | if added else "collection already has these rows; preserved" |
| 642 | ) |
| 643 | if rejected: |
| 644 | reason = ( |
| 645 | f"merged {added} new row(s); {len(rejected)} seed row(s) refused " |
| 646 | f"by the collection and not merged (see rejected); existing preserved" |
| 647 | ) |
| 648 | seed_warnings.append( |
| 649 | f"Seed {entry['collection']}: {len(rejected)} row(s) refused and not " |
| 650 | f"merged: " + ", ".join( |
| 651 | f"{row['id'] or '?'} ({row['code']})" for row in rejected[:10]) |
| 652 | + (" ..." if len(rejected) > 10 else "") |
| 653 | ) |
| 654 | installed_seed.append( |
| 655 | { |
| 656 | **planned, |
| 657 | "status": "merged" if added else "skipped", |
| 658 | "reason": reason, |
| 659 | "added": added, |
| 660 | "rejected": rejected, |
| 661 | "destination": f"collections/{entry['collection']}/records.tsv", |
| 662 | } |
| 663 | ) |
| 664 | continue |
| 665 | if _seed_meets_locked_checks(entry["collection"], content, base_dir=base): |
| 666 | # A collection whose schema declares locked_checks does not take |
| 667 | # its seed as a byte copy: each row is a write the checks decide |
| 668 | # (a seeded payment against a seeded invoice is checked against |
| 669 | # it like any other). Same result shape as a fresh copy. |
| 670 | added, rejected = _merge_seed_rows( |
| 671 | entry["collection"], content, base_dir=base, package_id=package_id |
| 672 | ) |
| 673 | if rejected: |
| 674 | seed_warnings.append( |
| 675 | f"Seed {entry['collection']}: {len(rejected)} row(s) refused and not " |
| 676 | f"written: " + ", ".join( |
| 677 | f"{row['id'] or '?'} ({row['code']})" for row in rejected[:10]) |
| 678 | + (" ..." if len(rejected) > 10 else "") |
| 679 | ) |
| 680 | installed_seed.append( |
| 681 | { |
| 682 | **planned, |
| 683 | "status": "written", |
| 684 | "added": added, |
| 685 | "rejected": rejected, |
| 686 | "destination": f"collections/{entry['collection']}/records.tsv", |
| 687 | } |
| 688 | ) |
| 689 | continue |
| 690 | _write_file_atomic_bytes(destination, content) |
| 691 | _attribute_seed_records(entry["collection"], package_id=package_id, base_dir=base) |
| 692 | written = { |
| 693 | **planned, |
| 694 | "status": "written", |
| 695 | "destination": f"collections/{entry['collection']}/records.tsv", |
| 696 | } |
| 697 | # A fresh collection takes the seed file byte for byte (the trusted |
| 698 | # package-author path; tests/test_package_schema_rules.py checks every |
| 699 | # shipped seed in CI). The file is not refused here, but two seed rows |
| 700 | # on one `unique` key are reported, so the install does not claim a |
| 701 | # clean collection that the next writer will trip over. |
| 702 | duplicates = _seed_unique_violations(entry["collection"], base_dir=base) |
| 703 | if duplicates is None: |
| 704 | seed_warnings.append( |
| 705 | f"Seed {entry['collection']}: its unique keys could not be checked " |
| 706 | f"after the seed was written." |
| 707 | ) |
| 708 | elif duplicates: |
| 709 | written["unique_violations"] = duplicates |
| 710 | seed_warnings.append( |
| 711 | f"Seed {entry['collection']}: {len(duplicates)} unique key(s) held by " |
| 712 | f"more than one seed row: " + "; ".join( |
| 713 | f"{', '.join(v['fields'])} on {', '.join(v['ids'])}" |
| 714 | for v in duplicates[:10]) |
| 715 | + (" ..." if len(duplicates) > 10 else "") |
| 716 | ) |
| 717 | installed_seed.append(written) |
| 718 | |
| 719 | # Seeded rows: refresh the ones an operator never touched, remember what |
| 720 | # every row looked like, and say what was left alone and why. |
| 721 | new_seed_baseline: dict[str, dict[str, Any]] = {} |
| 722 | previous_seed_rows = existing_baseline.get("seed_rows") or {} |
| 723 | for (entry, _planned, _destination, content), item in zip(seed_writes, installed_seed): |
| 724 | collection = entry["collection"] |
| 725 | replaced, kept, rows_baseline = _reconcile_seed_rows( |
| 726 | collection, content, base_dir=base, package_id=package_id, |
| 727 | previous=previous_seed_rows.get(collection) or {}, |
| 728 | preexisting=seed_preexisting.get(collection, set()), |
| 729 | ) |
| 730 | new_seed_baseline.setdefault(collection, {}).update(rows_baseline) |
| 731 | if replaced: |
| 732 | item["replaced"] = replaced |
| 733 | if item.get("status") == "skipped": |
| 734 | item["status"] = "merged" |
| 735 | item["reason"] = ( |
| 736 | f"{item.get('reason') or 'seed merged'}; refreshed {len(replaced)} " |
| 737 | f"row(s) an operator had not edited" |
| 738 | ) |
| 739 | if kept: |
| 740 | item["kept"] = kept |
| 741 | seed_warnings.append( |
| 742 | f"Seed {collection}: {len(kept)} row(s) differ from this version but were " |
| 743 | f"left as they are: " + ", ".join( |
| 744 | f"{row['id']} ({row['reason']}: {', '.join(row['columns'])})" |
| 745 | for row in kept[:10]) + (" ..." if len(kept) > 10 else "") |
| 746 | ) |
| 747 | |
| 748 | # Retire before merging: the rules this package used to ship and no |
| 749 | # longer does leave the policy first, then this version's are appended. |
| 750 | # The reverse order would leave a tightened rule in force beside the |
| 751 | # wide one it replaces between the two writes. |
| 752 | installed_retractions = _apply_permission_retractions( |
| 753 | package_id, |
| 754 | shipped=shipped_rules, |
| 755 | retracted=retracted_rules, |
| 756 | baseline=existing_baseline, |
| 757 | base_dir=base, |
| 758 | ) |
| 759 | |
| 760 | installed_permissions = [] |
| 761 | for planned, rules in permission_writes: |
| 762 | total, added = _merge_permission_rules(rules, base_dir=base) |
| 763 | installed_permissions.append( |
| 764 | { |
| 765 | **planned, |
| 766 | "status": "merged", |
| 767 | "rules": total, |
| 768 | "new_rules": added, |
| 769 | } |
| 770 | ) |
| 771 | |
| 772 | # Schedules land last: a task board that points at an object is only |
| 773 | # honest once that object is on disk. |
| 774 | installed_schedules = _apply_schedules( |
| 775 | package["schedules"], plan["schedules"], base_dir=base |
| 776 | ) |
| 777 | |
| 778 | # Nav lands after the seeds, because a package that ships the |
| 779 | # nav_entries schema itself (app-nav) has to have written it before |
| 780 | # its own doors can be registered. |
| 781 | installed_nav = _apply_nav( |
| 782 | package["nav"], plan["nav"], package_id=package_id, base_dir=base, roots=roots |
| 783 | ) |
| 784 | |
| 785 | # Attention sources land last of all, for the same reason schedules |
| 786 | # do: a counter that names an object is only honest once that object |
| 787 | # is on disk, and the row is what the daemon will start executing. |
| 788 | installed_attention = _apply_attention( |
| 789 | package["attention"], plan["attention"], package_id=package_id, |
| 790 | base_dir=base, roots=roots, root=root |
| 791 | ) |
| 792 | |
| 793 | object_package_baselines.record_baseline( |
| 794 | package_id, |
| 795 | version=package["version"], |
| 796 | objects=new_baseline_objects, |
| 797 | schemas=new_baseline_schemas, |
| 798 | schema_bodies=new_baseline_schema_bodies, |
| 799 | # What this version shipped, so the next install can retire what it |
| 800 | # no longer does (see _permission_retractions). |
| 801 | permissions=[_rule_baseline_payload(rule) for rule in shipped_rules], |
| 802 | seed_rows=new_seed_baseline, |
| 803 | # What this version declared, so installing app-nav later can |
| 804 | # register it (see _register_installed_declarations). |
| 805 | nav=package["nav"], |
| 806 | attention=package["attention"], |
| 807 | base_dir=base, |
| 808 | ) |
| 809 | |
| 810 | # Install order must not decide whether a package's doors and queues |
| 811 | # exist. A package installed before app-nav had its `nav` and |
| 812 | # `attention` reported as `skipped` -- with no warning, and an install |
| 813 | # that otherwise succeeded -- and nothing ever wrote them afterwards: |
| 814 | # three separate simulated-organisation runs installed their own package |
| 815 | # first and got an app with no menu entry and no attention count until |
| 816 | # somebody reinstalled it. So: an install that provides the registry |
| 817 | # (ships the nav_entries or attention_sources schema, i.e. app-nav) |
| 818 | # registers what every already-installed package declared, and an |
| 819 | # install whose own entries had to be skipped says so in `warnings`. |
| 820 | provides = {entry["collection"] for entry in package["schemas"]} |
| 821 | registered_for_others, declaration_warnings = _register_installed_declarations( |
| 822 | package_id, |
| 823 | nav=NAV_COLLECTION in provides, |
| 824 | attention=ATTENTION_COLLECTION in provides, |
| 825 | root=root, |
| 826 | base_dir=base, |
| 827 | roots=roots, |
| 828 | ) |
| 829 | seed_warnings.extend(declaration_warnings) |
| 830 | skipped_nav = [item for item in installed_nav if item.get("status") == "skipped"] |
| 831 | skipped_attention = [item for item in installed_attention if item.get("status") == "skipped"] |
| 832 | deferred_attention = [item for item in skipped_attention if item.get("stale_schema_owner")] |
| 833 | skipped_attention = [item for item in skipped_attention if not item.get("stale_schema_owner")] |
| 834 | if deferred_attention: |
| 835 | owner = deferred_attention[0]["stale_schema_owner"] |
| 836 | seed_warnings.append( |
| 837 | f"{package_id} declares {len(deferred_attention)} attention source" |
| 838 | f"{'' if len(deferred_attention) == 1 else 's'} not registered yet: the installed " |
| 839 | f"{ATTENTION_COLLECTION} schema is older than the one {owner} ships in this tree. " |
| 840 | f"Installing {owner} registers them; until then this app has no attention count." |
| 841 | ) |
| 842 | if skipped_nav or skipped_attention: |
| 843 | seed_warnings.append( |
| 844 | f"{package_id} declares {len(skipped_nav)} nav entr" |
| 845 | f"{'y' if len(skipped_nav) == 1 else 'ies'} and {len(skipped_attention)} " |
| 846 | f"attention source{'' if len(skipped_attention) == 1 else 's'} that were NOT " |
| 847 | f"registered: app-nav is not installed here ({NAV_COLLECTION} / " |
| 848 | f"{ATTENTION_COLLECTION} missing). Installing app-nav registers them; until " |
| 849 | f"then this app has no menu entry and no attention count." |
| 850 | ) |
| 851 | |
| 852 | result = { |
| 853 | "package": plan["package"], |
| 854 | "mode": "install", |
| 855 | "install_enabled": True, |
| 856 | "allow_replace": allow_replace, |
| 857 | "safe_to_install": True, |
| 858 | # The resolved data directory everything below landed in. Reported |
| 859 | # because "written" is not a claim anybody can check without it -- |
| 860 | # see resolve_base_dir for the afternoon that made this necessary. |
| 861 | "data_dir": plan["data_dir"], |
| 862 | "objects": installed_objects, |
| 863 | "schemas": installed_schemas, |
| 864 | "permissions": installed_permissions, |
| 865 | "permission_retractions": installed_retractions, |
| 866 | "seed": installed_seed, |
| 867 | "migrations": plan["migrations"], |
| 868 | "schedules": installed_schedules, |
| 869 | "nav": installed_nav, |
| 870 | "attention": installed_attention, |
| 871 | # Nav entries and attention sources of packages installed BEFORE |
| 872 | # this one, registered now because this install provided the |
| 873 | # registry. Each item names the package it belongs to. |
| 874 | "registered_for_others": registered_for_others, |
| 875 | "reconciles": reconciles, |
| 876 | "warnings": seed_warnings, |
| 877 | } |
| 878 | if restore_point is not None: |
| 879 | result["restore_point"] = dict(restore_point) |
| 880 | return result |
| 881 | |
| 882 | |
| 883 | def package_status( |
| 884 | package_id: str, |
| 885 | *, |
| 886 | root: Path | str = PACKAGES_DIR, |
| 887 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 888 | object_roots: Iterable[Path] | None = None, |
| 889 | ) -> dict[str, Any]: |
| 890 | """Return install/customization status for a package's baselined artifacts.""" |
| 891 | roots = list(object_roots) if object_roots is not None else get_object_roots() |
| 892 | base = Path(base_dir) |
| 893 | |
| 894 | package = _load_package(package_id, _package_dir(package_id, root)) |
| 895 | summary = _package_summary(package) |
| 896 | summary["pending_reconciles"] = object_reconciles.count_pending(base_dir=base, package=package_id) |
| 897 | |
| 898 | baseline = object_package_baselines.load_baseline(package_id, base_dir=base) |
| 899 | if baseline is None: |
| 900 | summary["installed"] = False |
| 901 | summary["customized"] = False |
| 902 | summary["artifacts"] = [] |
| 903 | return summary |
| 904 | |
| 905 | artifacts: list[dict[str, Any]] = [] |
| 906 | any_customized = False |
| 907 | |
| 908 | for object_id, base_sha in (baseline.get("objects") or {}).items(): |
| 909 | try: |
| 910 | live = object_source.get_object_source(object_id, roots) |
| 911 | except (FileNotFoundError, LookupError, OSError, ValueError, object_source.ObjectSourceError): |
| 912 | state = "removed" |
| 913 | else: |
| 914 | state = "pristine" if object_package_baselines.sha256_text(live) == base_sha else "customized" |
| 915 | if state == "customized": |
| 916 | any_customized = True |
| 917 | artifacts.append( |
| 918 | { |
| 919 | "kind": "object", |
| 920 | "id": object_id, |
| 921 | "state": state, |
| 922 | "overridden": object_namespace.has_override(object_id), |
| 923 | } |
| 924 | ) |
| 925 | |
| 926 | for collection, base_sha in (baseline.get("schemas") or {}).items(): |
| 927 | try: |
| 928 | live = object_schemas.get_schema(collection, base_dir=base, roots=roots) |
| 929 | except (object_schemas.SchemaNotFoundError, LookupError, OSError, ValueError): |
| 930 | state = "removed" |
| 931 | else: |
| 932 | state = ( |
| 933 | "pristine" |
| 934 | if object_package_baselines.canonical_schema_hash(live) == base_sha |
| 935 | else "customized" |
| 936 | ) |
| 937 | if state == "customized": |
| 938 | any_customized = True |
| 939 | artifacts.append({"kind": "schema", "collection": collection, "state": state}) |
| 940 | |
| 941 | summary["installed"] = True |
| 942 | summary["installed_version"] = baseline.get("version") |
| 943 | summary["customized"] = any_customized |
| 944 | summary["artifacts"] = artifacts |
| 945 | return summary |
| 946 | |
| 947 | |
| 948 | def _package_dir(package_id: str, root: Path | str) -> Path: |
| 949 | if not validate_package_id(package_id): |
| 950 | raise InvalidPackageIdError(f"Invalid package id: {package_id}") |
| 951 | |
| 952 | package_dir = Path(root) / package_id |
| 953 | manifest_path = package_dir / MANIFEST_FILE |
| 954 | if not package_dir.is_dir() or not manifest_path.is_file(): |
| 955 | raise PackageNotFoundError(f"Package not found: {package_id}") |
| 956 | return package_dir |
| 957 | |
| 958 | |
| 959 | def _load_package(package_id: str, package_dir: Path) -> dict[str, Any]: |
| 960 | manifest_path = package_dir / MANIFEST_FILE |
| 961 | try: |
| 962 | payload = json.loads(manifest_path.read_text()) |
| 963 | except json.JSONDecodeError as exc: |
| 964 | raise InvalidPackageManifestError(f"Package manifest contains invalid JSON: {package_id}") from exc |
| 965 | |
| 966 | return _normalize_manifest(package_id, payload) |
| 967 | |
| 968 | |
| 969 | def _refuse_unreadable_dron_version(package_id: str, payload: Mapping[str, Any]) -> None: |
| 970 | """A manifest's `dron` names the DRON it was written for. A later minor |
| 971 | may add what this server would drop, another major may mean something |
| 972 | else: either is refused before anything is read, so the author learns |
| 973 | the cause rather than the first section this server does not know. No |
| 974 | key means written before versions were declared, and is read as before. |
| 975 | Only a package declaration is held to this.""" |
| 976 | if "dron" not in payload: |
| 977 | return |
| 978 | value = payload["dron"] |
| 979 | where = f"Package {package_id} {MANIFEST_FILE}" |
| 980 | match = _DRON_VERSION_RE.fullmatch(value) if isinstance(value, str) else None |
| 981 | if match is None: |
| 982 | raise InvalidPackageManifestError( |
| 983 | f"{where}: dron {value!r} is not a DRON version; write the version the package " |
| 984 | f'was written for as "MAJOR.MINOR" text, for example "{DRON_VERSION}" ' |
| 985 | f"(this server reads DRON {DRON_VERSION})" |
| 986 | ) |
| 987 | asked = (int(match.group(1)), int(match.group(2))) |
| 988 | major, minor = (int(part) for part in DRON_VERSION.split(".")) |
| 989 | if asked[0] == major and asked[1] <= minor: |
| 990 | return |
| 991 | if asked[0] < major: |
| 992 | remedy = (f"update the package to DRON {major}.x, or install it on a server that reads " |
| 993 | f"DRON {value}") |
| 994 | else: |
| 995 | remedy = f"upgrade the server to one that reads DRON {value} to install it" |
| 996 | raise InvalidPackageManifestError( |
| 997 | f"{where}: the package was written for DRON {value} and this server reads DRON " |
| 998 | f"{DRON_VERSION}, so it could misread what the package declares; {remedy}. " |
| 999 | "Nothing was installed." |
| 1000 | ) |
| 1001 | |
| 1002 | |
| 1003 | # What a manifest may say (DRON_VERSION, dron/dron-package.schema.json). Every |
| 1004 | # section and entry used to be read key by key and the rest ignored, so a |
| 1005 | # misspelt section ("schedule" for "schedules") installed nothing and |
| 1006 | # reported success, and a misspelt entry key was a setting never applied. |
| 1007 | _MANIFEST_SECTIONS = frozenset({ |
| 1008 | "$schema", "dron", "id", "name", "version", "description", "compatibility", "dependencies", |
| 1009 | "objects", "schemas", "permissions", "seed", "migrations", "connectors", "schedules", |
| 1010 | "nav", "nav_optional", "attention", |
| 1011 | }) |
| 1012 | _MANIFEST_ENTRY_KEYS = { |
| 1013 | "dependencies": frozenset({"id", "version"}), |
| 1014 | "objects": frozenset({"id", "path"}), |
| 1015 | "schemas": frozenset({"collection", "path"}), |
| 1016 | "permissions": frozenset({"path"}), |
| 1017 | "seed": frozenset({"collection", "path"}), |
| 1018 | "migrations": frozenset({"id", "path"}), |
| 1019 | "connectors": frozenset({"collection", "module", "entry"}), |
| 1020 | "schedules": frozenset({"id", "object_id", "schedule", "type", "method", "payload", "description"}), |
| 1021 | "nav": frozenset({"id", "label", "path", "blurb", "surface", "group", "order"}), |
| 1022 | "attention": frozenset({ |
| 1023 | "id", "label", "path", "collection", "where", "detail", "object_id", "reads", |
| 1024 | "nav_id", "group", "severity", |
| 1025 | }), |
| 1026 | } |
| 1027 | |
| 1028 | |
| 1029 | def _refuse_unknown_manifest_keys(package_id: str, payload: Mapping[str, Any]) -> None: |
| 1030 | for key in payload: |
| 1031 | if key not in _MANIFEST_SECTIONS: |
| 1032 | raise InvalidPackageManifestError( |
| 1033 | f"Package {package_id} {MANIFEST_FILE}: unknown section {key!r}" |
| 1034 | f"{object_permissions.did_you_mean(str(key), _MANIFEST_SECTIONS)}" |
| 1035 | ) |
| 1036 | for section, allowed in _MANIFEST_ENTRY_KEYS.items(): |
| 1037 | entries = payload.get(section) |
| 1038 | if not isinstance(entries, list): |
| 1039 | continue # the section's own normalizer refuses it |
| 1040 | for number, entry in enumerate(entries, start=1): |
| 1041 | if not isinstance(entry, Mapping): |
| 1042 | continue |
| 1043 | for key in entry: |
| 1044 | if key not in allowed: |
| 1045 | raise InvalidPackageManifestError( |
| 1046 | f"Package {package_id} {MANIFEST_FILE} {section} entry {number}: " |
| 1047 | f"unknown key {key!r}{object_permissions.did_you_mean(str(key), allowed)}" |
| 1048 | ) |
| 1049 | |
| 1050 | |
| 1051 | _MANIFEST_LIST_SECTIONS = ( |
| 1052 | "dependencies", "objects", "schemas", "permissions", "seed", "migrations", "connectors", |
| 1053 | "schedules", "nav", "attention", |
| 1054 | ) |
| 1055 | _ATTENTION_OPERATORS = ("eq", "ne", "in", "gte", "lte", "gt", "lt", "older_than_days") |
| 1056 | _CONNECTOR_ENTRY_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") |
| 1057 | |
| 1058 | |
| 1059 | def _refuse_loose_manifest_values(package_id: str, payload: Mapping[str, Any]) -> None: |
| 1060 | """Refuse what dron/dron-package.schema.json refuses and the normalizers |
| 1061 | below used to read as absent or as a default: a null section, a value |
| 1062 | of the wrong kind for an optional key, a blank where a choice is |
| 1063 | required. Install and dry run only; a manifest already installed is |
| 1064 | not read through here.""" |
| 1065 | def refuse(where: str, message: str) -> None: |
| 1066 | raise InvalidPackageManifestError(f"Package {package_id} {MANIFEST_FILE}{where}: {message}") |
| 1067 | |
| 1068 | def check_text(where: str, mapping: Mapping[str, Any], key: str, *, blank_ok: bool) -> None: |
| 1069 | if key not in mapping: |
| 1070 | return |
| 1071 | value = mapping[key] |
| 1072 | if not isinstance(value, str): |
| 1073 | refuse(where, f"{key} must be text, not {value!r} (leave the key out to say nothing)") |
| 1074 | if not blank_ok and not value.strip(): |
| 1075 | refuse(where, f"{key} must not be blank (leave the key out to say nothing)") |
| 1076 | |
| 1077 | for section in _MANIFEST_LIST_SECTIONS: |
| 1078 | if section in payload and payload[section] is None: |
| 1079 | refuse("", f"{section} must be a list, not null (leave the section out, or write [])") |
| 1080 | if "description" in payload and not isinstance(payload["description"], str): |
| 1081 | refuse("", f"description must be text, not {payload['description']!r} (leave the key out to say nothing)") |
| 1082 | compatibility = payload.get("compatibility", {}) |
| 1083 | if compatibility is None: |
| 1084 | refuse("", "compatibility must be an object, not null (leave the key out, or write {})") |
| 1085 | if isinstance(compatibility, Mapping): |
| 1086 | for key, value in compatibility.items(): |
| 1087 | if not isinstance(value, str): |
| 1088 | refuse("", f"compatibility {key!r} must be text such as '>=0.1', not {value!r}") |
| 1089 | |
| 1090 | def entries(section: str): |
| 1091 | value = payload.get(section) |
| 1092 | if isinstance(value, list): |
| 1093 | for number, entry in enumerate(value, start=1): |
| 1094 | if isinstance(entry, Mapping): |
| 1095 | yield f" {section} entry {number}", entry |
| 1096 | |
| 1097 | for where, entry in entries("schedules"): |
| 1098 | check_text(where, entry, "description", blank_ok=True) |
| 1099 | for where, entry in entries("connectors"): |
| 1100 | if "entry" in entry: |
| 1101 | check_text(where, entry, "entry", blank_ok=False) |
| 1102 | if not _CONNECTOR_ENTRY_RE.fullmatch(entry["entry"]): |
| 1103 | refuse(where, f"entry {entry['entry']!r} must be a function name: letters, digits and " |
| 1104 | "underscores, not starting with a digit") |
| 1105 | for where, entry in entries("nav"): |
| 1106 | check_text(where, entry, "blurb", blank_ok=True) |
| 1107 | check_text(where, entry, "group", blank_ok=True) |
| 1108 | if "order" in entry and (entry["order"] is None or entry["order"] == ""): |
| 1109 | refuse(where, f"order must be a whole number such as 10, not {entry['order']!r} " |
| 1110 | "(leave the key out for the default)") |
| 1111 | if "surface" in entry: |
| 1112 | check_text(where, entry, "surface", blank_ok=False) |
| 1113 | for where, entry in entries("attention"): |
| 1114 | check_text(where, entry, "group", blank_ok=True) |
| 1115 | check_text(where, entry, "nav_id", blank_ok=False) |
| 1116 | if "severity" in entry: |
| 1117 | check_text(where, entry, "severity", blank_ok=False) |
| 1118 | if entry["severity"] != entry["severity"].strip() or ( |
| 1119 | entry["severity"].lower() in _ATTENTION_SEVERITIES |
| 1120 | and entry["severity"] not in _ATTENTION_SEVERITIES): |
| 1121 | refuse(where, f"severity {entry['severity']!r} is not DRON; write one of " |
| 1122 | f"{', '.join(_ATTENTION_SEVERITIES)}") |
| 1123 | if "reads" in entry and not isinstance(entry["reads"], list): |
| 1124 | refuse(where, f"reads must be a list of collection names, not {entry['reads']!r} " |
| 1125 | "(leave the key out, or write [])") |
| 1126 | _refuse_loose_attention_filters(where, entry, refuse, check_text) |
| 1127 | |
| 1128 | |
| 1129 | def _refuse_loose_attention_filters(where: str, entry: Mapping[str, Any], refuse, check_text) -> None: |
| 1130 | def operators(label: str, where_clause: Any) -> None: |
| 1131 | if not isinstance(where_clause, Mapping): |
| 1132 | return # object_attention refuses it, with its own message |
| 1133 | for field, expected in where_clause.items(): |
| 1134 | for condition in expected if isinstance(expected, list) else [expected]: |
| 1135 | if not isinstance(condition, Mapping): |
| 1136 | continue |
| 1137 | op = condition.get("op") |
| 1138 | if not isinstance(op, str) or op not in _ATTENTION_OPERATORS: |
| 1139 | if isinstance(op, str) and op.strip().lower() in _ATTENTION_OPERATORS: |
| 1140 | hint = f"; write {op.strip().lower()!r}" |
| 1141 | else: |
| 1142 | hint = f"; write one of {', '.join(_ATTENTION_OPERATORS)}" |
| 1143 | refuse(where, f"{label} {field}: op {op!r} is not DRON{hint}" |
| 1144 | if "op" in condition else |
| 1145 | f"{label} {field}: a condition needs an op, one of " |
| 1146 | f"{', '.join(_ATTENTION_OPERATORS)}") |
| 1147 | |
| 1148 | if "where" in entry: |
| 1149 | operators("where", entry["where"]) |
| 1150 | if "detail" in entry: |
| 1151 | detail = entry["detail"] |
| 1152 | if detail is None or detail in ("", [], {}): |
| 1153 | refuse(where, f"detail must be a part or a list of parts, not {detail!r} " |
| 1154 | "(leave the key out for no detail)") |
| 1155 | for number, part in enumerate(detail if isinstance(detail, list) else [detail], start=1): |
| 1156 | if not isinstance(part, Mapping): |
| 1157 | continue # object_attention refuses it, with its own message |
| 1158 | label = f"detail part {number}" |
| 1159 | if "op" in part and not isinstance(part["op"], str): |
| 1160 | refuse(where, f"{label}: op must be text, one of count, sum, max_age_days, not {part['op']!r}") |
| 1161 | if "format" in part: |
| 1162 | fmt = part["format"] |
| 1163 | if not isinstance(fmt, str) or not fmt.strip(): |
| 1164 | refuse(where, f"{label}: format must be one of integer, cents, dollars, hours, " |
| 1165 | f"not {fmt!r} (leave the key out for integer)") |
| 1166 | if "where" in part: |
| 1167 | operators(f"{label} where", part["where"]) |
| 1168 | |
| 1169 | |
| 1170 | def _declared_flag(payload: Mapping[str, Any], key: str, *, package_id: str) -> bool: |
| 1171 | """A manifest true/false. bool("no") is True, so text is refused, not read.""" |
| 1172 | value = payload.get(key, False) |
| 1173 | if not isinstance(value, bool): |
| 1174 | raise InvalidPackageManifestError( |
| 1175 | f"Package {package_id} {MANIFEST_FILE}: {key} must be true or false, not {value!r}" |
| 1176 | ) |
| 1177 | return value |
| 1178 | |
| 1179 | |
| 1180 | def _declared_text(payload: Mapping[str, Any], key: str, *, package_id: str) -> str | None: |
| 1181 | """Optional manifest text. Anything else used to become nothing without a word.""" |
| 1182 | value = payload.get(key) |
| 1183 | if value is not None and not isinstance(value, str): |
| 1184 | raise InvalidPackageManifestError( |
| 1185 | f"Package {package_id} {MANIFEST_FILE}: {key} must be text, not {value!r}" |
| 1186 | ) |
| 1187 | return value |
| 1188 | |
| 1189 | |
| 1190 | def _refuse_other_spelling( |
| 1191 | mapping: Mapping[str, Any], key: str, choices: Iterable[str], *, where: str |
| 1192 | ) -> None: |
| 1193 | """DRON spells a choice one way. The loader used to change the case of |
| 1194 | whatever it was given ("CRON", "Public"); now that is refused, with the |
| 1195 | spelling, so the file says what the server reads. Anything that is not a |
| 1196 | case variant is left to the caller's own check and message.""" |
| 1197 | value = mapping.get(key) |
| 1198 | if not isinstance(value, str) or value in choices: |
| 1199 | return |
| 1200 | for choice in choices: |
| 1201 | if value.strip().lower() == choice.lower(): |
| 1202 | raise InvalidPackageManifestError( |
| 1203 | f"Package {where}: {key} {value!r} is not DRON; write {choice!r}" |
| 1204 | ) |
| 1205 | |
| 1206 | |
| 1207 | def _normalize_manifest(package_id: str, payload: Any) -> dict[str, Any]: |
| 1208 | if not isinstance(payload, Mapping): |
| 1209 | raise InvalidPackageManifestError(f"Package manifest must contain an object: {package_id}") |
| 1210 | _refuse_unreadable_dron_version(package_id, payload) |
| 1211 | _refuse_unknown_manifest_keys(package_id, payload) |
| 1212 | _refuse_loose_manifest_values(package_id, payload) |
| 1213 | |
| 1214 | manifest_id = _required_text(payload, "id", package_id=package_id) |
| 1215 | if manifest_id != package_id: |
| 1216 | raise InvalidPackageManifestError( |
| 1217 | f"Package manifest id does not match directory: {package_id}" |
| 1218 | ) |
| 1219 | if not validate_package_id(manifest_id): |
| 1220 | raise InvalidPackageIdError(f"Invalid package id: {manifest_id}") |
| 1221 | |
| 1222 | version = _required_text(payload, "version", package_id=package_id) |
| 1223 | if not _VERSION_RE.fullmatch(version): |
| 1224 | raise InvalidPackageManifestError(f"Invalid package version: {package_id}") |
| 1225 | |
| 1226 | return { |
| 1227 | "id": manifest_id, |
| 1228 | "name": _required_text(payload, "name", package_id=package_id), |
| 1229 | "version": version, |
| 1230 | "description": _optional_text(_declared_text(payload, "description", package_id=package_id)), |
| 1231 | "compatibility": _mapping_field(payload.get("compatibility"), package_id=package_id), |
| 1232 | "dependencies": _normalize_dependencies(payload.get("dependencies", []), package_id=package_id), |
| 1233 | "objects": _normalize_objects(payload.get("objects", []), package_id=package_id), |
| 1234 | "schemas": _normalize_collection_paths( |
| 1235 | payload.get("schemas", []), |
| 1236 | package_id=package_id, |
| 1237 | collection_key="collection", |
| 1238 | section="schemas", |
| 1239 | ), |
| 1240 | "permissions": _normalize_path_entries( |
| 1241 | payload.get("permissions", []), |
| 1242 | package_id=package_id, |
| 1243 | section="permissions", |
| 1244 | ), |
| 1245 | "seed": _normalize_collection_paths( |
| 1246 | payload.get("seed", []), |
| 1247 | package_id=package_id, |
| 1248 | collection_key="collection", |
| 1249 | section="seed", |
| 1250 | ), |
| 1251 | "migrations": _normalize_migrations(payload.get("migrations", []), package_id=package_id), |
| 1252 | "connectors": _normalize_connectors(payload.get("connectors", []), package_id=package_id), |
| 1253 | "schedules": _normalize_schedules(payload.get("schedules", []), package_id=package_id), |
| 1254 | "nav": _normalize_nav(payload.get("nav", []), package_id=package_id), |
| 1255 | "attention": _normalize_attention(payload.get("attention", []), package_id=package_id), |
| 1256 | # The documented opt-out for a package that ships a site_* object |
| 1257 | # which is not a door: a JS widget (site_thread), a fragment |
| 1258 | # (site_materialize_run_button), or a per-record document reached |
| 1259 | # from the record itself (site_packing_slip). Saying so in the |
| 1260 | # manifest is the point -- "this app has no front page" becomes a |
| 1261 | # reviewable claim rather than an omission nobody notices. |
| 1262 | "nav_optional": _declared_flag(payload, "nav_optional", package_id=package_id), |
| 1263 | } |
| 1264 | |
| 1265 | |
| 1266 | def _package_summary(package: Mapping[str, Any]) -> dict[str, Any]: |
| 1267 | return { |
| 1268 | "id": package["id"], |
| 1269 | "name": package["name"], |
| 1270 | "version": package["version"], |
| 1271 | "description": package.get("description"), |
| 1272 | "status": "available", |
| 1273 | "object_count": len(package["objects"]), |
| 1274 | "schema_count": len(package["schemas"]), |
| 1275 | "permission_count": len(package["permissions"]), |
| 1276 | "seed_count": len(package["seed"]), |
| 1277 | "migration_count": len(package["migrations"]), |
| 1278 | "dependency_count": len(package["dependencies"]), |
| 1279 | "connector_count": len(package.get("connectors", [])), |
| 1280 | "schedule_count": len(package.get("schedules", [])), |
| 1281 | "nav_count": len(package.get("nav", [])), |
| 1282 | "attention_count": len(package.get("attention", [])), |
| 1283 | } |
| 1284 | |
| 1285 | |
| 1286 | def _normalize_objects(payload: Any, *, package_id: str) -> list[dict[str, str]]: |
| 1287 | entries = _list_field(payload, package_id=package_id, section="objects") |
| 1288 | normalized = [] |
| 1289 | for entry in entries: |
| 1290 | mapping = _entry_mapping(entry, package_id=package_id, section="objects") |
| 1291 | object_id = _required_text(mapping, "id", package_id=package_id) |
| 1292 | if not validate_object_id(object_id): |
| 1293 | raise InvalidPackageManifestError(f"Invalid package object id: {object_id}") |
| 1294 | normalized.append( |
| 1295 | { |
| 1296 | "id": object_id, |
| 1297 | "path": _safe_relative_path( |
| 1298 | _required_text(mapping, "path", package_id=package_id), |
| 1299 | package_id=package_id, |
| 1300 | section="objects", |
| 1301 | ), |
| 1302 | } |
| 1303 | ) |
| 1304 | return normalized |
| 1305 | |
| 1306 | |
| 1307 | def _normalize_collection_paths( |
| 1308 | payload: Any, |
| 1309 | *, |
| 1310 | package_id: str, |
| 1311 | collection_key: str, |
| 1312 | section: str, |
| 1313 | ) -> list[dict[str, str]]: |
| 1314 | entries = _list_field(payload, package_id=package_id, section=section) |
| 1315 | normalized = [] |
| 1316 | for entry in entries: |
| 1317 | mapping = _entry_mapping(entry, package_id=package_id, section=section) |
| 1318 | collection = _required_text(mapping, collection_key, package_id=package_id) |
| 1319 | if not object_collections.validate_collection_name(collection): |
| 1320 | raise InvalidPackageManifestError(f"Invalid package collection: {collection}") |
| 1321 | normalized.append( |
| 1322 | { |
| 1323 | collection_key: collection, |
| 1324 | "path": _safe_relative_path( |
| 1325 | _required_text(mapping, "path", package_id=package_id), |
| 1326 | package_id=package_id, |
| 1327 | section=section, |
| 1328 | ), |
| 1329 | } |
| 1330 | ) |
| 1331 | return normalized |
| 1332 | |
| 1333 | |
| 1334 | def _normalize_path_entries( |
| 1335 | payload: Any, |
| 1336 | *, |
| 1337 | package_id: str, |
| 1338 | section: str, |
| 1339 | ) -> list[dict[str, str]]: |
| 1340 | entries = _list_field(payload, package_id=package_id, section=section) |
| 1341 | normalized = [] |
| 1342 | for entry in entries: |
| 1343 | mapping = _entry_mapping(entry, package_id=package_id, section=section) |
| 1344 | normalized.append( |
| 1345 | { |
| 1346 | "path": _safe_relative_path( |
| 1347 | _required_text(mapping, "path", package_id=package_id), |
| 1348 | package_id=package_id, |
| 1349 | section=section, |
| 1350 | ) |
| 1351 | } |
| 1352 | ) |
| 1353 | return normalized |
| 1354 | |
| 1355 | |
| 1356 | def _normalize_migrations(payload: Any, *, package_id: str) -> list[dict[str, str]]: |
| 1357 | entries = _list_field(payload, package_id=package_id, section="migrations") |
| 1358 | normalized = [] |
| 1359 | for entry in entries: |
| 1360 | mapping = _entry_mapping(entry, package_id=package_id, section="migrations") |
| 1361 | migration_id = _required_text(mapping, "id", package_id=package_id) |
| 1362 | if not _MIGRATION_ID_RE.fullmatch(migration_id): |
| 1363 | raise InvalidPackageManifestError(f"Invalid package migration id: {migration_id}") |
| 1364 | normalized.append( |
| 1365 | { |
| 1366 | "id": migration_id, |
| 1367 | "path": _safe_relative_path( |
| 1368 | _required_text(mapping, "path", package_id=package_id), |
| 1369 | package_id=package_id, |
| 1370 | section="migrations", |
| 1371 | ), |
| 1372 | } |
| 1373 | ) |
| 1374 | return normalized |
| 1375 | |
| 1376 | |
| 1377 | def _normalize_connectors(payload: Any, *, package_id: str) -> list[dict[str, str]]: |
| 1378 | """A `connectors` entry declares that a collection is reconciled against an |
| 1379 | external system by a connector module inside this package (see |
| 1380 | object_connectors / plan/vocabulary/03-external-connectors-spec.md): |
| 1381 | `{collection, module, entry?}`. `module` is validated as a package-relative |
| 1382 | path (escape-checked again at load time); `entry` defaults to `reconcile`.""" |
| 1383 | entries = _list_field(payload, package_id=package_id, section="connectors") |
| 1384 | normalized = [] |
| 1385 | for entry in entries: |
| 1386 | mapping = _entry_mapping(entry, package_id=package_id, section="connectors") |
| 1387 | collection = _required_text(mapping, "collection", package_id=package_id) |
| 1388 | if not object_collections.validate_collection_name(collection): |
| 1389 | raise InvalidPackageManifestError(f"Invalid package connector collection: {collection}") |
| 1390 | module = _safe_relative_path( |
| 1391 | _required_text(mapping, "module", package_id=package_id), |
| 1392 | package_id=package_id, |
| 1393 | section="connectors", |
| 1394 | ) |
| 1395 | entry_name = _optional_text(mapping.get("entry")) or "reconcile" |
| 1396 | if not entry_name.isidentifier(): |
| 1397 | raise InvalidPackageManifestError(f"Invalid connector entry: {entry_name}") |
| 1398 | normalized.append({"collection": collection, "module": module, "entry": entry_name}) |
| 1399 | return normalized |
| 1400 | |
| 1401 | |
| 1402 | def _normalize_schedules(payload: Any, *, package_id: str) -> list[dict[str, Any]]: |
| 1403 | """A `schedules` entry declares a recurring pass the app needs to work: |
| 1404 | `{id, object_id, schedule, type?, method?, payload?, description?}`. |
| 1405 | |
| 1406 | Time-driven work belongs to the daemon (docs/logic-decisions.md #2), |
| 1407 | and until now the declaration of WHICH work lived only in a running |
| 1408 | server's state. That made a schedule invisible to review, absent from |
| 1409 | a fresh install, and lost on a rebuild. Declaring it here makes the |
| 1410 | recurring pass part of the package, like the object it calls. |
| 1411 | |
| 1412 | The id becomes a `task_<id>` state key, so it is restricted to the |
| 1413 | characters a key can safely hold; every other field is validated here |
| 1414 | rather than at 3am inside the daemon, where a bad cron string is a |
| 1415 | pass that quietly does nothing. |
| 1416 | """ |
| 1417 | entries = _list_field(payload, package_id=package_id, section="schedules") |
| 1418 | normalized: list[dict[str, Any]] = [] |
| 1419 | seen: set[str] = set() |
| 1420 | for entry in entries: |
| 1421 | mapping = _entry_mapping(entry, package_id=package_id, section="schedules") |
| 1422 | schedule_id = _required_text(mapping, "id", package_id=package_id) |
| 1423 | if not _SCHEDULE_ID_RE.fullmatch(schedule_id): |
| 1424 | raise InvalidPackageManifestError(f"Invalid package schedule id: {schedule_id}") |
| 1425 | if schedule_id in seen: |
| 1426 | raise InvalidPackageManifestError( |
| 1427 | f"Duplicate package schedule id: {schedule_id}" |
| 1428 | ) |
| 1429 | seen.add(schedule_id) |
| 1430 | |
| 1431 | object_id = _required_text(mapping, "object_id", package_id=package_id) |
| 1432 | if not validate_object_id(object_id): |
| 1433 | raise InvalidPackageManifestError( |
| 1434 | f"Invalid package schedule object_id: {object_id}" |
| 1435 | ) |
| 1436 | |
| 1437 | _refuse_other_spelling(mapping, "type", _SCHEDULE_TYPES, where=f"schedule {schedule_id}") |
| 1438 | schedule_type = (_optional_text(mapping.get("type")) or "cron").lower() |
| 1439 | if schedule_type not in _SCHEDULE_TYPES: |
| 1440 | raise InvalidPackageManifestError( |
| 1441 | f"Package schedule type must be cron|onetime: {schedule_id}" |
| 1442 | ) |
| 1443 | |
| 1444 | expression = _required_text(mapping, "schedule", package_id=package_id) |
| 1445 | _validate_schedule_expression(expression, schedule_type, schedule_id=schedule_id) |
| 1446 | |
| 1447 | _refuse_other_spelling(mapping, "method", _SCHEDULE_METHODS, where=f"schedule {schedule_id}") |
| 1448 | method = (_optional_text(mapping.get("method")) or "POST").upper() |
| 1449 | if method not in _SCHEDULE_METHODS: |
| 1450 | raise InvalidPackageManifestError( |
| 1451 | f"Invalid package schedule method: {schedule_id}" |
| 1452 | ) |
| 1453 | |
| 1454 | task_payload = mapping.get("payload", {}) |
| 1455 | if task_payload in (None, ""): |
| 1456 | task_payload = {} |
| 1457 | if not isinstance(task_payload, Mapping): |
| 1458 | raise InvalidPackageManifestError( |
| 1459 | f"Package schedule payload must be an object: {schedule_id}" |
| 1460 | ) |
| 1461 | |
| 1462 | normalized.append({ |
| 1463 | "id": schedule_id, |
| 1464 | "object_id": object_id, |
| 1465 | "method": method, |
| 1466 | "payload": dict(task_payload), |
| 1467 | "schedule": expression, |
| 1468 | "type": schedule_type, |
| 1469 | "description": _optional_text(mapping.get("description")), |
| 1470 | }) |
| 1471 | return normalized |
| 1472 | |
| 1473 | |
| 1474 | def _validate_schedule_expression( |
| 1475 | expression: str, |
| 1476 | schedule_type: str, |
| 1477 | *, |
| 1478 | schedule_id: str, |
| 1479 | ) -> None: |
| 1480 | """Reject a schedule that could never fire, at install time. |
| 1481 | |
| 1482 | The daemon treats an unparseable expression as "no next run" and moves |
| 1483 | on in silence, so a typo here is a pass that never runs and never |
| 1484 | complains -- the failure this whole feature exists to end. Cron is |
| 1485 | checked with croniter where it is installed, and structurally where it |
| 1486 | is not, so validation degrades rather than disappearing. |
| 1487 | """ |
| 1488 | if "\t" in expression or "\n" in expression: |
| 1489 | raise InvalidPackageManifestError( |
| 1490 | f"Package schedule expression may not contain tabs or newlines: {schedule_id}" |
| 1491 | ) |
| 1492 | if schedule_type == "onetime": |
| 1493 | from datetime import datetime |
| 1494 | |
| 1495 | try: |
| 1496 | datetime.fromisoformat(expression.replace("Z", "+00:00")) |
| 1497 | except ValueError as exc: |
| 1498 | raise InvalidPackageManifestError( |
| 1499 | f"Package onetime schedule must be an ISO timestamp: {schedule_id}" |
| 1500 | ) from exc |
| 1501 | return |
| 1502 | |
| 1503 | try: |
| 1504 | from croniter import croniter |
| 1505 | except ImportError: |
| 1506 | croniter = None |
| 1507 | if croniter is not None: |
| 1508 | if not croniter.is_valid(expression): |
| 1509 | raise InvalidPackageManifestError( |
| 1510 | f"Invalid package cron expression: {schedule_id}" |
| 1511 | ) |
| 1512 | return |
| 1513 | if len(expression.split()) not in (5, 6): |
| 1514 | raise InvalidPackageManifestError( |
| 1515 | f"Package cron expression must have 5 or 6 fields: {schedule_id}" |
| 1516 | ) |
| 1517 | |
| 1518 | |
| 1519 | def _load_scheduler_tasks(base_dir: Path) -> dict[str, dict[str, Any]]: |
| 1520 | """Every task currently on the daemon's board, keyed by schedule id. |
| 1521 | |
| 1522 | Unreadable rows are skipped rather than raising: one hand-edited task |
| 1523 | must not make a package uninstallable. |
| 1524 | """ |
| 1525 | try: |
| 1526 | state = object_state.get_object_state(SCHEDULER_OBJECT_ID, base_dir=base_dir) |
| 1527 | except Exception: |
| 1528 | return {} |
| 1529 | tasks: dict[str, dict[str, Any]] = {} |
| 1530 | for key, value in state.items(): |
| 1531 | if not str(key).startswith(_TASK_KEY_PREFIX): |
| 1532 | continue |
| 1533 | try: |
| 1534 | task = json.loads(value) |
| 1535 | except (TypeError, ValueError): |
| 1536 | continue |
| 1537 | if isinstance(task, Mapping): |
| 1538 | tasks[str(key)[len(_TASK_KEY_PREFIX):]] = dict(task) |
| 1539 | return tasks |
| 1540 | |
| 1541 | |
| 1542 | def _schedule_change( |
| 1543 | entry: Mapping[str, Any], |
| 1544 | *, |
| 1545 | existing: Mapping[str, dict[str, Any]], |
| 1546 | installable_object_ids: set[str], |
| 1547 | warnings: list[str], |
| 1548 | ) -> dict[str, Any]: |
| 1549 | live = existing.get(entry["id"]) |
| 1550 | if live is None: |
| 1551 | action = "create" |
| 1552 | elif all(live.get(field) == entry[field] |
| 1553 | for field in ("object_id", "method", "payload", "schedule", "type")) \ |
| 1554 | and (live.get("description") or None) == entry["description"]: |
| 1555 | # The description is compared too, so a plan that says "unchanged" |
| 1556 | # is one where nothing at all is about to be written -- a dry run |
| 1557 | # that under-reports is worse than no dry run. |
| 1558 | action = "unchanged" |
| 1559 | else: |
| 1560 | action = "update" |
| 1561 | |
| 1562 | if entry["object_id"] not in installable_object_ids: |
| 1563 | # A schedule aimed at an object that will not exist is the silent |
| 1564 | # failure this feature exists to end, so it blocks the install |
| 1565 | # rather than landing as a task that can never run. |
| 1566 | warnings.append( |
| 1567 | f"Schedule {entry['id']} targets an object this install will not " |
| 1568 | f"provide: {entry['object_id']}" |
| 1569 | ) |
| 1570 | |
| 1571 | change = { |
| 1572 | "id": entry["id"], |
| 1573 | "object_id": entry["object_id"], |
| 1574 | "schedule": entry["schedule"], |
| 1575 | "type": entry["type"], |
| 1576 | "exists": live is not None, |
| 1577 | "action": action, |
| 1578 | } |
| 1579 | if live is not None: |
| 1580 | change["status"] = live.get("status", "active") |
| 1581 | change["run_count"] = live.get("run_count", 0) |
| 1582 | return change |
| 1583 | |
| 1584 | |
| 1585 | def _apply_schedules( |
| 1586 | schedules: Iterable[Mapping[str, Any]], |
| 1587 | planned: Iterable[Mapping[str, Any]], |
| 1588 | *, |
| 1589 | base_dir: Path, |
| 1590 | ) -> list[dict[str, Any]]: |
| 1591 | """Write the package's schedules onto the daemon's task board. |
| 1592 | |
| 1593 | Two things are deliberately preserved across an install: |
| 1594 | |
| 1595 | **Run history** -- last_run/run_count/next_run belong to the daemon, |
| 1596 | not the package. Resetting them on an upgrade would make an operator's |
| 1597 | "when did this last work?" unanswerable. |
| 1598 | |
| 1599 | **A pause** -- if someone paused a task, it stays paused. The package |
| 1600 | declares what SHOULD run; an operator decides what DOES right now, and |
| 1601 | a reinstall that silently restarts a deliberately-stopped nightly pass |
| 1602 | is how an upgrade becomes an incident. |
| 1603 | |
| 1604 | A changed expression clears next_run so the daemon recomputes it from |
| 1605 | the new one; an unchanged expression keeps the pending firing exactly |
| 1606 | where it was, so reinstalling an app does not skip tonight's run. |
| 1607 | """ |
| 1608 | entries = list(schedules) |
| 1609 | plans = list(planned) |
| 1610 | if not entries: |
| 1611 | return [] |
| 1612 | |
| 1613 | manager = object_state.ObjectStateManager(SCHEDULER_OBJECT_ID, base_dir=base_dir) |
| 1614 | applied = [] |
| 1615 | for entry, plan in zip(entries, plans, strict=True): |
| 1616 | key = f"{_TASK_KEY_PREFIX}{entry['id']}" |
| 1617 | raw = manager.get(key) |
| 1618 | live: dict[str, Any] = {} |
| 1619 | if raw is not None: |
| 1620 | try: |
| 1621 | parsed = json.loads(raw) |
| 1622 | except (TypeError, ValueError): |
| 1623 | parsed = None |
| 1624 | if isinstance(parsed, Mapping): |
| 1625 | live = dict(parsed) |
| 1626 | |
| 1627 | task = { |
| 1628 | "id": entry["id"], |
| 1629 | "object_id": entry["object_id"], |
| 1630 | "method": entry["method"], |
| 1631 | "payload": entry["payload"], |
| 1632 | "schedule": entry["schedule"], |
| 1633 | "type": entry["type"], |
| 1634 | "status": live.get("status", "active"), |
| 1635 | } |
| 1636 | if entry.get("description"): |
| 1637 | task["description"] = entry["description"] |
| 1638 | for field in _SCHEDULE_RUNTIME_FIELDS: |
| 1639 | if field in live: |
| 1640 | task[field] = live[field] |
| 1641 | if live and live.get("schedule") != entry["schedule"]: |
| 1642 | task["next_run"] = None |
| 1643 | |
| 1644 | if live and json.dumps(live, sort_keys=True) == json.dumps(task, sort_keys=True): |
| 1645 | status = "unchanged" |
| 1646 | else: |
| 1647 | manager.set(key, json.dumps(task)) |
| 1648 | status = "updated" if live else "written" |
| 1649 | |
| 1650 | applied.append({**plan, "status": status, "task_status": task["status"], |
| 1651 | "destination": f"state/{SCHEDULER_OBJECT_ID}/{key}"}) |
| 1652 | return applied |
| 1653 | |
| 1654 | |
| 1655 | def _normalize_nav(payload: Any, *, package_id: str) -> list[dict[str, Any]]: |
| 1656 | """A `nav` entry declares a door the app puts on the site: |
| 1657 | `{id, label, path, blurb?, surface?, group?, order?}`. |
| 1658 | |
| 1659 | Navigation used to be a hand-maintained list, and there were three of |
| 1660 | them -- the app switcher's JS array, the home page's tile list, and |
| 1661 | the search result URL map -- each edited by whoever remembered. They |
| 1662 | disagreed by four entries and between them knew about none of the |
| 1663 | eight newest apps, so the front door of the server advertised a |
| 1664 | server that no longer existed. A menu built by hand rots the moment |
| 1665 | somebody ships without editing it; a menu FOLDED over what every |
| 1666 | installed package declares cannot. |
| 1667 | |
| 1668 | The id becomes the `nav_entries` record id, so it is restricted to |
| 1669 | the characters a record id can safely hold. `path` is validated for |
| 1670 | shape only -- whether anything answers it is a routing question this |
| 1671 | module deliberately does not pretend to answer (see `_nav_change`). |
| 1672 | """ |
| 1673 | entries = _list_field(payload, package_id=package_id, section="nav") |
| 1674 | normalized: list[dict[str, Any]] = [] |
| 1675 | seen: set[str] = set() |
| 1676 | for entry in entries: |
| 1677 | mapping = _entry_mapping(entry, package_id=package_id, section="nav") |
| 1678 | nav_id = _required_text(mapping, "id", package_id=package_id) |
| 1679 | if not _NAV_ID_RE.fullmatch(nav_id): |
| 1680 | raise InvalidPackageManifestError(f"Invalid package nav id: {nav_id}") |
| 1681 | if nav_id in seen: |
| 1682 | raise InvalidPackageManifestError(f"Duplicate package nav id: {nav_id}") |
| 1683 | seen.add(nav_id) |
| 1684 | |
| 1685 | label = _required_text(mapping, "label", package_id=package_id) |
| 1686 | path = _required_text(mapping, "path", package_id=package_id) |
| 1687 | if not path.startswith("/"): |
| 1688 | raise InvalidPackageManifestError( |
| 1689 | f"Package nav path must start with '/': {nav_id}" |
| 1690 | ) |
| 1691 | if any(character.isspace() for character in path): |
| 1692 | # A path with a space or a newline in it is a link that never |
| 1693 | # resolves and a TSV cell that can break the row it lives in. |
| 1694 | raise InvalidPackageManifestError( |
| 1695 | f"Package nav path may not contain whitespace: {nav_id}" |
| 1696 | ) |
| 1697 | |
| 1698 | _refuse_other_spelling(mapping, "surface", _NAV_SURFACES, where=f"nav {nav_id}") |
| 1699 | surface = (_optional_text(mapping.get("surface")) or "member").lower() |
| 1700 | if surface not in _NAV_SURFACES: |
| 1701 | raise InvalidPackageManifestError( |
| 1702 | f"Package nav surface must be public|member|operator|hidden: {nav_id}" |
| 1703 | ) |
| 1704 | |
| 1705 | order = mapping.get("order", _NAV_DEFAULT_ORDER) |
| 1706 | if order in (None, ""): |
| 1707 | order = _NAV_DEFAULT_ORDER |
| 1708 | if isinstance(order, bool) or not isinstance(order, int): |
| 1709 | raise InvalidPackageManifestError( |
| 1710 | f"Package nav order must be an integer: {nav_id}" |
| 1711 | ) |
| 1712 | |
| 1713 | normalized.append({ |
| 1714 | "id": nav_id, |
| 1715 | "label": label, |
| 1716 | "path": path, |
| 1717 | "blurb": _optional_text(mapping.get("blurb")) or "", |
| 1718 | "group": _optional_text(mapping.get("group")) or _NAV_DEFAULT_GROUP, |
| 1719 | "surface": surface, |
| 1720 | "order": order, |
| 1721 | }) |
| 1722 | return normalized |
| 1723 | |
| 1724 | |
| 1725 | def _load_nav_entries( |
| 1726 | base_dir: Path, |
| 1727 | *, |
| 1728 | roots: Iterable[Path] | None = None, |
| 1729 | ) -> dict[str, dict[str, str]] | None: |
| 1730 | """Every nav entry currently registered, keyed by record id. |
| 1731 | |
| 1732 | ``None`` means the `nav_entries` collection is not installed at all |
| 1733 | (app-nav absent). That is not an error: a package must never fail to |
| 1734 | install because the navigation app is missing, any more than an app |
| 1735 | should fail because nobody has opened the menu yet. |
| 1736 | """ |
| 1737 | try: |
| 1738 | rows = object_records.read_collection_records( |
| 1739 | NAV_COLLECTION, base_dir=base_dir, roots=roots) |
| 1740 | except (object_collections.CollectionNotFoundError, |
| 1741 | object_collections.InvalidCollectionNameError): |
| 1742 | return None |
| 1743 | except (OSError, ValueError): |
| 1744 | # A hand-edited row must not make a package uninstallable, the |
| 1745 | # same posture _load_scheduler_tasks takes. |
| 1746 | return {} |
| 1747 | return {str(row.get("id") or ""): dict(row) for row in rows if row.get("id")} |
| 1748 | |
| 1749 | |
| 1750 | def _nav_change( |
| 1751 | entry: Mapping[str, Any], |
| 1752 | *, |
| 1753 | existing: Mapping[str, Mapping[str, str]], |
| 1754 | package_id: str, |
| 1755 | warnings: list[str], |
| 1756 | ) -> dict[str, Any]: |
| 1757 | live = existing.get(entry["id"]) |
| 1758 | if live is None: |
| 1759 | action = "create" |
| 1760 | elif all(str(live.get(field) or "") == str(entry[field]) for field in _NAV_PACKAGE_FIELDS): |
| 1761 | # Every package-owned field is compared, blurb and order |
| 1762 | # included, so a plan that says "unchanged" is one where nothing |
| 1763 | # at all is about to be written -- a dry run that under-reports |
| 1764 | # is worse than no dry run. |
| 1765 | action = "unchanged" |
| 1766 | else: |
| 1767 | action = "update" |
| 1768 | |
| 1769 | # Whether a path is actually SERVED is not knowable here: routing has |
| 1770 | # three sources (convention, site_routes records, views records) and |
| 1771 | # two of them are data this install may be about to seed. Guessing |
| 1772 | # would produce false blockers, so the only thing refused is the one |
| 1773 | # collision that is unambiguous and destructive: two packages fighting |
| 1774 | # over one door, where whichever installs last silently wins. |
| 1775 | owner = str((live or {}).get("package") or "") |
| 1776 | if owner and owner != package_id: |
| 1777 | warnings.append( |
| 1778 | f"Nav entry {entry['id']} is already registered by another package: {owner}" |
| 1779 | ) |
| 1780 | for other_id, other in existing.items(): |
| 1781 | if other_id == entry["id"]: |
| 1782 | continue |
| 1783 | other_owner = str(other.get("package") or "") |
| 1784 | if other_owner and other_owner != package_id and other.get("path") == entry["path"]: |
| 1785 | warnings.append( |
| 1786 | f"Nav entry {entry['id']} claims a path already registered by " |
| 1787 | f"{other_owner}: {entry['path']}" |
| 1788 | ) |
| 1789 | |
| 1790 | return { |
| 1791 | "id": entry["id"], |
| 1792 | "label": entry["label"], |
| 1793 | "path": entry["path"], |
| 1794 | "group": entry["group"], |
| 1795 | "surface": entry["surface"], |
| 1796 | "exists": live is not None, |
| 1797 | "action": action, |
| 1798 | } |
| 1799 | |
| 1800 | |
| 1801 | def _apply_nav( |
| 1802 | nav: Iterable[Mapping[str, Any]], |
| 1803 | planned: Iterable[Mapping[str, Any]], |
| 1804 | *, |
| 1805 | package_id: str, |
| 1806 | base_dir: Path, |
| 1807 | roots: Iterable[Path] | None = None, |
| 1808 | ) -> list[dict[str, Any]]: |
| 1809 | """Register the package's doors in the `nav_entries` collection. |
| 1810 | |
| 1811 | Two things are deliberately preserved across an install: |
| 1812 | |
| 1813 | **The operator's `hidden`** -- `operator_hidden` is the one column an |
| 1814 | install never writes on an existing row. The package declares what |
| 1815 | the app IS; the operator decides what they want to SEE, and an |
| 1816 | upgrade that silently un-hides a page somebody deliberately took off |
| 1817 | the menu is the same class of incident as one that restarts a paused |
| 1818 | nightly pass. |
| 1819 | |
| 1820 | **Somebody else's row** -- entries this package did not register are |
| 1821 | not touched and not deleted. Removing a `nav` entry from a manifest |
| 1822 | leaves the row alone, matching the rest of install: deregistering |
| 1823 | never destroys. |
| 1824 | |
| 1825 | A missing `nav_entries` collection is reported and skipped rather |
| 1826 | than raised. The nav app is not a dependency of being installable. |
| 1827 | """ |
| 1828 | entries = list(nav) |
| 1829 | plans = list(planned) |
| 1830 | if not entries: |
| 1831 | return [] |
| 1832 | |
| 1833 | existing = _load_nav_entries(base_dir, roots=roots) |
| 1834 | if existing is None: |
| 1835 | return [ |
| 1836 | {**plan, "status": "skipped", |
| 1837 | "reason": f"{NAV_COLLECTION} collection is not installed"} |
| 1838 | for plan in plans |
| 1839 | ] |
| 1840 | |
| 1841 | applied = [] |
| 1842 | for entry, plan in zip(entries, plans, strict=True): |
| 1843 | live = existing.get(entry["id"]) |
| 1844 | row = { |
| 1845 | "package": package_id, |
| 1846 | "label": entry["label"], |
| 1847 | "path": entry["path"], |
| 1848 | "blurb": entry["blurb"], |
| 1849 | "group": entry["group"], |
| 1850 | "surface": entry["surface"], |
| 1851 | "order": str(entry["order"]), |
| 1852 | } |
| 1853 | if live is None: |
| 1854 | object_records.create_collection_record( |
| 1855 | NAV_COLLECTION, |
| 1856 | {"id": entry["id"], "operator_hidden": "false", **row}, |
| 1857 | base_dir=base_dir, roots=roots, actor=f"package:{package_id}", |
| 1858 | ) |
| 1859 | status = "written" |
| 1860 | elif all(str(live.get(field) or "") == row[field] for field in row): |
| 1861 | status = "unchanged" |
| 1862 | else: |
| 1863 | # `row` carries no operator_hidden key at all, so the update |
| 1864 | # cannot reach that column even by accident. |
| 1865 | object_records.update_collection_record( |
| 1866 | NAV_COLLECTION, entry["id"], row, |
| 1867 | base_dir=base_dir, roots=roots, actor=f"package:{package_id}", |
| 1868 | ) |
| 1869 | status = "updated" |
| 1870 | |
| 1871 | applied.append({**plan, "status": status, |
| 1872 | "destination": f"collections/{NAV_COLLECTION}/{entry['id']}"}) |
| 1873 | return applied |
| 1874 | |
| 1875 | |
| 1876 | def _normalize_attention(payload: Any, *, package_id: str) -> list[dict[str, Any]]: |
| 1877 | """An `attention` entry declares one queue of things that need a human: |
| 1878 | `{id, object_id, label, path, nav_id?, group?, severity?}`. |
| 1879 | |
| 1880 | Every gate and derived state on this server ends in a pile somebody |
| 1881 | has to look at -- receipts waiting to be confirmed into expenses, time |
| 1882 | entries waiting for an approver, invoices past their due date, bank |
| 1883 | lines nothing matched. The system computes those piles constantly and |
| 1884 | then discards them: `system_scan_processor` returns a field called |
| 1885 | `needing_a_human` that no surface has ever read. What was missing was |
| 1886 | not the arithmetic, it was a place to declare that the arithmetic |
| 1887 | MEANS something -- and the only honest place for that definition is |
| 1888 | the package that owns the domain, because nobody else knows that |
| 1889 | `extracted` is a waiting room and `confirmed` is not. |
| 1890 | |
| 1891 | `object_id` names the provider, an object exposing `COUNT(request) -> |
| 1892 | {"count": int, "detail"?: str}`, with `reads` naming the collections it |
| 1893 | folds (its number reaches only viewers who may read every row of them; |
| 1894 | without it, only admins). Or, instead of `object_id`, the entry |
| 1895 | declares the count -- `collection`, `where`, optional `detail` -- and |
| 1896 | object_attention counts it for each viewer, through the permission |
| 1897 | engine; that is the form for "rows of one collection in a waiting |
| 1898 | state", which ten providers were. `path` is validated for shape only, |
| 1899 | exactly as `nav` paths are: whether anything answers it is a routing |
| 1900 | question this module deliberately does not pretend to answer. |
| 1901 | `nav_id` is the door this count decorates, so the app list can read |
| 1902 | "Invoices - 5 overdue" without a second surface to maintain; it is |
| 1903 | optional because a queue can belong to a package that ships no page |
| 1904 | at all (app-intake is one). |
| 1905 | """ |
| 1906 | entries = _list_field(payload, package_id=package_id, section="attention") |
| 1907 | normalized: list[dict[str, Any]] = [] |
| 1908 | seen: set[str] = set() |
| 1909 | for entry in entries: |
| 1910 | mapping = _entry_mapping(entry, package_id=package_id, section="attention") |
| 1911 | attention_id = _required_text(mapping, "id", package_id=package_id) |
| 1912 | if not _ATTENTION_ID_RE.fullmatch(attention_id): |
| 1913 | raise InvalidPackageManifestError( |
| 1914 | f"Invalid package attention id: {attention_id}") |
| 1915 | if attention_id in seen: |
| 1916 | raise InvalidPackageManifestError( |
| 1917 | f"Duplicate package attention id: {attention_id}") |
| 1918 | seen.add(attention_id) |
| 1919 | |
| 1920 | declared = _normalize_attention_declaration(mapping, attention_id) |
| 1921 | if declared is None: |
| 1922 | object_id = _required_text(mapping, "object_id", package_id=package_id) |
| 1923 | if not validate_object_id(object_id): |
| 1924 | raise InvalidPackageManifestError( |
| 1925 | f"Invalid package attention object_id: {object_id}") |
| 1926 | # `reads`: the collections the provider folds its number from. |
| 1927 | # The number is computed with no viewer, so it is shown only to |
| 1928 | # a viewer who may read every row of each (object_attention. |
| 1929 | # provider_shown_to); without it, only to admins. |
| 1930 | try: |
| 1931 | reads = object_attention.parse_reads(mapping.get("reads")) |
| 1932 | except object_attention.InvalidDeclarationError as exc: |
| 1933 | raise InvalidPackageManifestError( |
| 1934 | f"Package attention {attention_id}: {exc}") from exc |
| 1935 | declared = {"object_id": object_id, "collection": "", "where": "", "detail": "", |
| 1936 | "reads": object_attention.canonical_json(reads)} |
| 1937 | elif "reads" in mapping: |
| 1938 | raise InvalidPackageManifestError( |
| 1939 | f"Package attention {attention_id}: a declared count is counted for each " |
| 1940 | "viewer over the rows they may read; reads is for a provider (object_id)") |
| 1941 | |
| 1942 | label = _required_text(mapping, "label", package_id=package_id) |
| 1943 | path = _required_text(mapping, "path", package_id=package_id) |
| 1944 | if not path.startswith("/"): |
| 1945 | raise InvalidPackageManifestError( |
| 1946 | f"Package attention path must start with '/': {attention_id}" |
| 1947 | ) |
| 1948 | if any(character.isspace() for character in path): |
| 1949 | # A count nobody can click is a number on a poster. A path |
| 1950 | # with a space or a newline in it is both a link that never |
| 1951 | # resolves and a TSV cell that can break the row it lives in. |
| 1952 | raise InvalidPackageManifestError( |
| 1953 | f"Package attention path may not contain whitespace: {attention_id}" |
| 1954 | ) |
| 1955 | |
| 1956 | nav_id = _optional_text(mapping.get("nav_id")) or "" |
| 1957 | if nav_id and not _NAV_ID_RE.fullmatch(nav_id): |
| 1958 | raise InvalidPackageManifestError( |
| 1959 | f"Invalid package attention nav_id: {attention_id}") |
| 1960 | |
| 1961 | severity = (_optional_text(mapping.get("severity")) |
| 1962 | or _ATTENTION_DEFAULT_SEVERITY).lower() |
| 1963 | if severity not in _ATTENTION_SEVERITIES: |
| 1964 | raise InvalidPackageManifestError( |
| 1965 | f"Package attention severity must be normal|warning|urgent: {attention_id}" |
| 1966 | ) |
| 1967 | |
| 1968 | normalized.append({ |
| 1969 | "id": attention_id, |
| 1970 | **declared, |
| 1971 | "label": label, |
| 1972 | "path": path, |
| 1973 | "nav_id": nav_id, |
| 1974 | "group": _optional_text(mapping.get("group")) or _ATTENTION_DEFAULT_GROUP, |
| 1975 | "severity": severity, |
| 1976 | }) |
| 1977 | return normalized |
| 1978 | |
| 1979 | |
| 1980 | def _normalize_attention_declaration( |
| 1981 | mapping: Mapping[str, Any], attention_id: str, |
| 1982 | ) -> dict[str, str] | None: |
| 1983 | """The `collection` + `where` (+ `detail`) form of an attention entry, |
| 1984 | validated and stored as canonical JSON text; None for a provider entry. |
| 1985 | |
| 1986 | Exactly one of `object_id` and `collection`: an entry naming both |
| 1987 | would have two definitions of one number, and whichever the daemon or |
| 1988 | the page happened to prefer would silently win. The vocabulary and its |
| 1989 | reasons are object_attention's. |
| 1990 | """ |
| 1991 | collection = _optional_text(mapping.get("collection")) |
| 1992 | if not collection: |
| 1993 | for key in ("where", "detail"): |
| 1994 | if key in mapping: |
| 1995 | raise InvalidPackageManifestError( |
| 1996 | f"Package attention {key} needs a collection: {attention_id}") |
| 1997 | return None |
| 1998 | if _optional_text(mapping.get("object_id")): |
| 1999 | raise InvalidPackageManifestError( |
| 2000 | f"Package attention names both object_id and collection: {attention_id}") |
| 2001 | if not _ATTENTION_COLLECTION_RE.fullmatch(collection): |
| 2002 | raise InvalidPackageManifestError( |
| 2003 | f"Invalid package attention collection: {attention_id}") |
| 2004 | try: |
| 2005 | where = object_attention.parse_where(mapping.get("where")) |
| 2006 | detail = object_attention.parse_detail(mapping.get("detail")) |
| 2007 | except object_attention.InvalidDeclarationError as exc: |
| 2008 | raise InvalidPackageManifestError( |
| 2009 | f"Package attention {attention_id}: {exc}") from exc |
| 2010 | return { |
| 2011 | "object_id": "", |
| 2012 | "collection": collection, |
| 2013 | "where": object_attention.canonical_json(where), |
| 2014 | "detail": object_attention.canonical_json(detail), |
| 2015 | "reads": "", |
| 2016 | } |
| 2017 | |
| 2018 | |
| 2019 | def _load_attention_sources( |
| 2020 | base_dir: Path, |
| 2021 | *, |
| 2022 | roots: Iterable[Path] | None = None, |
| 2023 | ) -> dict[str, dict[str, str]] | None: |
| 2024 | """Every attention source currently registered, keyed by record id. |
| 2025 | |
| 2026 | ``None`` means the `attention_sources` collection is not installed at |
| 2027 | all (app-nav absent). Same posture as `_load_nav_entries`: a package |
| 2028 | must never fail to install because the home screen is missing, any |
| 2029 | more than an app should fail because nobody has looked at it yet. |
| 2030 | """ |
| 2031 | try: |
| 2032 | rows = object_records.read_collection_records( |
| 2033 | ATTENTION_COLLECTION, base_dir=base_dir, roots=roots) |
| 2034 | except (object_collections.CollectionNotFoundError, |
| 2035 | object_collections.InvalidCollectionNameError): |
| 2036 | return None |
| 2037 | except (OSError, ValueError): |
| 2038 | # A hand-edited row must not make a package uninstallable, the |
| 2039 | # same posture _load_nav_entries takes. |
| 2040 | return {} |
| 2041 | return {str(row.get("id") or ""): dict(row) for row in rows if row.get("id")} |
| 2042 | |
| 2043 | |
| 2044 | def _attention_change( |
| 2045 | entry: Mapping[str, Any], |
| 2046 | *, |
| 2047 | existing: Mapping[str, Mapping[str, str]], |
| 2048 | package_id: str, |
| 2049 | installable_object_ids: set[str], |
| 2050 | installable_collections: set[str], |
| 2051 | base_dir: Path, |
| 2052 | warnings: list[str], |
| 2053 | ) -> dict[str, Any]: |
| 2054 | live = existing.get(entry["id"]) |
| 2055 | if live is None: |
| 2056 | action = "create" |
| 2057 | elif all(str(live.get(field) or "") == str(entry[field]) |
| 2058 | for field in _ATTENTION_PACKAGE_FIELDS): |
| 2059 | # Every package-owned field is compared, nav_id and severity |
| 2060 | # included, so a plan that says "unchanged" is one where nothing |
| 2061 | # at all is about to be written. |
| 2062 | action = "unchanged" |
| 2063 | else: |
| 2064 | action = "update" |
| 2065 | |
| 2066 | if entry["collection"]: |
| 2067 | if (entry["collection"] not in installable_collections |
| 2068 | and not (base_dir / "schemas" / f"{entry['collection']}.json").is_file()): |
| 2069 | # Same failure, same answer: a count of a collection that will |
| 2070 | # not exist reads zero forever. |
| 2071 | warnings.append( |
| 2072 | f"Attention source {entry['id']} counts a collection this install " |
| 2073 | f"will not provide: {entry['collection']}" |
| 2074 | ) |
| 2075 | elif entry["object_id"] not in installable_object_ids: |
| 2076 | # A counter aimed at an object that will not exist reads as zero |
| 2077 | # forever, and a queue that reads zero forever is indistinguishable |
| 2078 | # from a queue that is empty. That silent failure is the entire |
| 2079 | # reason this section exists, so it blocks the install. |
| 2080 | warnings.append( |
| 2081 | f"Attention source {entry['id']} targets an object this install " |
| 2082 | f"will not provide: {entry['object_id']}" |
| 2083 | ) |
| 2084 | |
| 2085 | # Two packages writing one attention_sources row is two definitions of |
| 2086 | # what needs a human, where whichever installed last silently wins. |
| 2087 | # Unlike nav there is no path-collision rule: two queues legitimately |
| 2088 | # point at one list (an orders page can be both "to pick" and "to |
| 2089 | # invoice"), and blocking that would be a false blocker. |
| 2090 | owner = str((live or {}).get("package") or "") |
| 2091 | if owner and owner != package_id: |
| 2092 | warnings.append( |
| 2093 | f"Attention source {entry['id']} is already registered by another " |
| 2094 | f"package: {owner}" |
| 2095 | ) |
| 2096 | |
| 2097 | return { |
| 2098 | "id": entry["id"], |
| 2099 | # The declaration's three keys only when there is a declaration, so |
| 2100 | # a provider entry's plan reads exactly as it always has. |
| 2101 | **{field: entry[field] for field in _ATTENTION_PACKAGE_FIELDS |
| 2102 | if entry[field] or field not in _ATTENTION_OPTIONAL_FIELDS}, |
| 2103 | "exists": live is not None, |
| 2104 | "action": action, |
| 2105 | } |
| 2106 | |
| 2107 | |
| 2108 | def _stale_schema_owner( |
| 2109 | collection: str, |
| 2110 | *, |
| 2111 | installing: str, |
| 2112 | root: Path | str | None, |
| 2113 | base_dir: Path, |
| 2114 | ) -> str | None: |
| 2115 | """The installed package that owns `collection`'s schema when this tree |
| 2116 | ships a different one for it, else None. |
| 2117 | |
| 2118 | A package may write rows into a collection another package owns |
| 2119 | (app-nav's `attention_sources`, written by whichever package declares a |
| 2120 | queue). Those rows are written under the schema the box has installed, |
| 2121 | and after an upgrade that is the OLD one until the owner is reinstalled: |
| 2122 | 2026.11v3's attention_sources required `object_id`, which the declared |
| 2123 | counts that came after it do not have. Install order, which an |
| 2124 | alphabetical deploy loop leaves to the package names, must not decide |
| 2125 | whether such a row can be written, and the old schema is not the judge |
| 2126 | of a row written for the new one -- so a caller that finds an owner here |
| 2127 | defers its rows (the owner's install writes them, see |
| 2128 | _register_installed_declarations) instead of refusing the whole install. |
| 2129 | Judged by the owner's recorded baseline against the schema its manifest |
| 2130 | ships under `root`, so an operator's own edit to the live schema is |
| 2131 | neither seen nor overwritten. |
| 2132 | """ |
| 2133 | if root is None: |
| 2134 | return None |
| 2135 | baselines = object_package_baselines.list_baselines(base_dir=base_dir) |
| 2136 | for owner_id, baseline in sorted(baselines.items()): |
| 2137 | if owner_id == installing or not validate_package_id(owner_id): |
| 2138 | continue |
| 2139 | installed_body = (baseline.get("schema_bodies") or {}).get(collection) |
| 2140 | if installed_body is None: |
| 2141 | continue |
| 2142 | owner_dir = Path(root) / owner_id |
| 2143 | try: |
| 2144 | owner = _load_package(owner_id, owner_dir) |
| 2145 | for entry in owner["schemas"]: |
| 2146 | if entry["collection"] != collection: |
| 2147 | continue |
| 2148 | payload = json.loads(_package_file(owner_dir, entry["path"]).read_text(encoding="utf-8")) |
| 2149 | shipped = object_schemas.normalize_declaration(collection, payload) |
| 2150 | return None if shipped == installed_body else owner_id |
| 2151 | except (InvalidPackageManifestError, InvalidPackageIdError, PackageInstallError, |
| 2152 | OSError, ValueError): |
| 2153 | continue |
| 2154 | return None |
| 2155 | |
| 2156 | |
| 2157 | def _apply_attention( |
| 2158 | attention: Iterable[Mapping[str, Any]], |
| 2159 | planned: Iterable[Mapping[str, Any]], |
| 2160 | *, |
| 2161 | package_id: str, |
| 2162 | base_dir: Path, |
| 2163 | roots: Iterable[Path] | None = None, |
| 2164 | root: Path | str | None = None, |
| 2165 | ) -> list[dict[str, Any]]: |
| 2166 | """Register the package's queues in the `attention_sources` collection. |
| 2167 | |
| 2168 | Two things are deliberately preserved across an install: |
| 2169 | |
| 2170 | **The operator's `operator_muted`** -- the one column an install never |
| 2171 | writes on an existing row. The package declares what a queue MEANS; |
| 2172 | the operator decides whether this deployment wants to be told about |
| 2173 | it, and an upgrade that silently un-mutes a counter somebody turned |
| 2174 | off is the same class of incident as one that restarts a paused |
| 2175 | nightly pass. |
| 2176 | |
| 2177 | **Somebody else's row** -- sources this package did not register are |
| 2178 | not touched and not deleted. Removing an `attention` entry from a |
| 2179 | manifest leaves the row alone, matching the rest of install: |
| 2180 | deregistering never destroys. (The rollup pass is what stops feeding |
| 2181 | a stale row, because it only executes providers it can still resolve.) |
| 2182 | |
| 2183 | A missing `attention_sources` collection is reported and skipped |
| 2184 | rather than raised. The home screen is not a dependency of being |
| 2185 | installable. |
| 2186 | |
| 2187 | A box upgraded from an older release can hold an older |
| 2188 | `attention_sources` schema than the one app-nav ships in this tree |
| 2189 | (`object_id` was required before declared counts). Given `root`, rows |
| 2190 | are then deferred -- status `skipped`, with `stale_schema_owner` -- rather |
| 2191 | than judged by a schema the owner is about to replace; app-nav's install |
| 2192 | registers them (_register_installed_declarations). Against a current |
| 2193 | schema a real validation error still raises and refuses the install. |
| 2194 | """ |
| 2195 | entries = list(attention) |
| 2196 | plans = list(planned) |
| 2197 | if not entries: |
| 2198 | return [] |
| 2199 | |
| 2200 | existing = _load_attention_sources(base_dir, roots=roots) |
| 2201 | if existing is None: |
| 2202 | return [ |
| 2203 | {**plan, "status": "skipped", |
| 2204 | "reason": f"{ATTENTION_COLLECTION} collection is not installed"} |
| 2205 | for plan in plans |
| 2206 | ] |
| 2207 | owner = _stale_schema_owner(ATTENTION_COLLECTION, installing=package_id, |
| 2208 | root=root, base_dir=base_dir) |
| 2209 | if owner is not None: |
| 2210 | return [ |
| 2211 | {**plan, "status": "skipped", "stale_schema_owner": owner, |
| 2212 | "reason": f"the installed {ATTENTION_COLLECTION} schema is older than the one " |
| 2213 | f"{owner} ships; installing {owner} registers this"} |
| 2214 | for plan in plans |
| 2215 | ] |
| 2216 | |
| 2217 | applied = [] |
| 2218 | for entry, plan in zip(entries, plans, strict=True): |
| 2219 | live = existing.get(entry["id"]) |
| 2220 | # A provider entry writes no declaration columns, unless it is |
| 2221 | # replacing a declaration that has to be cleared. |
| 2222 | row = {"package": package_id, |
| 2223 | **{field: entry[field] for field in _ATTENTION_PACKAGE_FIELDS |
| 2224 | if entry[field] or field not in _ATTENTION_OPTIONAL_FIELDS |
| 2225 | or str((live or {}).get(field) or "")}} |
| 2226 | if live is None: |
| 2227 | object_records.create_collection_record( |
| 2228 | ATTENTION_COLLECTION, |
| 2229 | {"id": entry["id"], "operator_muted": "false", **row}, |
| 2230 | base_dir=base_dir, roots=roots, actor=f"package:{package_id}", |
| 2231 | ) |
| 2232 | status = "written" |
| 2233 | elif all(str(live.get(field) or "") == row[field] for field in row): |
| 2234 | status = "unchanged" |
| 2235 | else: |
| 2236 | # `row` carries no operator_muted key at all, so the update |
| 2237 | # cannot reach that column even by accident. |
| 2238 | object_records.update_collection_record( |
| 2239 | ATTENTION_COLLECTION, entry["id"], row, |
| 2240 | base_dir=base_dir, roots=roots, actor=f"package:{package_id}", |
| 2241 | ) |
| 2242 | status = "updated" |
| 2243 | |
| 2244 | applied.append({**plan, "status": status, |
| 2245 | "destination": f"collections/{ATTENTION_COLLECTION}/{entry['id']}"}) |
| 2246 | return applied |
| 2247 | |
| 2248 | |
| 2249 | def _installed_declarations( |
| 2250 | package_id: str, |
| 2251 | baseline: Mapping[str, Any], |
| 2252 | *, |
| 2253 | root: Path | str, |
| 2254 | ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]] | None: |
| 2255 | """(nav, attention) an installed package declared, or None if unknown. |
| 2256 | |
| 2257 | From its baseline when the install recorded them. A baseline stamped |
| 2258 | before they were recorded falls back to the manifest under `root`, but |
| 2259 | only when that manifest is the version installed: a newer manifest on |
| 2260 | disk would register doors and queues for code this box does not run. |
| 2261 | """ |
| 2262 | nav, attention = baseline.get("nav"), baseline.get("attention") |
| 2263 | if isinstance(nav, list) and isinstance(attention, list): |
| 2264 | return ([dict(e) for e in nav if isinstance(e, Mapping)], |
| 2265 | [dict(e) for e in attention if isinstance(e, Mapping)]) |
| 2266 | try: |
| 2267 | package = _load_package(package_id, _package_dir(package_id, root)) |
| 2268 | except (InvalidPackageIdError, InvalidPackageManifestError, PackageNotFoundError, |
| 2269 | OSError, ValueError): |
| 2270 | return None |
| 2271 | if str(package.get("version")) != str(baseline.get("version")): |
| 2272 | return None |
| 2273 | return package["nav"], package["attention"] |
| 2274 | |
| 2275 | |
| 2276 | def _register_installed_declarations( |
| 2277 | installing: str, |
| 2278 | *, |
| 2279 | nav: bool, |
| 2280 | attention: bool, |
| 2281 | root: Path | str, |
| 2282 | base_dir: Path, |
| 2283 | roots: Iterable[Path] | None = None, |
| 2284 | ) -> tuple[list[dict[str, Any]], list[str]]: |
| 2285 | """Register the nav entries (when `nav`) and attention sources (when |
| 2286 | `attention`) of every installed package other than `installing` that are |
| 2287 | not registered yet. Returns (what was registered, warnings). |
| 2288 | |
| 2289 | Only MISSING rows are written: a row that exists -- this package's, |
| 2290 | another package's, or one an operator has hidden or muted -- is left |
| 2291 | exactly as it is, so this cannot undo a choice or settle a collision. |
| 2292 | The rows are written as their own package's (`package` column), the same |
| 2293 | rows that package's install would have written had app-nav been there. |
| 2294 | Runs only when this install provides the registry, so an operator who |
| 2295 | deleted a row sees it come back only when app-nav itself is installed |
| 2296 | again (`operator_hidden` is the way to keep a door off the menu). |
| 2297 | |
| 2298 | A package whose declarations cannot be known (a baseline from before |
| 2299 | they were recorded, and no manifest of the installed version under |
| 2300 | `root`) is named in a warning rather than skipped in silence. |
| 2301 | """ |
| 2302 | if not nav and not attention: |
| 2303 | return [], [] |
| 2304 | registered: list[dict[str, Any]] = [] |
| 2305 | warnings: list[str] = [] |
| 2306 | baselines = object_package_baselines.list_baselines(base_dir=base_dir) |
| 2307 | for other_id, baseline in sorted(baselines.items()): |
| 2308 | if other_id == installing or not validate_package_id(other_id): |
| 2309 | continue |
| 2310 | declared = _installed_declarations(other_id, baseline, root=root) |
| 2311 | if declared is None: |
| 2312 | warnings.append( |
| 2313 | f"{other_id}: what it declares for nav and attention is not recorded " |
| 2314 | f"and its installed version's manifest is not under {root}, so its " |
| 2315 | f"doors and queues (if any) were not registered; reinstall it to " |
| 2316 | f"register them" |
| 2317 | ) |
| 2318 | continue |
| 2319 | other_nav, other_attention = declared |
| 2320 | if nav and other_nav: |
| 2321 | live = _load_nav_entries(base_dir, roots=roots) |
| 2322 | missing = [entry for entry in other_nav if live is not None and entry["id"] not in live] |
| 2323 | for item in _apply_nav(missing, [{"id": entry["id"]} for entry in missing], |
| 2324 | package_id=other_id, base_dir=base_dir, roots=roots): |
| 2325 | registered.append({"package": other_id, "kind": "nav", **item}) |
| 2326 | if attention and other_attention: |
| 2327 | live = _load_attention_sources(base_dir, roots=roots) |
| 2328 | missing = [entry for entry in other_attention |
| 2329 | if live is not None and entry["id"] not in live] |
| 2330 | for item in _apply_attention(missing, [{"id": entry["id"]} for entry in missing], |
| 2331 | package_id=other_id, base_dir=base_dir, roots=roots, |
| 2332 | root=root): |
| 2333 | registered.append({"package": other_id, "kind": "attention", **item}) |
| 2334 | return registered, warnings |
| 2335 | |
| 2336 | |
| 2337 | def iter_connectors(*, root: Path | str = PACKAGES_DIR) -> list[dict[str, str]]: |
| 2338 | """Every connector declaration under a package root, each with its module |
| 2339 | resolved to an absolute path proven to live INSIDE its package. Robust to a |
| 2340 | single bad package: a manifest that won't parse, or a module that is missing |
| 2341 | or escapes the package dir, is skipped (never raises) so one bad package |
| 2342 | can't blind the whole reconcile pass.""" |
| 2343 | packages_root = Path(root) |
| 2344 | if not packages_root.is_dir(): |
| 2345 | return [] |
| 2346 | out: list[dict[str, str]] = [] |
| 2347 | for path in sorted(packages_root.iterdir(), key=lambda item: item.name): |
| 2348 | if not path.is_dir() or not validate_package_id(path.name): |
| 2349 | continue |
| 2350 | if not (path / MANIFEST_FILE).is_file(): |
| 2351 | continue |
| 2352 | try: |
| 2353 | package = _load_package(path.name, path) |
| 2354 | except (InvalidPackageManifestError, InvalidPackageIdError, OSError, ValueError): |
| 2355 | continue |
| 2356 | for decl in package.get("connectors", []): |
| 2357 | status = _package_file_status(path, decl["module"]) |
| 2358 | if not status["exists"]: # missing module, or escapes the package |
| 2359 | continue |
| 2360 | out.append({ |
| 2361 | "package_id": package["id"], |
| 2362 | "collection": decl["collection"], |
| 2363 | "module": str((path / decl["module"]).resolve()), |
| 2364 | "entry": decl["entry"], |
| 2365 | }) |
| 2366 | return out |
| 2367 | |
| 2368 | |
| 2369 | def _normalize_dependencies(payload: Any, *, package_id: str) -> list[dict[str, str | None]]: |
| 2370 | entries = _list_field(payload, package_id=package_id, section="dependencies") |
| 2371 | normalized = [] |
| 2372 | for entry in entries: |
| 2373 | if isinstance(entry, str): |
| 2374 | dependency_id = entry |
| 2375 | version = None |
| 2376 | else: |
| 2377 | mapping = _entry_mapping(entry, package_id=package_id, section="dependencies") |
| 2378 | dependency_id = _required_text(mapping, "id", package_id=package_id) |
| 2379 | version = _optional_text(mapping.get("version")) |
| 2380 | if not validate_package_id(dependency_id): |
| 2381 | raise InvalidPackageManifestError(f"Invalid package dependency id: {dependency_id}") |
| 2382 | normalized.append({"id": dependency_id, "version": version}) |
| 2383 | return normalized |
| 2384 | |
| 2385 | |
| 2386 | def _object_change( |
| 2387 | entry: Mapping[str, str], |
| 2388 | *, |
| 2389 | package_dir: Path, |
| 2390 | object_roots: Iterable[Path] | None, |
| 2391 | warnings: list[str], |
| 2392 | ) -> dict[str, Any]: |
| 2393 | file_status = _package_file_status(package_dir, entry["path"]) |
| 2394 | if not file_status["exists"]: |
| 2395 | warnings.append(f"Missing package object file: {entry['path']}") |
| 2396 | installed = resolve_object_id(entry["id"], object_roots) is not None |
| 2397 | return { |
| 2398 | "id": entry["id"], |
| 2399 | "path": entry["path"], |
| 2400 | "exists": file_status["exists"], |
| 2401 | "action": "replace" if installed else "create", |
| 2402 | "installed": installed, |
| 2403 | } |
| 2404 | |
| 2405 | |
| 2406 | def _schema_change( |
| 2407 | entry: Mapping[str, str], |
| 2408 | *, |
| 2409 | package_dir: Path, |
| 2410 | base_dir: Path, |
| 2411 | warnings: list[str], |
| 2412 | ) -> dict[str, Any]: |
| 2413 | file_status = _package_file_status(package_dir, entry["path"]) |
| 2414 | if not file_status["exists"]: |
| 2415 | warnings.append(f"Missing package schema file: {entry['path']}") |
| 2416 | else: |
| 2417 | # Judged in the plan, not only at install, so a dry run says what is |
| 2418 | # wrong and the install is refused before anything is written. |
| 2419 | try: |
| 2420 | payload = json.loads(_package_file(package_dir, entry["path"]).read_text(encoding="utf-8")) |
| 2421 | object_schemas.normalize_declaration(entry["collection"], payload) |
| 2422 | except json.JSONDecodeError: |
| 2423 | warnings.append(f"Package schema contains invalid JSON: {entry['path']}") |
| 2424 | except ValueError as exc: |
| 2425 | warnings.append(f"Package schema is invalid: {entry['path']}: {exc}") |
| 2426 | installed = (base_dir / "schemas" / f"{entry['collection']}.json").is_file() |
| 2427 | return { |
| 2428 | "collection": entry["collection"], |
| 2429 | "path": entry["path"], |
| 2430 | "exists": file_status["exists"], |
| 2431 | "action": "replace" if installed else "create", |
| 2432 | "installed": installed, |
| 2433 | } |
| 2434 | |
| 2435 | |
| 2436 | def _seed_change( |
| 2437 | entry: Mapping[str, str], |
| 2438 | *, |
| 2439 | package_dir: Path, |
| 2440 | base_dir: Path, |
| 2441 | warnings: list[str], |
| 2442 | ) -> dict[str, Any]: |
| 2443 | file_status = _package_file_status(package_dir, entry["path"]) |
| 2444 | if not file_status["exists"]: |
| 2445 | warnings.append(f"Missing package seed file: {entry['path']}") |
| 2446 | installed = (base_dir / "collections" / entry["collection"] / "records.tsv").is_file() |
| 2447 | return { |
| 2448 | "collection": entry["collection"], |
| 2449 | "path": entry["path"], |
| 2450 | "exists": file_status["exists"], |
| 2451 | # Seed is install-once: on an upgrade where the collection already has |
| 2452 | # records, seeding is skipped so live data is preserved (not merged). |
| 2453 | "action": "skip" if installed else "create", |
| 2454 | "installed": installed, |
| 2455 | } |
| 2456 | |
| 2457 | |
| 2458 | def _migration_change( |
| 2459 | entry: Mapping[str, str], |
| 2460 | *, |
| 2461 | package: str, |
| 2462 | package_dir: Path, |
| 2463 | base_dir: Path, |
| 2464 | warnings: list[str], |
| 2465 | ) -> dict[str, Any]: |
| 2466 | file_status = _package_file_status(package_dir, entry["path"]) |
| 2467 | if not file_status["exists"]: |
| 2468 | warnings.append(f"Missing package migration file: {entry['path']}") |
| 2469 | marker = base_dir / PACKAGE_MIGRATIONS_DIR / package / f"{entry['id']}.json" |
| 2470 | applied = marker.is_file() |
| 2471 | return { |
| 2472 | "id": entry["id"], |
| 2473 | "path": entry["path"], |
| 2474 | "exists": file_status["exists"], |
| 2475 | "action": "skip" if applied else "apply", |
| 2476 | "applied": applied, |
| 2477 | } |
| 2478 | |
| 2479 | |
| 2480 | def _permission_change( |
| 2481 | entry: Mapping[str, str], |
| 2482 | *, |
| 2483 | package_id: str, |
| 2484 | package_dir: Path, |
| 2485 | base_dir: Path, |
| 2486 | warnings: list[str], |
| 2487 | ) -> dict[str, Any]: |
| 2488 | change = { |
| 2489 | "path": entry["path"], |
| 2490 | "action": "merge", |
| 2491 | "exists": False, |
| 2492 | "rules": 0, |
| 2493 | "new_rules": 0, |
| 2494 | } |
| 2495 | file_status = _package_file_status(package_dir, entry["path"]) |
| 2496 | if not file_status["exists"]: |
| 2497 | warnings.append(f"Missing package permissions file: {entry['path']}") |
| 2498 | return change |
| 2499 | change["exists"] = True |
| 2500 | |
| 2501 | try: |
| 2502 | rules = _load_permission_rules(package_dir, entry, package_id=package_id) |
| 2503 | except PackageInstallError as exc: |
| 2504 | warnings.append(str(exc)) |
| 2505 | return change |
| 2506 | |
| 2507 | change["rules"] = len(rules) |
| 2508 | try: |
| 2509 | policy = object_permission_store.load_policy(base_dir) |
| 2510 | existing_keys = {_rule_merge_key(rule) for rule in policy.rules} |
| 2511 | except ValueError: |
| 2512 | existing_keys = set() |
| 2513 | change["new_rules"] = sum(1 for rule in rules if _rule_merge_key(rule) not in existing_keys) |
| 2514 | return change |
| 2515 | |
| 2516 | |
| 2517 | def _load_permission_rules( |
| 2518 | package_dir: Path, |
| 2519 | entry: Mapping[str, str], |
| 2520 | *, |
| 2521 | package_id: str, |
| 2522 | ) -> list[object_permissions.PermissionRule]: |
| 2523 | return _load_permission_fragment(package_dir, entry, package_id=package_id)[0] |
| 2524 | |
| 2525 | |
| 2526 | _PERMISSION_FILE_KEYS = ("$schema", "rules", "retracted") |
| 2527 | |
| 2528 | |
| 2529 | def _load_permission_fragment( |
| 2530 | package_dir: Path, |
| 2531 | entry: Mapping[str, str], |
| 2532 | *, |
| 2533 | package_id: str, |
| 2534 | ) -> tuple[list[object_permissions.PermissionRule], list[object_permissions.PermissionRule]]: |
| 2535 | """One fragment file as (rules it ships, rules it retracts). |
| 2536 | |
| 2537 | `retracted` is optional and has the same rule shape as `rules`; see |
| 2538 | `_permission_retractions` for what it does and why it exists. Every rule |
| 2539 | is held to DRON first (`object_permissions.check_rule_declaration`), so a |
| 2540 | rule that would not do what it says refuses the install instead. |
| 2541 | """ |
| 2542 | source = _package_file(package_dir, entry["path"]) |
| 2543 | try: |
| 2544 | payload = json.loads(source.read_text(encoding="utf-8")) |
| 2545 | except (OSError, json.JSONDecodeError) as exc: |
| 2546 | raise PackageInstallError( |
| 2547 | f"Package permissions file contains invalid JSON: {entry['path']}" |
| 2548 | ) from exc |
| 2549 | |
| 2550 | path = entry["path"] |
| 2551 | # DRON has one shape for a rules file: an object with `rules` and an |
| 2552 | # optional `retracted` (dron/dron-permissions.schema.json). A bare list, |
| 2553 | # or a misspelt `retracted`, used to load as if it were right -- the |
| 2554 | # second silently withdrawing nothing. |
| 2555 | if not isinstance(payload, dict) or not isinstance(payload.get("rules"), list): |
| 2556 | raise PackageInstallError( |
| 2557 | f"Package permissions file must contain an object with a rules list: {path}" |
| 2558 | ) |
| 2559 | for key in payload: |
| 2560 | if key not in _PERMISSION_FILE_KEYS: |
| 2561 | raise PackageInstallError( |
| 2562 | f"Package permissions file {path}: unknown key {key!r}" |
| 2563 | f"{object_permissions.did_you_mean(key, _PERMISSION_FILE_KEYS)}" |
| 2564 | ) |
| 2565 | retracted_payload = payload.get("retracted", []) |
| 2566 | if not isinstance(retracted_payload, list): |
| 2567 | raise PackageInstallError( |
| 2568 | f"Package permissions retracted must be a list: {path}" |
| 2569 | ) |
| 2570 | |
| 2571 | def parse(section: str, label: str, plural: str) -> list[object_permissions.PermissionRule]: |
| 2572 | parsed = [] |
| 2573 | for number, rule_payload in enumerate(payload.get(section, []), start=1): |
| 2574 | where = f"{path} {label} {number}" |
| 2575 | if not isinstance(rule_payload, dict): |
| 2576 | raise PackageInstallError(f"Package {plural} must be objects: {where}") |
| 2577 | try: |
| 2578 | object_permissions.check_rule_declaration(rule_payload) |
| 2579 | parsed.append(object_permissions.rule_from_dict({**rule_payload, "package": package_id})) |
| 2580 | except ValueError as exc: |
| 2581 | raise PackageInstallError(f"Package {label.replace('rule', 'permission rule')} is invalid: {where}: {exc}") from exc |
| 2582 | return parsed |
| 2583 | |
| 2584 | return (parse("rules", "rule", "permission rules"), |
| 2585 | parse("retracted", "retracted rule", "permissions retracted rules")) |
| 2586 | |
| 2587 | |
| 2588 | def _package_permission_rules( |
| 2589 | package: Mapping[str, Any], |
| 2590 | package_dir: Path, |
| 2591 | *, |
| 2592 | package_id: str, |
| 2593 | ) -> tuple[list[object_permissions.PermissionRule], list[object_permissions.PermissionRule]]: |
| 2594 | """Everything a package ships and everything it retracts, across all of |
| 2595 | its fragment files. |
| 2596 | |
| 2597 | Retirement is decided per PACKAGE, not per file: a rule moved from one |
| 2598 | fragment to another has not been retired. A rule that is both shipped |
| 2599 | and retracted is a contradiction the installer will not guess about -- |
| 2600 | whichever it applied last would win -- so it blocks the install like any |
| 2601 | other invalid fragment. |
| 2602 | """ |
| 2603 | shipped: list[object_permissions.PermissionRule] = [] |
| 2604 | retracted: list[object_permissions.PermissionRule] = [] |
| 2605 | for entry in package["permissions"]: |
| 2606 | rules, gone = _load_permission_fragment(package_dir, entry, package_id=package_id) |
| 2607 | shipped.extend(rules) |
| 2608 | retracted.extend(gone) |
| 2609 | shipped_keys = {_rule_merge_key(rule) for rule in shipped} |
| 2610 | for rule in retracted: |
| 2611 | if _rule_merge_key(rule) in shipped_keys: |
| 2612 | target = rule.collection or rule.object_id or "everything" |
| 2613 | raise PackageInstallError( |
| 2614 | f"Package {package_id} both ships and retracts a permission rule: " |
| 2615 | f"{rule.effect} {rule.principal} {sorted(rule.actions)} on {target}" |
| 2616 | ) |
| 2617 | return shipped, retracted |
| 2618 | |
| 2619 | |
| 2620 | def _rule_merge_key(rule: object_permissions.PermissionRule) -> str: |
| 2621 | payload = object_permissions.rule_to_dict(rule) |
| 2622 | payload.pop("reason", None) |
| 2623 | payload.pop("package", None) |
| 2624 | return json.dumps(payload, sort_keys=True) |
| 2625 | |
| 2626 | |
| 2627 | # --------------------------------------------------------------------------- |
| 2628 | # Retiring rules a package no longer ships |
| 2629 | # |
| 2630 | # THE PROBLEM. _merge_permission_rules only appends. A package that deleted |
| 2631 | # a rule (2026-11-28: fourteen public execute grants for objects nothing |
| 2632 | # ships) or tightened one (template_runs and thread_comments reads gained a |
| 2633 | # row filter -- a different rule, by the merge key) fixed FRESH installs |
| 2634 | # only. A box that already had the package kept the old, wider rule beside |
| 2635 | # the new one, and an allow that is still in the policy still allows. |
| 2636 | # |
| 2637 | # WHAT IS KNOWN ABOUT A LIVE RULE. Its `package` tag: who appended it. That |
| 2638 | # has been stamped since the first merge, but it is not enough on its own to |
| 2639 | # remove anything, because the operator edits policy by GET / change / PUT |
| 2640 | # and the tag rides along: a rule tagged app-notes that app-notes does not |
| 2641 | # ship is EITHER what an old app-notes shipped OR the operator's edit of it. |
| 2642 | # Removing every such rule would undo the operator's work on every upgrade |
| 2643 | # (docs/upgrade-and-customization.md: an upgrade replaces the package layer |
| 2644 | # and never the local one). |
| 2645 | # |
| 2646 | # SO A RULE IS REMOVED ONLY WHEN TWO THINGS AGREE: the live rule is tagged |
| 2647 | # as this package's, AND it is identical (the merge key: everything but |
| 2648 | # `reason`) to a rule this package is KNOWN to have shipped and no longer |
| 2649 | # ships. "Known" comes from one of two places: |
| 2650 | # |
| 2651 | # 1. the recorded baseline (`permissions` in data/package_baselines/ |
| 2652 | # <id>.json, written by every install from now on): what the installed |
| 2653 | # version shipped. Baseline minus shipped is retired automatically, the |
| 2654 | # same three-way comparison objects and schemas already get. |
| 2655 | # 2. the fragment's `retracted` list: rules an earlier version shipped, |
| 2656 | # written out by the package author. This is the only thing that |
| 2657 | # reaches a box installed before (1) existed, which has no record of |
| 2658 | # what it was given. |
| 2659 | # |
| 2660 | # An operator's edit changes the key, so it matches neither; an operator's |
| 2661 | # own rule has no tag. Both are left and REPORTED, as is a tagged rule |
| 2662 | # nothing accounts for (`unaccounted`): the installer says what it saw and |
| 2663 | # a person decides. GET /permissions/unshipped lists them at any time. |
| 2664 | # |
| 2665 | # WHAT WAS REJECTED. |
| 2666 | # - Treating the tag as ownership and dropping every tagged rule the |
| 2667 | # package does not ship: see above, it destroys edits. |
| 2668 | # - Removing an untagged rule identical to a retired one. It was in the |
| 2669 | # policy before the package was installed (the merge skipped it and |
| 2670 | # never tagged it), so it is the operator's; it is reported instead, |
| 2671 | # because it is now the only thing keeping that grant alive. |
| 2672 | # - Withholding a rule the operator deleted. Re-adding a shipped rule that |
| 2673 | # is missing is the existing append behaviour and is left alone here: a |
| 2674 | # reinstall is also how a wiped policy gets its package rules back. |
| 2675 | # |
| 2676 | # Two packages may ship the same rule; only the first to install is tagged. |
| 2677 | # When that one retires the rule and another installed package's baseline |
| 2678 | # still lists it, the rule changes hands instead of disappearing. |
| 2679 | # --------------------------------------------------------------------------- |
| 2680 | |
| 2681 | |
| 2682 | def _rule_baseline_payload(rule: object_permissions.PermissionRule) -> dict[str, Any]: |
| 2683 | payload = object_permissions.rule_to_dict(rule) |
| 2684 | payload.pop("package", None) |
| 2685 | return payload |
| 2686 | |
| 2687 | |
| 2688 | def _baseline_permission_rules( |
| 2689 | baseline: Mapping[str, Any] | None, |
| 2690 | ) -> list[object_permissions.PermissionRule] | None: |
| 2691 | """The rules a recorded baseline says were shipped, or None when it does |
| 2692 | not say (no baseline, one from before permissions were recorded, or one |
| 2693 | that cannot be read as rules). None means "unknown", never "no rules".""" |
| 2694 | if not isinstance(baseline, Mapping) or "permissions" not in baseline: |
| 2695 | return None |
| 2696 | recorded = baseline["permissions"] |
| 2697 | if not isinstance(recorded, list): |
| 2698 | return None |
| 2699 | try: |
| 2700 | return [object_permissions.rule_from_dict(payload) for payload in recorded] |
| 2701 | except ValueError: |
| 2702 | return None |
| 2703 | |
| 2704 | |
| 2705 | def _other_package_shippers(package_id: str, *, base_dir: Path) -> dict[str, str]: |
| 2706 | """merge key -> another installed package whose baseline lists that rule.""" |
| 2707 | shippers: dict[str, str] = {} |
| 2708 | baselines = object_package_baselines.list_baselines(base_dir=base_dir) |
| 2709 | for other_id, baseline in sorted(baselines.items()): |
| 2710 | if other_id == package_id: |
| 2711 | continue |
| 2712 | for rule in _baseline_permission_rules(baseline) or (): |
| 2713 | shippers.setdefault(_rule_merge_key(rule), other_id) |
| 2714 | return shippers |
| 2715 | |
| 2716 | |
| 2717 | def _permission_retractions( |
| 2718 | policy_rules: Iterable[object_permissions.PermissionRule], |
| 2719 | *, |
| 2720 | package_id: str, |
| 2721 | shipped: Iterable[object_permissions.PermissionRule], |
| 2722 | retracted: Iterable[object_permissions.PermissionRule], |
| 2723 | baseline_rules: Iterable[object_permissions.PermissionRule] | None, |
| 2724 | other_shippers: Callable[[], Mapping[str, str]], |
| 2725 | ) -> tuple[list[dict[str, Any]], tuple[object_permissions.PermissionRule, ...]]: |
| 2726 | """Decide what an install does to the rules already in the policy. |
| 2727 | |
| 2728 | Pure: returns (report entries, the policy's rules afterwards) and |
| 2729 | writes nothing, so a dry run and an install cannot disagree. New rules |
| 2730 | are not added here (_merge_permission_rules appends them afterwards). |
| 2731 | |
| 2732 | Each entry is `{"action", "because", "why", "rule"}`: |
| 2733 | |
| 2734 | - `remove` -- tagged as this package's and identical to a rule it |
| 2735 | retracts (`because: "retracted"`) or shipped at the last install and |
| 2736 | no longer ships (`"no_longer_shipped"`). |
| 2737 | - `reassign` -- the same, but another installed package still ships the |
| 2738 | rule (`"still_shipped_by:<id>"`): the tag moves to it. |
| 2739 | - `keep` -- left in place and worth a person's attention: an untagged |
| 2740 | rule identical to a retired one (`"operator_rule"`), or a rule tagged |
| 2741 | as this package's that it neither ships nor retires |
| 2742 | (`"unaccounted"`). |
| 2743 | """ |
| 2744 | shipped_keys = {_rule_merge_key(rule) for rule in shipped} |
| 2745 | retire: dict[str, tuple[str, str]] = {} |
| 2746 | for rule in retracted: |
| 2747 | retire[_rule_merge_key(rule)] = ( |
| 2748 | "retracted", |
| 2749 | rule.reason or "retracted by the package", |
| 2750 | ) |
| 2751 | for rule in baseline_rules or (): |
| 2752 | key = _rule_merge_key(rule) |
| 2753 | if key not in shipped_keys: |
| 2754 | retire.setdefault( |
| 2755 | key, |
| 2756 | ("no_longer_shipped", "shipped by the installed version and not by this one"), |
| 2757 | ) |
| 2758 | |
| 2759 | entries: list[dict[str, Any]] = [] |
| 2760 | remaining: list[object_permissions.PermissionRule] = [] |
| 2761 | shippers: Mapping[str, str] | None = None |
| 2762 | for rule in policy_rules: |
| 2763 | key = _rule_merge_key(rule) |
| 2764 | payload = object_permissions.rule_to_dict(rule) |
| 2765 | if key in retire and rule.package == package_id: |
| 2766 | because, why = retire[key] |
| 2767 | if shippers is None: |
| 2768 | shippers = other_shippers() |
| 2769 | other = shippers.get(key) |
| 2770 | if other is not None: |
| 2771 | entries.append({ |
| 2772 | "action": "reassign", |
| 2773 | "because": f"still_shipped_by:{other}", |
| 2774 | "why": f"{why}; {other} still ships it, so it is now recorded as {other}'s", |
| 2775 | "rule": payload, |
| 2776 | }) |
| 2777 | remaining.append(replace(rule, package=other)) |
| 2778 | else: |
| 2779 | entries.append({"action": "remove", "because": because, "why": why, "rule": payload}) |
| 2780 | continue |
| 2781 | if key in retire and rule.package is None: |
| 2782 | entries.append({ |
| 2783 | "action": "keep", |
| 2784 | "because": "operator_rule", |
| 2785 | "why": ( |
| 2786 | f"identical to a rule {package_id} has withdrawn ({retire[key][1]}), but " |
| 2787 | "not recorded as installed by it, so it is treated as yours and left in " |
| 2788 | "place; delete it from the policy if you do not want it" |
| 2789 | ), |
| 2790 | "rule": payload, |
| 2791 | }) |
| 2792 | elif key not in retire and rule.package == package_id and key not in shipped_keys: |
| 2793 | entries.append({ |
| 2794 | "action": "keep", |
| 2795 | "because": "unaccounted", |
| 2796 | "why": ( |
| 2797 | f"recorded as installed by {package_id}, which neither ships nor " |
| 2798 | "retracts it: either edited by hand, or shipped by a version from " |
| 2799 | "before this box recorded what packages ship. Left in place; delete " |
| 2800 | "it, or remove its package tag to keep it as your own" |
| 2801 | ), |
| 2802 | "rule": payload, |
| 2803 | }) |
| 2804 | remaining.append(rule) |
| 2805 | return entries, tuple(remaining) |
| 2806 | |
| 2807 | |
| 2808 | def _plan_permission_retractions( |
| 2809 | package_id: str, |
| 2810 | *, |
| 2811 | shipped: list[object_permissions.PermissionRule], |
| 2812 | retracted: list[object_permissions.PermissionRule], |
| 2813 | baseline: Mapping[str, Any] | None, |
| 2814 | policy: object_permissions.PermissionPolicy, |
| 2815 | base_dir: Path, |
| 2816 | ) -> tuple[list[dict[str, Any]], tuple[object_permissions.PermissionRule, ...]]: |
| 2817 | return _permission_retractions( |
| 2818 | policy.rules, |
| 2819 | package_id=package_id, |
| 2820 | shipped=shipped, |
| 2821 | retracted=retracted, |
| 2822 | baseline_rules=_baseline_permission_rules(baseline), |
| 2823 | other_shippers=lambda: _other_package_shippers(package_id, base_dir=base_dir), |
| 2824 | ) |
| 2825 | |
| 2826 | |
| 2827 | _RETRACTION_STATUS = {"remove": "removed", "reassign": "reassigned", "keep": "kept"} |
| 2828 | |
| 2829 | |
| 2830 | def _apply_permission_retractions( |
| 2831 | package_id: str, |
| 2832 | *, |
| 2833 | shipped: list[object_permissions.PermissionRule], |
| 2834 | retracted: list[object_permissions.PermissionRule], |
| 2835 | baseline: Mapping[str, Any] | None, |
| 2836 | base_dir: Path, |
| 2837 | ) -> list[dict[str, Any]]: |
| 2838 | """Retire this package's withdrawn rules from the policy; return the |
| 2839 | report entries with a `status`. Runs BEFORE the merge appends this |
| 2840 | version's rules, so a tightened rule is never in force beside the wide |
| 2841 | one it replaces, not even between the two writes.""" |
| 2842 | try: |
| 2843 | policy = object_permission_store.load_policy(base_dir) |
| 2844 | except ValueError: |
| 2845 | if shipped or retracted or _baseline_permission_rules(baseline): |
| 2846 | raise |
| 2847 | # A package with no rules, now or at its last install, has nothing |
| 2848 | # to retire and nothing to merge; an unreadable policy was never its |
| 2849 | # install's to fail on, and still is not. |
| 2850 | return [] |
| 2851 | entries, remaining = _plan_permission_retractions( |
| 2852 | package_id, |
| 2853 | shipped=shipped, |
| 2854 | retracted=retracted, |
| 2855 | baseline=baseline, |
| 2856 | policy=policy, |
| 2857 | base_dir=base_dir, |
| 2858 | ) |
| 2859 | if any(entry["action"] != "keep" for entry in entries): |
| 2860 | object_permission_store.save_policy( |
| 2861 | object_permissions.PermissionPolicy( |
| 2862 | access_mode=policy.access_mode, |
| 2863 | rules=remaining, |
| 2864 | roles=policy.roles, |
| 2865 | user_roles=policy.user_roles, |
| 2866 | admin_roles=policy.admin_roles, |
| 2867 | ), |
| 2868 | base_dir=base_dir, |
| 2869 | ) |
| 2870 | return [{**entry, "status": _RETRACTION_STATUS[entry["action"]]} for entry in entries] |
| 2871 | |
| 2872 | |
| 2873 | def unshipped_permission_rules( |
| 2874 | *, |
| 2875 | roots: Iterable[Path | str] = (PACKAGES_DIR,), |
| 2876 | base_dir: Path | str | None = None, |
| 2877 | ) -> dict[str, Any]: |
| 2878 | """The rules in the active policy that no installed package ships. |
| 2879 | |
| 2880 | The standing answer to "what is in my policy that did not come from the |
| 2881 | apps I have, as they are now?" -- what an upgrade's `permission_ |
| 2882 | retractions` reports per package, for the whole box at once and without |
| 2883 | installing anything. Read-only. |
| 2884 | |
| 2885 | An installed package is one with a recorded baseline; what it ships is |
| 2886 | read from its package directory under `roots` (first root that has it |
| 2887 | wins, the way the server resolves a package id). Each listed rule has a |
| 2888 | `state`: |
| 2889 | |
| 2890 | - `operator` -- no package tag: written by hand, or by a tool. |
| 2891 | - `retracted` -- tagged for an installed package whose files retract it: |
| 2892 | the next install of that package removes it. |
| 2893 | - `unaccounted` -- tagged for an installed package that neither ships |
| 2894 | nor retracts it: an edited package rule, or one from an older version. |
| 2895 | - `package_missing` -- tagged for a package that is not installed, or |
| 2896 | whose files are not on this box. |
| 2897 | |
| 2898 | A listed rule that is "wide" (an allow for `registered` or `public` with |
| 2899 | no collection and no object_id) also carries a one-line `wide` |
| 2900 | explanation, and `wide_rules` lists every such rule in the policy, |
| 2901 | listed or not. The starter policy used to ship one; it has no package |
| 2902 | tag, so no retraction removes it. |
| 2903 | |
| 2904 | A rule identical to one an installed package ships is not listed, |
| 2905 | whoever it is tagged for. Raises ValueError for an unreadable policy. |
| 2906 | """ |
| 2907 | base = resolve_base_dir(base_dir) |
| 2908 | policy = object_permission_store.load_policy(base) |
| 2909 | installed = sorted(object_package_baselines.list_baselines(base_dir=base)) |
| 2910 | |
| 2911 | shipped_keys: set[str] = set() |
| 2912 | retracted_keys: dict[str, set[str]] = {} |
| 2913 | readable: set[str] = set() |
| 2914 | warnings: list[str] = [] |
| 2915 | for package_id in installed: |
| 2916 | if not validate_package_id(package_id): |
| 2917 | continue |
| 2918 | package_dir = next( |
| 2919 | (Path(root) / package_id for root in roots |
| 2920 | if (Path(root) / package_id / MANIFEST_FILE).is_file()), |
| 2921 | None, |
| 2922 | ) |
| 2923 | if package_dir is None: |
| 2924 | continue |
| 2925 | try: |
| 2926 | package = _load_package(package_id, package_dir) |
| 2927 | shipped, retracted = _package_permission_rules( |
| 2928 | package, package_dir, package_id=package_id) |
| 2929 | except (InvalidPackageManifestError, PackageInstallError, PackageNotFoundError) as exc: |
| 2930 | warnings.append(f"{package_id}: {exc}") |
| 2931 | continue |
| 2932 | readable.add(package_id) |
| 2933 | shipped_keys.update(_rule_merge_key(rule) for rule in shipped) |
| 2934 | retracted_keys[package_id] = {_rule_merge_key(rule) for rule in retracted} |
| 2935 | |
| 2936 | listed = [] |
| 2937 | for index, rule in enumerate(policy.rules): |
| 2938 | key = _rule_merge_key(rule) |
| 2939 | if key in shipped_keys: |
| 2940 | continue |
| 2941 | if rule.package is None: |
| 2942 | state = "operator" |
| 2943 | elif rule.package not in readable: |
| 2944 | state = "package_missing" |
| 2945 | elif key in retracted_keys[rule.package]: |
| 2946 | state = "retracted" |
| 2947 | else: |
| 2948 | state = "unaccounted" |
| 2949 | entry = { |
| 2950 | "index": index, |
| 2951 | "state": state, |
| 2952 | "package": rule.package, |
| 2953 | "rule": object_permissions.rule_to_dict(rule), |
| 2954 | } |
| 2955 | why = object_permissions.wide_rule_reason(rule) |
| 2956 | if why is not None: |
| 2957 | entry["wide"] = why |
| 2958 | listed.append(entry) |
| 2959 | return { |
| 2960 | "rules": listed, |
| 2961 | "count": len(listed), |
| 2962 | "policy_rules": len(policy.rules), |
| 2963 | "installed_packages": installed, |
| 2964 | "wide_rules": wide_permission_rules(policy), |
| 2965 | # DRON mistakes in the stored file the engine reads loosely (a key it |
| 2966 | # ignores, a deny that never applies): object_permissions.stored_ |
| 2967 | # policy_findings. Indexes are positions in GET /permissions/policy. |
| 2968 | "findings": object_permission_store.stored_policy_findings(base), |
| 2969 | "warnings": warnings, |
| 2970 | } |
| 2971 | |
| 2972 | |
| 2973 | def wide_permission_rules(policy: object_permissions.PermissionPolicy) -> list[dict[str, Any]]: |
| 2974 | """Every rule in the policy that is "wide" (object_permissions.wide_rule_ |
| 2975 | reason), listed or not: a package could ship one, and it would still be |
| 2976 | the first thing to read. `index` is the position in GET /permissions/ |
| 2977 | policy, which is what a person removing it needs.""" |
| 2978 | found = [] |
| 2979 | for index, rule in enumerate(policy.rules): |
| 2980 | why = object_permissions.wide_rule_reason(rule) |
| 2981 | if why is not None: |
| 2982 | found.append({ |
| 2983 | "index": index, |
| 2984 | "package": rule.package, |
| 2985 | "why": why, |
| 2986 | "rule": object_permissions.rule_to_dict(rule), |
| 2987 | }) |
| 2988 | return found |
| 2989 | |
| 2990 | |
| 2991 | def _merge_permission_rules( |
| 2992 | rules: list[object_permissions.PermissionRule], |
| 2993 | *, |
| 2994 | base_dir: Path, |
| 2995 | ) -> tuple[int, int]: |
| 2996 | """Append new package rules to the policy; return (total, newly added). |
| 2997 | |
| 2998 | Append-only on purpose: what a package no longer ships is retired |
| 2999 | separately and first, by _apply_permission_retractions.""" |
| 3000 | policy = object_permission_store.load_policy(base_dir) |
| 3001 | existing_keys = {_rule_merge_key(rule) for rule in policy.rules} |
| 3002 | |
| 3003 | added = [] |
| 3004 | for rule in rules: |
| 3005 | if _rule_merge_key(rule) in existing_keys: |
| 3006 | continue |
| 3007 | added.append(rule) |
| 3008 | existing_keys.add(_rule_merge_key(rule)) |
| 3009 | |
| 3010 | if added: |
| 3011 | merged = object_permissions.PermissionPolicy( |
| 3012 | access_mode=policy.access_mode, |
| 3013 | rules=tuple(policy.rules) + tuple(added), |
| 3014 | roles=policy.roles, |
| 3015 | user_roles=policy.user_roles, |
| 3016 | admin_roles=policy.admin_roles, |
| 3017 | ) |
| 3018 | object_permission_store.save_policy(merged, base_dir=base_dir) |
| 3019 | |
| 3020 | return len(rules), len(added) |
| 3021 | |
| 3022 | |
| 3023 | def _path_change( |
| 3024 | entry: Mapping[str, str], |
| 3025 | *, |
| 3026 | package_dir: Path, |
| 3027 | section: str, |
| 3028 | action: str, |
| 3029 | warnings: list[str], |
| 3030 | ) -> dict[str, Any]: |
| 3031 | file_status = _package_file_status(package_dir, entry["path"]) |
| 3032 | if not file_status["exists"]: |
| 3033 | warnings.append(f"Missing package {section} file: {entry['path']}") |
| 3034 | return { |
| 3035 | "path": entry["path"], |
| 3036 | "exists": file_status["exists"], |
| 3037 | "action": action, |
| 3038 | } |
| 3039 | |
| 3040 | |
| 3041 | def _package_file_status(package_dir: Path, relative_path: str) -> dict[str, bool]: |
| 3042 | package_root = package_dir.resolve() |
| 3043 | candidate = package_dir / relative_path |
| 3044 | resolved = candidate.resolve(strict=False) |
| 3045 | inside = resolved == package_root or package_root in resolved.parents |
| 3046 | return { |
| 3047 | "exists": inside and candidate.is_file(), |
| 3048 | "inside_package": inside, |
| 3049 | } |
| 3050 | |
| 3051 | |
| 3052 | def _install_blockers( |
| 3053 | plan: Mapping[str, Any], |
| 3054 | *, |
| 3055 | package: Mapping[str, Any], |
| 3056 | allow_replace: bool, |
| 3057 | ) -> list[str]: |
| 3058 | blockers = [str(warning) for warning in plan.get("warnings", [])] |
| 3059 | |
| 3060 | if package["migrations"]: |
| 3061 | blockers.append("Package migration execution is not implemented yet") |
| 3062 | |
| 3063 | if not allow_replace: |
| 3064 | for entry in plan["objects"]: |
| 3065 | if entry["action"] == "replace": |
| 3066 | blockers.append(f"Object already exists; set allow_replace=true: {entry['id']}") |
| 3067 | for entry in plan["schemas"]: |
| 3068 | if entry["action"] == "replace": |
| 3069 | blockers.append( |
| 3070 | f"Schema already exists; set allow_replace=true: {entry['collection']}" |
| 3071 | ) |
| 3072 | |
| 3073 | # Existing seed data is NOT a blocker: seed is install-once, so an upgrade |
| 3074 | # of an already-installed package skips seeding and preserves live records |
| 3075 | # (see the seed apply step). This is what makes "upgrade the app, keep the |
| 3076 | # data" work — the package ships code + schema + a seed template, while the |
| 3077 | # records live outside the package in the server's data dir. |
| 3078 | |
| 3079 | return blockers |
| 3080 | |
| 3081 | |
| 3082 | def _package_file(package_dir: Path, relative_path: str) -> Path: |
| 3083 | status = _package_file_status(package_dir, relative_path) |
| 3084 | if not status["inside_package"]: |
| 3085 | raise PackageInstallError(f"Package file escapes package directory: {relative_path}") |
| 3086 | if not status["exists"]: |
| 3087 | raise PackageInstallError(f"Package file does not exist: {relative_path}") |
| 3088 | return package_dir / relative_path |
| 3089 | |
| 3090 | |
| 3091 | def _object_destination(entry: Mapping[str, str], object_root: Path) -> Path: |
| 3092 | relative = Path(entry["path"]) |
| 3093 | if relative.parts and relative.parts[0] == "objects": |
| 3094 | relative = Path(*relative.parts[1:]) |
| 3095 | if not relative.parts or relative.suffix != ".py": |
| 3096 | raise PackageInstallError(f"Package object path must point to a Python file: {entry['path']}") |
| 3097 | destination = object_root / relative |
| 3098 | _ensure_inside(destination, object_root, label="object") |
| 3099 | return destination |
| 3100 | |
| 3101 | |
| 3102 | def _ensure_inside(path: Path, root: Path, *, label: str) -> None: |
| 3103 | resolved_path = path.resolve(strict=False) |
| 3104 | resolved_root = root.resolve(strict=False) |
| 3105 | try: |
| 3106 | resolved_path.relative_to(resolved_root) |
| 3107 | except ValueError as exc: |
| 3108 | raise PackageInstallError(f"Package {label} destination escapes its root: {path}") from exc |
| 3109 | |
| 3110 | |
| 3111 | def _root_for_path(path: Path | None, roots: Iterable[Path]) -> Path | None: |
| 3112 | if path is None: |
| 3113 | return None |
| 3114 | for root in roots: |
| 3115 | try: |
| 3116 | _ensure_inside(path, root, label="object") |
| 3117 | except PackageInstallError: |
| 3118 | continue |
| 3119 | return root |
| 3120 | return None |
| 3121 | |
| 3122 | |
| 3123 | def _seed_refusal(record_id: str, exc: Exception) -> dict[str, str]: |
| 3124 | """How a merged seed row the collection refused is reported.""" |
| 3125 | if isinstance(exc, object_records.UniqueConstraintError): |
| 3126 | code = "unique_violation" |
| 3127 | elif isinstance(exc, object_records.RecordLockedError): |
| 3128 | code = "record_locked" |
| 3129 | elif isinstance(exc, object_records.CheckRefusedError): |
| 3130 | code = exc.code |
| 3131 | elif isinstance(exc, ValueError): |
| 3132 | code = "invalid_record" |
| 3133 | else: |
| 3134 | code = type(exc).__name__ |
| 3135 | return {"id": record_id, "code": code, "error": str(exc)[:300]} |
| 3136 | |
| 3137 | |
| 3138 | def _seed_unique_violations(collection: str, *, base_dir: Path) -> list[dict[str, Any]] | None: |
| 3139 | """The `unique` keys more than one row of a just-written seed holds, |
| 3140 | or None when the check could not run. Read-only: a report, never a |
| 3141 | gate on an install whose files are already written.""" |
| 3142 | try: |
| 3143 | return object_records.find_unique_violations(collection, base_dir=base_dir) |
| 3144 | except Exception: # noqa: BLE001 -- a report, never a gate |
| 3145 | return None |
| 3146 | |
| 3147 | |
| 3148 | def _seed_meets_locked_checks(collection: str, content: bytes, *, base_dir: Path) -> bool: |
| 3149 | """True when a fresh seed must go row by row: its collection's schema |
| 3150 | declares locked_checks and the file has at least one data row. A |
| 3151 | header-only seed has nothing to check and is copied as before.""" |
| 3152 | try: |
| 3153 | schema = object_schemas.get_schema(collection, base_dir=base_dir) |
| 3154 | except Exception: # noqa: BLE001 -- no schema: nothing declared |
| 3155 | return False |
| 3156 | if not schema.get("locked_checks"): |
| 3157 | return False |
| 3158 | lines = [line for line in content.decode("utf-8", "replace").splitlines() if line.strip()] |
| 3159 | return len(lines) > 1 |
| 3160 | |
| 3161 | |
| 3162 | def _merge_seed_rows( |
| 3163 | collection: str, content: bytes, *, base_dir: Path, package_id: str |
| 3164 | ) -> tuple[int, list[dict[str, str]]]: |
| 3165 | """Add the seed rows whose id isn't already in ``collection``; leave every |
| 3166 | existing row untouched. Returns (how many were added, the rows the |
| 3167 | collection refused). Seed rows carry explicit ids and created_at, which |
| 3168 | ``create_collection_record`` honors (require_id + preserve_read_only), so |
| 3169 | a re-run adds nothing. |
| 3170 | |
| 3171 | One bad row never fails the install, but it is not swallowed either: a |
| 3172 | row the collection refuses -- a `unique` key live data already holds, a |
| 3173 | value its schema rejects -- comes back with the refusal, and the install |
| 3174 | result lists it. It used to be a bare ``except: continue``, so the result |
| 3175 | said "merged 1 new row(s)" and a default row the package shipped was |
| 3176 | simply not there, with nothing anywhere saying why.""" |
| 3177 | try: |
| 3178 | text = content.decode("utf-8") |
| 3179 | except UnicodeDecodeError: |
| 3180 | return 0, [{"id": "", "code": "invalid_encoding", |
| 3181 | "error": "seed file is not UTF-8; no row of it was merged"}] |
| 3182 | rows = list(csv.DictReader(io.StringIO(text), delimiter="\t")) |
| 3183 | if not rows: |
| 3184 | return 0, [] |
| 3185 | try: |
| 3186 | existing = { |
| 3187 | r.get("id") |
| 3188 | for r in object_records.read_collection_records(collection, base_dir=base_dir) |
| 3189 | } |
| 3190 | except (object_collections.CollectionNotFoundError, |
| 3191 | object_collections.InvalidCollectionNameError, OSError, ValueError): |
| 3192 | existing = set() |
| 3193 | added = 0 |
| 3194 | rejected: list[dict[str, str]] = [] |
| 3195 | for row in rows: |
| 3196 | record_id = (row.get("id") or "").strip() |
| 3197 | if not record_id or record_id in existing: |
| 3198 | continue |
| 3199 | try: |
| 3200 | object_records.create_collection_record( |
| 3201 | collection, {k: v for k, v in row.items() if v is not None}, |
| 3202 | base_dir=base_dir, actor=f"package:{package_id}", preserve_read_only=True, |
| 3203 | ) |
| 3204 | existing.add(record_id) |
| 3205 | added += 1 |
| 3206 | except Exception as exc: # noqa: BLE001 -- one bad seed row never fails the install |
| 3207 | rejected.append(_seed_refusal(record_id, exc)) |
| 3208 | return added, rejected |
| 3209 | |
| 3210 | |
| 3211 | _SEED_ROW_UNTRACKED = ("id", "created_at", "updated_at") |
| 3212 | |
| 3213 | |
| 3214 | def _seed_row_columns(rows: list[dict[str, str]]) -> list[str]: |
| 3215 | header = list(rows[0].keys()) if rows else [] |
| 3216 | return [c for c in header if c and c not in _SEED_ROW_UNTRACKED] |
| 3217 | |
| 3218 | |
| 3219 | def _reconcile_seed_rows( |
| 3220 | collection: str, |
| 3221 | content: bytes, |
| 3222 | *, |
| 3223 | base_dir: Path, |
| 3224 | package_id: str, |
| 3225 | previous: Mapping[str, Any], |
| 3226 | preexisting: set[str], |
| 3227 | ) -> tuple[list[str], list[dict[str, Any]], dict[str, Any]]: |
| 3228 | """Refresh seeded rows a new package version changed, never an edited one. |
| 3229 | |
| 3230 | Seed rows merge by id, so a row that is already there was never touched |
| 3231 | -- which meant a shipped view could not be improved on a box that had it |
| 3232 | (a new id on the same route collides). This is the same three-way idea |
| 3233 | the schemas and permission rules use, per COLUMN of each row: |
| 3234 | |
| 3235 | - the package's value for a column did not change since the baseline: |
| 3236 | nothing to do, and an operator's edit to it is theirs; |
| 3237 | - it changed, and the live value is still what the install wrote (its |
| 3238 | hash is the baseline's): the row is refreshed to the new value; |
| 3239 | - it changed, but the live value is not what the install wrote, or no |
| 3240 | baseline exists for it (the box was installed before rows were |
| 3241 | tracked) and the live value is not already the shipped one: LEFT ALONE |
| 3242 | and reported under `kept` with the columns, because an edit and an |
| 3243 | old default look the same without a baseline. |
| 3244 | |
| 3245 | Rows this install created (`id` not in `preexisting`) are only recorded. |
| 3246 | Returns (ids refreshed, kept rows, the new per-row baseline). Hashes, |
| 3247 | not values, are stored, and `id`, `created_at` and `updated_at` are not |
| 3248 | tracked. A refresh the collection refuses is reported as kept, with its |
| 3249 | code, and never fails the install. |
| 3250 | """ |
| 3251 | try: |
| 3252 | rows = list(csv.DictReader(io.StringIO(content.decode("utf-8")), delimiter="\t")) |
| 3253 | live_rows = { |
| 3254 | str(row.get("id") or ""): row |
| 3255 | for row in object_records.read_collection_records(collection, base_dir=base_dir) |
| 3256 | } |
| 3257 | except Exception: # noqa: BLE001 -- the baseline is a convenience, never a gate |
| 3258 | return [], [], dict(previous) |
| 3259 | columns = _seed_row_columns(rows) |
| 3260 | sha = object_package_baselines.sha256_text |
| 3261 | replaced: list[str] = [] |
| 3262 | kept: list[dict[str, Any]] = [] |
| 3263 | baseline: dict[str, Any] = {} |
| 3264 | for seed in rows: |
| 3265 | record_id = (seed.get("id") or "").strip() |
| 3266 | live = live_rows.get(record_id) |
| 3267 | if not record_id or live is None: |
| 3268 | continue |
| 3269 | old = previous.get(record_id) or {} |
| 3270 | old_shipped = old.get("shipped") or {} |
| 3271 | old_live = old.get("live") or {} |
| 3272 | shipped = dict(old_shipped) |
| 3273 | seen = dict(old_live) |
| 3274 | if record_id not in preexisting: |
| 3275 | shipped = {c: sha(seed.get(c) or "") for c in columns} |
| 3276 | seen = {c: sha(live.get(c) or "") for c in columns} |
| 3277 | baseline[record_id] = {"shipped": shipped, "live": seen} |
| 3278 | continue |
| 3279 | changes: dict[str, str] = {} |
| 3280 | held: list[str] = [] |
| 3281 | reason = "edited" |
| 3282 | for column in columns: |
| 3283 | want = seed.get(column) or "" |
| 3284 | have = live.get(column) or "" |
| 3285 | if column in old_shipped and sha(want) == old_shipped[column]: |
| 3286 | continue # the package did not change it |
| 3287 | if have == want: |
| 3288 | shipped[column], seen[column] = sha(want), sha(have) |
| 3289 | elif column in old_live and sha(have) == old_live[column]: |
| 3290 | changes[column] = want # still what the install wrote |
| 3291 | else: |
| 3292 | held.append(column) |
| 3293 | if column not in old_live: |
| 3294 | reason = "no baseline" |
| 3295 | if changes: |
| 3296 | try: |
| 3297 | stored = object_records.update_collection_record( |
| 3298 | collection, record_id, changes, base_dir=base_dir, |
| 3299 | actor=f"package:{package_id}", preserve_read_only=True) |
| 3300 | except Exception as exc: # noqa: BLE001 -- one row never fails the install |
| 3301 | refusal = _seed_refusal(record_id, exc) |
| 3302 | kept.append({"id": record_id, "reason": f"refused: {refusal['code']}", |
| 3303 | "columns": sorted(changes)}) |
| 3304 | else: |
| 3305 | replaced.append(record_id) |
| 3306 | for column, value in changes.items(): |
| 3307 | shipped[column] = sha(value) |
| 3308 | seen[column] = sha(stored.get(column) or "") |
| 3309 | if held: |
| 3310 | kept.append({"id": record_id, "reason": reason, "columns": held}) |
| 3311 | baseline[record_id] = {"shipped": shipped, "live": seen} |
| 3312 | return replaced, kept, baseline |
| 3313 | |
| 3314 | |
| 3315 | def _write_file_atomic_bytes(path: Path, content: bytes) -> None: |
| 3316 | path.parent.mkdir(parents=True, exist_ok=True) |
| 3317 | tmp_name = "" |
| 3318 | try: |
| 3319 | with tempfile.NamedTemporaryFile( |
| 3320 | "wb", |
| 3321 | dir=path.parent, |
| 3322 | prefix=f".{path.name}.", |
| 3323 | suffix=".tmp", |
| 3324 | delete=False, |
| 3325 | ) as tmp: |
| 3326 | tmp_name = tmp.name |
| 3327 | tmp.write(content) |
| 3328 | tmp.flush() |
| 3329 | os.fsync(tmp.fileno()) |
| 3330 | os.replace(tmp_name, path) |
| 3331 | finally: |
| 3332 | if tmp_name: |
| 3333 | try: |
| 3334 | Path(tmp_name).unlink() |
| 3335 | except FileNotFoundError: |
| 3336 | pass |
| 3337 | |
| 3338 | |
| 3339 | def _attribute_seed_records(collection: str, *, package_id: str, base_dir: Path) -> None: |
| 3340 | """Emit an attributed "create" change for every row a seed file just wrote. |
| 3341 | |
| 3342 | Seed writes land the whole records.tsv in one atomic byte-for-byte |
| 3343 | copy (see the seed_writes loop above), bypassing |
| 3344 | object_records.create_collection_record entirely -- so, unlike a |
| 3345 | normal record write, nothing emits a change automatically. This is |
| 3346 | the seed-install side of universal attribution: read the file back |
| 3347 | (install-once, so every row it now holds is a fresh create) and log |
| 3348 | one change per row, attributed to the installing package rather than |
| 3349 | left unattributed. |
| 3350 | """ |
| 3351 | try: |
| 3352 | rows = object_records.read_collection_records(collection, base_dir=base_dir) |
| 3353 | except (object_collections.CollectionNotFoundError, object_collections.InvalidCollectionNameError): |
| 3354 | return |
| 3355 | for row in rows: |
| 3356 | object_record_changes.append_record_change( |
| 3357 | collection=collection, |
| 3358 | record_id=row["id"], |
| 3359 | action="create", |
| 3360 | before=None, |
| 3361 | after=row, |
| 3362 | actor=f"package-install:{package_id}", |
| 3363 | base_dir=base_dir, |
| 3364 | ) |
| 3365 | |
| 3366 | |
| 3367 | def _relative_display_path(path: Path, root: Path) -> str: |
| 3368 | try: |
| 3369 | return path.resolve(strict=False).relative_to(root.resolve(strict=False)).as_posix() |
| 3370 | except ValueError: |
| 3371 | return path.name |
| 3372 | |
| 3373 | |
| 3374 | def _safe_relative_path(value: str, *, package_id: str, section: str) -> str: |
| 3375 | if "\x00" in value: |
| 3376 | raise InvalidPackageManifestError(f"Package {section} path contains a null byte: {package_id}") |
| 3377 | path = Path(value) |
| 3378 | if path.is_absolute() or not path.parts: |
| 3379 | raise InvalidPackageManifestError(f"Package {section} path must be relative: {package_id}") |
| 3380 | if any(part in {"", ".", ".."} for part in path.parts): |
| 3381 | raise InvalidPackageManifestError(f"Package {section} path is not safe: {package_id}") |
| 3382 | return path.as_posix() |
| 3383 | |
| 3384 | |
| 3385 | def _required_text(payload: Mapping[str, Any], key: str, *, package_id: str) -> str: |
| 3386 | value = payload.get(key) |
| 3387 | text = _optional_text(value) |
| 3388 | if text is None: |
| 3389 | raise InvalidPackageManifestError(f"Package manifest requires '{key}': {package_id}") |
| 3390 | return text |
| 3391 | |
| 3392 | |
| 3393 | def _optional_text(value: Any) -> str | None: |
| 3394 | if value is None: |
| 3395 | return None |
| 3396 | if not isinstance(value, str): |
| 3397 | return None |
| 3398 | text = value.strip() |
| 3399 | return text or None |
| 3400 | |
| 3401 | |
| 3402 | def _mapping_field(value: Any, *, package_id: str) -> dict[str, Any]: |
| 3403 | if value is None: |
| 3404 | return {} |
| 3405 | if not isinstance(value, Mapping): |
| 3406 | raise InvalidPackageManifestError(f"Package compatibility must be an object: {package_id}") |
| 3407 | return dict(value) |
| 3408 | |
| 3409 | |
| 3410 | def _list_field(value: Any, *, package_id: str, section: str) -> list[Any]: |
| 3411 | if value is None: |
| 3412 | return [] |
| 3413 | if not isinstance(value, list): |
| 3414 | raise InvalidPackageManifestError(f"Package {section} must be a list: {package_id}") |
| 3415 | return value |
| 3416 | |
| 3417 | |
| 3418 | def _entry_mapping(value: Any, *, package_id: str, section: str) -> Mapping[str, Any]: |
| 3419 | if not isinstance(value, Mapping): |
| 3420 | raise InvalidPackageManifestError(f"Package {section} entries must be objects: {package_id}") |
| 3421 | return value |