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_schemas.py · 99.2 KB · 2185 lines
| 1 | """Schema metadata for DBBASIC collections. |
| 2 | |
| 3 | Schemas describe the fields, validation hints, and relations Scroll can use to |
| 4 | render forms, tables, and diagrams. They are metadata, not the default storage |
| 5 | engine; objects can still read/write TSV files, APIs, SQL, or other backends. |
| 6 | """ |
| 7 | |
| 8 | from __future__ import annotations |
| 9 | |
| 10 | import difflib |
| 11 | import json |
| 12 | import math |
| 13 | import os |
| 14 | import re |
| 15 | import tempfile |
| 16 | import threading |
| 17 | import time |
| 18 | from decimal import Decimal, InvalidOperation |
| 19 | from pathlib import Path |
| 20 | from typing import Any, Iterable, Mapping |
| 21 | |
| 22 | import object_collections |
| 23 | import object_computed |
| 24 | import object_permissions |
| 25 | from object_versions import DEFAULT_DATA_DIR |
| 26 | |
| 27 | SCHEMAS_DIR = "schemas" |
| 28 | _FIELD_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$") |
| 29 | |
| 30 | # Storage engine opt-in (docs/append-only-storage-design.md). A schema's |
| 31 | # top-level "storage" key selects how object_records.py physically writes |
| 32 | # a collection's records.tsv: "classic" (default, omitted key) rewrites the |
| 33 | # whole file per write, unchanged from the original behavior; "append" |
| 34 | # opts a collection into append-only writes with last-wins-by-id reads. |
| 35 | # Only present in the normalized schema when the source payload set it, so |
| 36 | # a schema that never mentions storage stays byte-identical to before this |
| 37 | # feature existed (see the metadata-key handling in _normalize_schema). |
| 38 | STORAGE_CLASSIC = "classic" |
| 39 | STORAGE_APPEND = "append" |
| 40 | VALID_STORAGE_MODES = frozenset({STORAGE_CLASSIC, STORAGE_APPEND}) |
| 41 | |
| 42 | # Module-level cache for parsed+normalized manual schemas. |
| 43 | # |
| 44 | # key (base_dir exactly as the caller spelled it, schema name) |
| 45 | # value (schema file path, stat signature, normalized schema) |
| 46 | # |
| 47 | # A HIT IS ONE DICT LOOKUP AND ONE lstat(). It used to be four |
| 48 | # Path.resolve() calls and three stats (71 us), because the path-safety |
| 49 | # check ran before the cache was consulted, on a name the cache had already |
| 50 | # validated; get_schema is called 50 times per list and 120-340 times per |
| 51 | # write, so that check was a third to a half of those requests. The check is |
| 52 | # not skipped, it is made unnecessary: an entry is only stored for a schema |
| 53 | # file that passed it AND is a regular file, and the signature is taken with |
| 54 | # lstat, so a schema file later replaced by a symlink (the one way the path |
| 55 | # could start pointing outside the schemas directory) no longer matches and |
| 56 | # goes back through _schema_path. |
| 57 | # |
| 58 | # INVALIDATION IS BY WHAT IS ON DISK. The server may be several workers, |
| 59 | # and the daemon, the package installer, the schema API in another worker |
| 60 | # and an operator's editor all write these files; nothing tells this |
| 61 | # process. Every call stats the file and compares |
| 62 | # (mtime_ns, ctime_ns, size, inode, device): |
| 63 | # - an in-place edit moves mtime (and ctime, which unlike mtime cannot be |
| 64 | # set back by a restore or `touch -r`); |
| 65 | # - an atomic replace (replace_schema, the installer) is a new inode even |
| 66 | # when it lands in the same timestamp tick with the same size, which |
| 67 | # the (mtime_ns, size) signature this replaces could not tell apart; |
| 68 | # - device and inode also cover a relative base_dir after a chdir. |
| 69 | # The stat is taken BEFORE the file is read, so a write landing mid-read |
| 70 | # leaves a signature older than the content and the next call re-reads. A |
| 71 | # file changed within _SCHEMA_CACHE_RACY_NS of being read is not cached at |
| 72 | # all: a second in-place write inside the filesystem's timestamp |
| 73 | # granularity would leave the same stat behind (the margin and reasoning of |
| 74 | # object_identity's session cache). Missing files, symlinks and files that |
| 75 | # fail to parse are never cached: a schema created or fixed later is picked |
| 76 | # up on the very next call, and an error is raised every time. |
| 77 | # |
| 78 | # Every caller of get_schema/_load_manual_schema was audited (object_records, |
| 79 | # object_field_permissions, object_packages, object_server, object_mcp |
| 80 | # argument-building, and the test suite) and none of them mutate the |
| 81 | # returned dict -- they only read from it (json.dumps for hashing, `.get` |
| 82 | # for field lookups, dict/set comprehensions that copy). So cache hits |
| 83 | # return the cached dict directly rather than paying for a defensive copy; |
| 84 | # if a future caller starts mutating it, that would need revisiting. |
| 85 | _SCHEMA_CACHE: dict[tuple[str, str], tuple[str, tuple[int, int, int, int, int], dict[str, Any]]] = {} |
| 86 | _SCHEMA_CACHE_LOCK = threading.Lock() |
| 87 | _SCHEMA_CACHE_MAX_ENTRIES = 4096 |
| 88 | _SCHEMA_CACHE_RACY_NS = 50_000_000 |
| 89 | |
| 90 | |
| 91 | class InvalidSchemaNameError(ValueError): |
| 92 | """Raised when a schema name is not safe for routes or storage.""" |
| 93 | |
| 94 | |
| 95 | class SchemaNotFoundError(LookupError): |
| 96 | """Raised when a schema cannot be found or derived.""" |
| 97 | |
| 98 | |
| 99 | def validate_schema_name(schema: str) -> bool: |
| 100 | """Return True when a schema/collection name is route-safe.""" |
| 101 | return object_collections.validate_collection_name(schema) |
| 102 | |
| 103 | |
| 104 | def list_schemas( |
| 105 | *, |
| 106 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 107 | roots: Iterable[Path] | None = None, |
| 108 | ) -> list[dict[str, Any]]: |
| 109 | """Return summaries for manual schemas and derived collection schemas.""" |
| 110 | base = Path(base_dir) |
| 111 | collection_names = object_collections.collection_names(base_dir=base, roots=roots) |
| 112 | manual_names = set(_iter_manual_schema_names(base)) |
| 113 | schemas = [ |
| 114 | _schema_summary(name, _load_manual_schema(name, base_dir=base), source="manual") |
| 115 | if name in manual_names |
| 116 | else _schema_summary(name, _derived_schema(name), source="derived") |
| 117 | for name in sorted(collection_names | manual_names) |
| 118 | ] |
| 119 | return schemas |
| 120 | |
| 121 | |
| 122 | def list_append_storage_collections( |
| 123 | *, |
| 124 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 125 | ) -> list[str]: |
| 126 | """Return the names of collections whose manual schema currently |
| 127 | declares ``"storage": "append"``, sorted. |
| 128 | |
| 129 | Only a manual schema file can set `storage` (a derived schema -- a |
| 130 | collection with no schema file -- always defaults to classic; see |
| 131 | _collection_storage_mode in object_records.py), so this only needs to |
| 132 | glob the schemas directory and load each manual schema through |
| 133 | _load_manual_schema's stat-keyed _SCHEMA_CACHE, rather |
| 134 | than walking every collection's records directory. Repeated calls |
| 135 | (e.g. object_records.list_append_collection_stats on every /admin/ |
| 136 | storage poll, or the daemon's compaction pass on every tick) are cheap |
| 137 | after the first, same as every other schema read in this codebase. |
| 138 | """ |
| 139 | base = Path(base_dir) |
| 140 | names = [] |
| 141 | for name in _iter_manual_schema_names(base): |
| 142 | schema = _load_manual_schema(name, base_dir=base) |
| 143 | if schema is not None and schema.get("storage") == STORAGE_APPEND: |
| 144 | names.append(name) |
| 145 | return sorted(names) |
| 146 | |
| 147 | |
| 148 | def get_schema( |
| 149 | schema: str, |
| 150 | *, |
| 151 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 152 | roots: Iterable[Path] | None = None, |
| 153 | ) -> dict[str, Any]: |
| 154 | """Return one manual schema, or an empty derived schema for a collection.""" |
| 155 | cached = _cached_manual_schema(schema, base_dir) |
| 156 | if cached is not None: |
| 157 | return cached |
| 158 | |
| 159 | if not validate_schema_name(schema): |
| 160 | raise InvalidSchemaNameError(f"Invalid schema name: {schema}") |
| 161 | |
| 162 | base = Path(base_dir) |
| 163 | manual_schema = _load_manual_schema(schema, base_dir=base) |
| 164 | if manual_schema is not None: |
| 165 | return manual_schema |
| 166 | |
| 167 | # Not list_collections(): that summarises every object (state, files, |
| 168 | # logs) to answer a yes/no question about one name. |
| 169 | if object_collections.is_known_collection(schema, base_dir=base, roots=roots): |
| 170 | return _derived_schema(schema) |
| 171 | |
| 172 | raise SchemaNotFoundError(f"Schema not found: {schema}") |
| 173 | |
| 174 | |
| 175 | def replace_schema( |
| 176 | schema: str, |
| 177 | payload: Mapping[str, Any], |
| 178 | *, |
| 179 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 180 | ) -> dict[str, Any]: |
| 181 | """Validate and atomically replace a manual schema file.""" |
| 182 | if not validate_schema_name(schema): |
| 183 | raise InvalidSchemaNameError(f"Invalid schema name: {schema}") |
| 184 | |
| 185 | base = Path(base_dir) |
| 186 | normalized = normalize_schema(schema, payload, source="manual") |
| 187 | root = _schema_root(base) |
| 188 | root.mkdir(parents=True, exist_ok=True) |
| 189 | path = _schema_path(schema, base) |
| 190 | |
| 191 | tmp_name = "" |
| 192 | try: |
| 193 | with tempfile.NamedTemporaryFile( |
| 194 | "w", |
| 195 | encoding="utf-8", |
| 196 | dir=root, |
| 197 | prefix=f".{schema}.", |
| 198 | suffix=".tmp", |
| 199 | delete=False, |
| 200 | ) as tmp: |
| 201 | tmp_name = tmp.name |
| 202 | json.dump(normalized, tmp, indent=2, sort_keys=True) |
| 203 | tmp.write("\n") |
| 204 | tmp.flush() |
| 205 | os.fsync(tmp.fileno()) |
| 206 | os.replace(tmp_name, path) |
| 207 | finally: |
| 208 | if tmp_name: |
| 209 | try: |
| 210 | Path(tmp_name).unlink() |
| 211 | except FileNotFoundError: |
| 212 | pass |
| 213 | |
| 214 | # Hygiene only: the replace above is a new inode, which no cached |
| 215 | # signature matches, in this process or any other. |
| 216 | for spelling in {_base_dir_key(base_dir), _base_dir_key(base)}: |
| 217 | _SCHEMA_CACHE.pop((spelling, schema), None) |
| 218 | |
| 219 | return normalized |
| 220 | |
| 221 | |
| 222 | def merge_schema_fields( |
| 223 | base: Mapping[str, Any], |
| 224 | mine: Mapping[str, Any], |
| 225 | theirs: Mapping[str, Any], |
| 226 | ) -> tuple[dict[str, Any], list[str]]: |
| 227 | """Three-way merge a schema's field list; return (merged_schema, collisions). |
| 228 | |
| 229 | Schemas are additive (docs/upgrade-and-customization.md, Rule 3: Data |
| 230 | Fields That Survive Schema Upgrades): an operator-added field and a |
| 231 | package-added field should both survive an upgrade rather than forcing a |
| 232 | conflict just because *something* changed on both sides. `base` is the |
| 233 | schema as last recorded in the package baseline, `mine` is the live |
| 234 | (possibly customized) schema, and `theirs` is the newly shipped schema. |
| 235 | |
| 236 | The result is `dict(theirs)` with `"fields"` replaced by the merged list. |
| 237 | Field order is theirs' order first, then any mine-only fields appended in |
| 238 | mine's order. `collisions` names fields that changed incompatibly on both |
| 239 | sides (same field, no shared ancestor value, and mine != theirs); those |
| 240 | fields keep the operator's version in `merged_schema`, pending a human |
| 241 | decision -- callers should treat any non-empty `collisions` as "do not |
| 242 | apply, park a conflict instead." |
| 243 | |
| 244 | Pure function: no I/O, no validation of the inputs or output. |
| 245 | """ |
| 246 | base_by = {field["name"]: field for field in (base or {}).get("fields", [])} |
| 247 | mine_by = {field["name"]: field for field in (mine or {}).get("fields", [])} |
| 248 | theirs_by = {field["name"]: field for field in (theirs or {}).get("fields", [])} |
| 249 | |
| 250 | theirs_names = [field["name"] for field in (theirs or {}).get("fields", [])] |
| 251 | mine_names = [field["name"] for field in (mine or {}).get("fields", [])] |
| 252 | mine_only_names = [name for name in mine_names if name not in theirs_by] |
| 253 | ordered_names = theirs_names + mine_only_names |
| 254 | |
| 255 | collisions: list[str] = [] |
| 256 | merged_fields: list[dict[str, Any]] = [] |
| 257 | |
| 258 | for name in ordered_names: |
| 259 | b = base_by.get(name) |
| 260 | m = mine_by.get(name) |
| 261 | t = theirs_by.get(name) |
| 262 | |
| 263 | if m is not None and t is not None: |
| 264 | if m == t: |
| 265 | merged_fields.append(m) |
| 266 | elif b is not None and m == b: |
| 267 | # Operator didn't touch it; package changed it. |
| 268 | merged_fields.append(t) |
| 269 | elif b is not None and t == b: |
| 270 | # Package didn't touch it; operator changed it. |
| 271 | merged_fields.append(m) |
| 272 | else: |
| 273 | # Both changed it (or there's no shared base to compare to): |
| 274 | # a genuine collision. Keep the operator's version pending |
| 275 | # a resolution, but flag it. |
| 276 | collisions.append(name) |
| 277 | merged_fields.append(m) |
| 278 | elif m is not None: |
| 279 | # Operator has it, package doesn't (never shipped it, or |
| 280 | # removed it). Additive-safe: never silently drop a field the |
| 281 | # operator kept. |
| 282 | merged_fields.append(m) |
| 283 | else: |
| 284 | # Package has it, operator doesn't. |
| 285 | if b is None: |
| 286 | # Newly added by the package. |
| 287 | merged_fields.append(t) |
| 288 | elif t == b: |
| 289 | # Operator removed it, package left it unchanged: respect |
| 290 | # the removal. |
| 291 | continue |
| 292 | else: |
| 293 | # Operator removed it, but the package changed it: |
| 294 | # collision -- surface it rather than silently resurrect |
| 295 | # a field the operator deliberately dropped. |
| 296 | collisions.append(name) |
| 297 | merged_fields.append(t) |
| 298 | |
| 299 | merged = dict(theirs) |
| 300 | merged["fields"] = merged_fields |
| 301 | return merged, collisions |
| 302 | |
| 303 | |
| 304 | def normalize_schema( |
| 305 | schema: str, |
| 306 | payload: Mapping[str, Any], |
| 307 | *, |
| 308 | source: str = "manual", |
| 309 | ) -> dict[str, Any]: |
| 310 | """Validate schema metadata and return canonical JSON-compatible data.""" |
| 311 | if not validate_schema_name(schema): |
| 312 | raise InvalidSchemaNameError(f"Invalid schema name: {schema}") |
| 313 | return _normalize_schema(schema, payload, source=source) |
| 314 | |
| 315 | |
| 316 | def _iter_manual_schema_names(base_dir: Path) -> list[str]: |
| 317 | root = _schema_root(base_dir) |
| 318 | if not root.exists() or not root.is_dir(): |
| 319 | return [] |
| 320 | |
| 321 | names = [] |
| 322 | for path in sorted(root.glob("*.json"), key=lambda item: item.name): |
| 323 | name = path.stem |
| 324 | if validate_schema_name(name): |
| 325 | names.append(name) |
| 326 | return names |
| 327 | |
| 328 | |
| 329 | def _base_dir_key(base_dir: Path | str) -> str | None: |
| 330 | try: |
| 331 | return os.fspath(base_dir) |
| 332 | except TypeError: |
| 333 | return None |
| 334 | |
| 335 | |
| 336 | def _schema_file_signature(path: str) -> tuple[int, int, int, int, int] | None: |
| 337 | """(mtime_ns, ctime_ns, size, inode, device) of a regular file, without |
| 338 | following a symlink; None for a symlink, a directory or nothing.""" |
| 339 | try: |
| 340 | info = os.lstat(path) |
| 341 | except OSError: |
| 342 | return None |
| 343 | if (info.st_mode & 0o170000) != 0o100000: |
| 344 | return None |
| 345 | return (info.st_mtime_ns, info.st_ctime_ns, info.st_size, info.st_ino, info.st_dev) |
| 346 | |
| 347 | |
| 348 | def _cached_manual_schema(schema: str, base_dir: Path | str) -> dict[str, Any] | None: |
| 349 | """The cached schema when its file still has the stat it was read |
| 350 | under, else None (which says nothing about whether the schema exists).""" |
| 351 | try: |
| 352 | entry = _SCHEMA_CACHE.get((_base_dir_key(base_dir), schema)) |
| 353 | except TypeError: # an unhashable "name": let validation refuse it |
| 354 | return None |
| 355 | if entry is None or _schema_file_signature(entry[0]) != entry[1]: |
| 356 | return None |
| 357 | return entry[2] |
| 358 | |
| 359 | |
| 360 | def _load_manual_schema(schema: str, *, base_dir: Path) -> dict[str, Any] | None: |
| 361 | cached = _cached_manual_schema(schema, base_dir) |
| 362 | if cached is not None: |
| 363 | return cached |
| 364 | |
| 365 | path = _schema_path(schema, base_dir) |
| 366 | cache_key = (_base_dir_key(base_dir), schema) |
| 367 | # A miss drops whatever was kept, before anything below can raise: an |
| 368 | # entry only ever comes back from a successful, settled read. |
| 369 | _SCHEMA_CACHE.pop(cache_key, None) |
| 370 | # Signature first, read second (see the note on _SCHEMA_CACHE). |
| 371 | signature = _schema_file_signature(str(path)) |
| 372 | read_at = time.time_ns() |
| 373 | if not path.exists(): |
| 374 | return None |
| 375 | if not path.is_file(): |
| 376 | raise ValueError(f"Schema path is not a file: {schema}") |
| 377 | |
| 378 | try: |
| 379 | payload = json.loads(path.read_text()) |
| 380 | except json.JSONDecodeError as exc: |
| 381 | raise ValueError(f"Schema file contains invalid JSON: {schema}") from exc |
| 382 | |
| 383 | normalized = _normalize_schema(schema, payload, source="manual") |
| 384 | if signature is not None and read_at - max(signature[0], signature[1]) >= _SCHEMA_CACHE_RACY_NS: |
| 385 | with _SCHEMA_CACHE_LOCK: |
| 386 | if len(_SCHEMA_CACHE) >= _SCHEMA_CACHE_MAX_ENTRIES: |
| 387 | _SCHEMA_CACHE.clear() |
| 388 | _SCHEMA_CACHE[cache_key] = (str(path), signature, normalized) |
| 389 | return normalized |
| 390 | |
| 391 | |
| 392 | def _derived_schema(schema: str) -> dict[str, Any]: |
| 393 | return { |
| 394 | "name": schema, |
| 395 | "title": _title_from_name(schema), |
| 396 | "source": "derived", |
| 397 | "version": 1, |
| 398 | "fields": [], |
| 399 | "field_count": 0, |
| 400 | } |
| 401 | |
| 402 | |
| 403 | def _schema_summary( |
| 404 | schema: str, |
| 405 | payload: dict[str, Any] | None, |
| 406 | *, |
| 407 | source: str, |
| 408 | ) -> dict[str, Any]: |
| 409 | active = payload or _derived_schema(schema) |
| 410 | return { |
| 411 | "name": active["name"], |
| 412 | "title": active["title"], |
| 413 | "source": source, |
| 414 | "version": active["version"], |
| 415 | "field_count": active["field_count"], |
| 416 | } |
| 417 | |
| 418 | |
| 419 | def _normalize_schema( |
| 420 | schema: str, |
| 421 | payload: Any, |
| 422 | *, |
| 423 | source: str, |
| 424 | ) -> dict[str, Any]: |
| 425 | if not isinstance(payload, Mapping): |
| 426 | raise ValueError(f"Schema file must contain an object: {schema}") |
| 427 | |
| 428 | name = _optional_string(payload.get("name")) or _optional_string(payload.get("collection")) or schema |
| 429 | if name != schema: |
| 430 | raise ValueError(f"Schema file name does not match schema collection: {schema}") |
| 431 | if not validate_schema_name(name): |
| 432 | raise InvalidSchemaNameError(f"Invalid schema name: {name}") |
| 433 | |
| 434 | fields_payload = payload.get("fields", []) |
| 435 | if not isinstance(fields_payload, list): |
| 436 | raise ValueError(f"Schema fields must be a list: {schema}") |
| 437 | |
| 438 | fields = [_normalize_field(field, schema=schema) for field in fields_payload] |
| 439 | _check_required_when_fields(fields, schema=schema) |
| 440 | normalized = { |
| 441 | "name": name, |
| 442 | "title": _optional_string(payload.get("title")) or _title_from_name(name), |
| 443 | "source": source, |
| 444 | "version": _optional_int(payload.get("version")) or 1, |
| 445 | "fields": fields, |
| 446 | "field_count": len(fields), |
| 447 | } |
| 448 | if "storage" in payload: |
| 449 | storage = payload.get("storage") |
| 450 | if storage not in VALID_STORAGE_MODES: |
| 451 | raise ValueError( |
| 452 | f"Schema storage must be one of {sorted(VALID_STORAGE_MODES)}: {schema}" |
| 453 | ) |
| 454 | normalized["storage"] = storage |
| 455 | if "unique" in payload: |
| 456 | unique = _normalize_unique(payload["unique"], schema=schema, fields=fields) |
| 457 | if unique: |
| 458 | normalized["unique"] = unique |
| 459 | if "locked_when" in payload: |
| 460 | locked_when = _normalize_locked_when( |
| 461 | payload["locked_when"], schema=schema, declared=[field["name"] for field in fields] |
| 462 | ) |
| 463 | if locked_when: |
| 464 | normalized["locked_when"] = locked_when |
| 465 | if "locked_checks" in payload: |
| 466 | locked_checks = _normalize_locked_checks(payload["locked_checks"], schema=schema) |
| 467 | if locked_checks: |
| 468 | normalized["locked_checks"] = locked_checks |
| 469 | if "subject_exempt" in payload: |
| 470 | # Why this collection cannot be searched for a person (a privacy |
| 471 | # export returns the sentence). Must say something: an empty reason |
| 472 | # is an omission dressed as a declaration. |
| 473 | reason = payload["subject_exempt"] |
| 474 | if not isinstance(reason, str) or not reason.strip(): |
| 475 | raise ValueError( |
| 476 | f"Schema subject_exempt must be a sentence saying why: {schema}") |
| 477 | normalized["subject_exempt"] = reason.strip() |
| 478 | metadata_keys = ( |
| 479 | "description", |
| 480 | "permissions", |
| 481 | "ui", |
| 482 | "layout", |
| 483 | "views", |
| 484 | "forms", |
| 485 | "search", |
| 486 | "table", |
| 487 | "diagram", |
| 488 | "validation", |
| 489 | # 10-flow-spec.md's root-level `flow` key (which field on this |
| 490 | # collection owns a `transitions` map, plus who/what annotations on |
| 491 | # top of it) -- no shipped schema declares this yet, but it must |
| 492 | # survive normalization for 60-list-modes-spec.md's board mode to |
| 493 | # honor its own documented default-group-field chain the moment one |
| 494 | # does. Passed through unchanged, same as every other metadata key |
| 495 | # here: this whitelists the key, it does not interpret it. |
| 496 | "flow", |
| 497 | # 64-feed-spec.md's root-level `blocks` key (a collection opts into a |
| 498 | # block -- e.g. `blocks.feed` names the owner/visibility/time fields |
| 499 | # that make it a feed source). Must survive normalization or install |
| 500 | # would strip it from the stored schema and the feed would find zero |
| 501 | # sources. Whitelisted, not interpreted -- same posture as `flow`. |
| 502 | "blocks", |
| 503 | # Root-level `capabilities` key: generic per-collection behaviors a |
| 504 | # collection opts into, wired by the platform rather than hand-built |
| 505 | # per app (e.g. `capabilities.comments: true` -> the detail page mounts |
| 506 | # window.dbbasicThread for that record; see app-thread + view_render). |
| 507 | # Must survive normalization or the flag is stripped on install and the |
| 508 | # capability never turns on. Whitelisted, not interpreted -- same |
| 509 | # posture as `flow`/`blocks`. |
| 510 | "capabilities", |
| 511 | # Root-level `hooks` key: per-collection pre-write hook declaration |
| 512 | # (`hooks.before_write` names an object the generic HTTP write path |
| 513 | # executes synchronously -- reject/transform -- after permission |
| 514 | # checks, before persist; see object_server._apply_before_write_hook |
| 515 | # and plan/pre-write-hook-spec.md). Server-side only: deliberately NOT |
| 516 | # exposed by /api/schema. Whitelisted, not interpreted. |
| 517 | "hooks", |
| 518 | ) |
| 519 | for key in metadata_keys: |
| 520 | if key in payload: |
| 521 | normalized[key] = _json_compatible(payload[key], field_name=f"{schema}.{key}") |
| 522 | return normalized |
| 523 | |
| 524 | |
| 525 | # --- what a package may DECLARE (DRON 0.1, dron/dron-collection.schema.json) --- |
| 526 | # |
| 527 | # _normalize_schema keeps the keys it knows and drops the rest without a |
| 528 | # word. It has to stay that forgiving for what is already on a box (a schema |
| 529 | # an operator saved, the normalized copy every install writes, which adds |
| 530 | # `source` and `field_count`), because a box must not stop reading its own |
| 531 | # data over a key. A package schema is different: it is a declaration about |
| 532 | # to be installed, and a dropped key there is a rule the author believes in |
| 533 | # and the server never applies ("maxlength" for validation.max_length, a |
| 534 | # misspelt "requied"). check_declaration refuses it, naming the key, before |
| 535 | # anything is written; object_packages calls it on every package schema. |
| 536 | |
| 537 | DECLARED_ROOT_KEYS = frozenset({ |
| 538 | "$schema", "name", "collection", "title", "description", "version", "storage", |
| 539 | "fields", "unique", "locked_when", "locked_checks", "subject_exempt", "permissions", |
| 540 | "ui", "layout", "views", "forms", "search", "table", "diagram", "validation", |
| 541 | "flow", "blocks", "capabilities", "hooks", |
| 542 | }) |
| 543 | DECLARED_FIELD_KEYS = frozenset({ |
| 544 | "name", "type", "required", "label", "description", "relation", "validation", |
| 545 | "default", "enum", "read_only", "ui", "layout", "permissions", "placeholder", "help", |
| 546 | "store", "visible_when", "formula", "rollup", "transitions", "subject", |
| 547 | }) |
| 548 | # The field types and their aliases; the engine lower-cases whatever it is |
| 549 | # given and treats anything else as text. DRON spells each one way. |
| 550 | DECLARED_FIELD_TYPES = frozenset({ |
| 551 | "text", "textarea", "integer", "int", "number", "float", "currency", "boolean", |
| 552 | "bool", "date", "datetime", "timestamp", "enum", "computed", "relation", |
| 553 | }) |
| 554 | DECLARED_VALIDATION_KEYS = frozenset({ |
| 555 | "min", "max", "exclusive_min", "exclusive_max", "min_length", "max_length", |
| 556 | "pattern", "required_when", |
| 557 | }) |
| 558 | # Spellings the engine still honours in a stored schema but DRON does not |
| 559 | # define, with the DRON spelling to use instead. Refused in a declaration |
| 560 | # like any unknown key, with the right spelling in the message. |
| 561 | FIELD_SYNONYMS = { |
| 562 | "readonly": "read_only", |
| 563 | "readOnly": "read_only", |
| 564 | "computed": '"type": "computed"', |
| 565 | } |
| 566 | VALIDATION_SYNONYMS = { |
| 567 | "regex": "pattern", |
| 568 | "required": '"required": true on the field', |
| 569 | "not_null": '"required": true on the field', |
| 570 | "choices": '"type": "enum" with an "enum" list on the field', |
| 571 | "in": '"type": "enum" with an "enum" list on the field', |
| 572 | } |
| 573 | # Root-level objects whose keys DRON closes, and the closed objects inside them. |
| 574 | _DECLARED_ROOT_OBJECTS = { |
| 575 | "hooks": frozenset({"before_write"}), |
| 576 | "search": frozenset({"fields", "result_fields"}), |
| 577 | "capabilities": frozenset({"attachments", "comments", "shareable"}), |
| 578 | "blocks": frozenset({"feed"}), |
| 579 | "views": frozenset({ |
| 580 | "list_mode", "list_fields", "detail_fields", "filter_fields", "board", "tree", |
| 581 | "calendar", "related", |
| 582 | }), |
| 583 | } |
| 584 | _DECLARED_NESTED_OBJECTS = { |
| 585 | ("blocks", "feed"): frozenset({ |
| 586 | "owner_field", "time_field", "visibility_field", "visibility_true_value", |
| 587 | "summary_fields", "link_field", |
| 588 | }), |
| 589 | ("views", "board"): frozenset({"group_field"}), |
| 590 | ("views", "tree"): frozenset({"parent_field"}), |
| 591 | ("views", "calendar"): frozenset({"date_field"}), |
| 592 | } |
| 593 | _DECLARED_VIEWS_RELATED_KEYS = frozenset({"collection", "fk_field"}) |
| 594 | # What `views.list_mode` may be, in the order the DRON schema lists them. |
| 595 | VIEW_LIST_MODES = ("table", "board", "tree", "calendar", "cards", "feed") |
| 596 | _DECLARED_FIELD_OBJECTS = { |
| 597 | "relation": frozenset({"collection", "display_field", "requires"}), |
| 598 | "rollup": frozenset({"collection", "fk_field", "op", "field", "where"}), |
| 599 | "visible_when": frozenset({"field", "equals", "in"}), |
| 600 | } |
| 601 | |
| 602 | |
| 603 | # A bound (`min`, `max`) is a finite number, or text that reads as one. This is |
| 604 | # the pattern dron-collection.schema.json gives `numericBound`; a test holds the |
| 605 | # two together. |
| 606 | _NUMERIC_BOUND_RE = re.compile(r"^\s*[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)([eE][+-]?[0-9]+)?\s*$") |
| 607 | |
| 608 | |
| 609 | def _is_numeric_bound(value: Any) -> bool: |
| 610 | if isinstance(value, bool): |
| 611 | return False |
| 612 | if isinstance(value, float): |
| 613 | return math.isfinite(value) |
| 614 | if isinstance(value, int): |
| 615 | return True |
| 616 | return isinstance(value, str) and _NUMERIC_BOUND_RE.fullmatch(value) is not None |
| 617 | |
| 618 | |
| 619 | def _one_of(choices: Iterable[str]) -> str: |
| 620 | """'a, b or c', in the order given.""" |
| 621 | names = list(choices) |
| 622 | return ", ".join(names[:-1]) + " or " + names[-1] |
| 623 | |
| 624 | |
| 625 | def _did_you_mean(value: str, choices: Iterable[str]) -> str: |
| 626 | match = difflib.get_close_matches(value, sorted(choices), n=1, cutoff=0.6) |
| 627 | return f" (did you mean {match[0]!r}?)" if match else "" |
| 628 | |
| 629 | |
| 630 | def _refuse_unknown_keys( |
| 631 | payload: Mapping[str, Any], |
| 632 | allowed: frozenset[str], |
| 633 | *, |
| 634 | where: str, |
| 635 | synonyms: Mapping[str, str] | None = None, |
| 636 | ) -> None: |
| 637 | for key in payload: |
| 638 | if key in allowed: |
| 639 | continue |
| 640 | if synonyms and key in synonyms: |
| 641 | raise ValueError( |
| 642 | f"{where}: {key!r} is not DRON; write {synonyms[key]} instead" |
| 643 | ) |
| 644 | raise ValueError(f"{where}: unknown key {key!r}{_did_you_mean(str(key), allowed)}") |
| 645 | |
| 646 | |
| 647 | # The sections of a collection declaration and what each is. A section of the |
| 648 | # wrong shape (`"hooks": "hook_x"`, `"capabilities": ["comments"]`) used to be |
| 649 | # skipped as if it had not been written. |
| 650 | _ROOT_OBJECT_HINTS = { |
| 651 | "hooks": '{"before_write": "hook_widgets"}', |
| 652 | "views": '{"list_mode": "table", "list_fields": ["name", "status"]}', |
| 653 | "search": '{"fields": ["name", "notes"]}', |
| 654 | "capabilities": '{"comments": true}', |
| 655 | "blocks": '{"feed": {"owner_field": "owner_id", "time_field": "created_at"}}', |
| 656 | "forms": '{"default": {"fields": ["name", "status"]}}', |
| 657 | "ui": "{}", "flow": "{}", "layout": "{}", "table": "{}", "diagram": "{}", |
| 658 | "validation": "{}", "permissions": "{}", |
| 659 | } |
| 660 | _ROOT_TEXT_KEYS = ("title", "description") |
| 661 | # Lists of field names: root object, key (a path through nested objects). |
| 662 | _FIELD_NAME_LISTS = ( |
| 663 | ("search", "fields"), ("search", "result_fields"), ("views", "list_fields"), |
| 664 | ("views", "detail_fields"), ("views", "filter_fields"), ("blocks", "feed", "summary_fields"), |
| 665 | ) |
| 666 | # One field name each. |
| 667 | _FIELD_NAME_KEYS = ( |
| 668 | ("views", "board", "group_field"), ("views", "tree", "parent_field"), |
| 669 | ("views", "calendar", "date_field"), ("blocks", "feed", "owner_field"), |
| 670 | ("blocks", "feed", "time_field"), ("blocks", "feed", "visibility_field"), |
| 671 | ("blocks", "feed", "link_field"), |
| 672 | ) |
| 673 | _NESTED_OBJECT_KEYS = (("views", "board"), ("views", "tree"), ("views", "calendar"), ("blocks", "feed")) |
| 674 | |
| 675 | |
| 676 | def _dig(payload: Any, path: tuple[str, ...]) -> Any: |
| 677 | """The value at `path`, or _ABSENT when a step is missing or not an object.""" |
| 678 | node = payload |
| 679 | for step in path: |
| 680 | if not isinstance(node, Mapping) or step not in node: |
| 681 | return _ABSENT |
| 682 | node = node[step] |
| 683 | return node |
| 684 | |
| 685 | |
| 686 | _ABSENT = object() |
| 687 | |
| 688 | |
| 689 | def _check_sections(schema: str, payload: Mapping[str, Any]) -> None: |
| 690 | """Every section is the shape DRON gives it: an object, text, a list of |
| 691 | field names, a field name. The loader skipped a section that was not an |
| 692 | object and read the rest as written.""" |
| 693 | for key in ("name", "collection"): |
| 694 | # "" and null fell back to the file's own name, as if unwritten. |
| 695 | if key in payload: |
| 696 | _require_collection_name(payload[key], where=schema, key=key, why="name this collection") |
| 697 | for section in ("unique", "locked_when"): |
| 698 | entries = payload.get(section) |
| 699 | for index, entry in enumerate(entries if isinstance(entries, list) else []): |
| 700 | if isinstance(entry, Mapping) and "message" in entry and not isinstance(entry["message"], str): |
| 701 | raise ValueError(f"{schema}: {section}[{index}]: message must be text, not {entry['message']!r}") |
| 702 | for key in _ROOT_TEXT_KEYS: |
| 703 | if key in payload and not isinstance(payload[key], str): |
| 704 | raise ValueError(f"{schema}: {key} must be text, not {payload[key]!r}") |
| 705 | for key, hint in _ROOT_OBJECT_HINTS.items(): |
| 706 | if key in payload and not isinstance(payload[key], Mapping): |
| 707 | raise ValueError(f"{schema}: {key} must be an object such as {hint}, not {payload[key]!r}") |
| 708 | forms = payload.get("forms") |
| 709 | for form_name, form in (forms.items() if isinstance(forms, Mapping) else ()): |
| 710 | if not isinstance(form, Mapping): |
| 711 | raise ValueError(f"{schema}: forms.{form_name} must be an object such as " |
| 712 | f'{{"fields": ["name"]}}, not {form!r}') |
| 713 | if "fields" in form: |
| 714 | _check_name_list(form["fields"], where=f"{schema}: forms.{form_name}.fields") |
| 715 | for path in _NESTED_OBJECT_KEYS: |
| 716 | value = _dig(payload, path) |
| 717 | if value is not _ABSENT and not isinstance(value, Mapping): |
| 718 | raise ValueError(f"{schema}: {'.'.join(path)} must be an object, not {value!r}") |
| 719 | for path in _FIELD_NAME_LISTS: |
| 720 | value = _dig(payload, path) |
| 721 | if value is not _ABSENT: |
| 722 | _check_name_list(value, where=f"{schema}: {'.'.join(path)}", |
| 723 | at_least_one=path == ("search", "fields")) |
| 724 | for path in _FIELD_NAME_KEYS: |
| 725 | value = _dig(payload, path) |
| 726 | if value is not _ABSENT: |
| 727 | _require_field_name(value, where=f"{schema}: {'.'.join(path[:-1])}", key=path[-1], |
| 728 | why="name a field of this collection") |
| 729 | feed = _dig(payload, ("blocks", "feed")) |
| 730 | if isinstance(feed, Mapping): |
| 731 | for key in ("owner_field", "time_field"): |
| 732 | if key not in feed: |
| 733 | raise ValueError(f"{schema}: blocks.feed: no {key} (the field the feed reads)") |
| 734 | if "visibility_true_value" in feed and not isinstance(feed["visibility_true_value"], str): |
| 735 | raise ValueError( |
| 736 | f"{schema}: blocks.feed: visibility_true_value must be text, " |
| 737 | f"not {feed['visibility_true_value']!r}") |
| 738 | related = _dig(payload, ("views", "related")) |
| 739 | if related is not _ABSENT: |
| 740 | if not isinstance(related, list): |
| 741 | raise ValueError(f"{schema}: views.related must be a list of " |
| 742 | f'{{"collection": ..., "fk_field": ...}}, not {related!r}') |
| 743 | for index, entry in enumerate(related): |
| 744 | here = f"{schema}: views.related[{index}]" |
| 745 | if not isinstance(entry, Mapping): |
| 746 | raise ValueError(f'{here} must be an object with collection and fk_field, not {entry!r}') |
| 747 | for key in ("collection", "fk_field"): |
| 748 | if key not in entry: |
| 749 | raise ValueError(f"{here}: no {key}") |
| 750 | _require_collection_name(entry["collection"], where=here, key="collection", |
| 751 | why="the collection that holds the related rows") |
| 752 | _require_field_name(entry["fk_field"], where=here, key="fk_field", |
| 753 | why="the field there that holds this record's id") |
| 754 | |
| 755 | |
| 756 | def _check_name_list(value: Any, *, where: str, at_least_one: bool = False) -> None: |
| 757 | if not isinstance(value, list): |
| 758 | raise ValueError(f"{where} must be a list of field names such as [\"name\", \"status\"], not {value!r}") |
| 759 | if at_least_one and not value: |
| 760 | raise ValueError(f"{where} must name at least one field") |
| 761 | for item in value: |
| 762 | if not (isinstance(item, str) and _FIELD_NAME_RE.fullmatch(item)): |
| 763 | raise ValueError(f"{where}: {item!r} is not a field name ({FIELD_NAME_RULE})") |
| 764 | |
| 765 | |
| 766 | def check_declaration(schema: str, payload: Any) -> None: |
| 767 | """Refuse a collection declaration DRON refuses; raise ValueError naming the key path. |
| 768 | |
| 769 | Run before `normalize_schema` on a package's schema file (see the note |
| 770 | above DECLARED_ROOT_KEYS for why the normalizer itself stays lenient). |
| 771 | Shapes the normalizer already checks (unique, locked_when, locked_checks, |
| 772 | transitions) are left to it. |
| 773 | """ |
| 774 | if not isinstance(payload, Mapping): |
| 775 | return # the normalizer refuses it, with its own message |
| 776 | _refuse_unknown_keys(payload, DECLARED_ROOT_KEYS, where=schema) |
| 777 | # Values the normalizer would coerce rather than refuse: int("3") and |
| 778 | # int(2.7) both load, so a version written as text was silently read. |
| 779 | version = payload.get("version") |
| 780 | if "version" in payload and (isinstance(version, bool) or not isinstance(version, int)): |
| 781 | if not (isinstance(version, float) and version.is_integer()): |
| 782 | raise ValueError(f"{schema}: version {version!r} must be a whole number such as 2") |
| 783 | _check_sections(schema, payload) |
| 784 | for key, allowed in _DECLARED_ROOT_OBJECTS.items(): |
| 785 | value = payload.get(key) |
| 786 | if not isinstance(value, Mapping): |
| 787 | continue |
| 788 | _refuse_unknown_keys(value, allowed, where=f"{schema}: {key}") |
| 789 | if key == "views" and "list_mode" in value and value["list_mode"] not in VIEW_LIST_MODES: |
| 790 | # Not an error at load: the list drew plain rows with a notice. |
| 791 | mode = value["list_mode"] |
| 792 | hint = _did_you_mean(mode, VIEW_LIST_MODES) if isinstance(mode, str) else "" |
| 793 | raise ValueError( |
| 794 | f"{schema}: views.list_mode {mode!r} is not a list mode; " |
| 795 | f"write one of {_one_of(VIEW_LIST_MODES)}{hint}") |
| 796 | if key == "hooks" and "before_write" in value: |
| 797 | hook = value["before_write"] |
| 798 | if not (isinstance(hook, str) and object_collections.validate_collection_name(hook)): |
| 799 | # Hooks and collections share the object-id shape. A name that |
| 800 | # is not one never resolves, and a declared hook that fails |
| 801 | # stops every public write of the collection. |
| 802 | raise ValueError( |
| 803 | f"{schema}: hooks.before_write {hook!r} is not an object id " |
| 804 | "(letters, digits and underscores, 1 to 64 characters)") |
| 805 | for (parent, child), nested in _DECLARED_NESTED_OBJECTS.items(): |
| 806 | if parent == key and isinstance(value.get(child), Mapping): |
| 807 | _refuse_unknown_keys(value[child], nested, where=f"{schema}: {key}.{child}") |
| 808 | if key == "views" and isinstance(value.get("related"), list): |
| 809 | for index, entry in enumerate(value["related"]): |
| 810 | if isinstance(entry, Mapping): |
| 811 | _refuse_unknown_keys( |
| 812 | entry, _DECLARED_VIEWS_RELATED_KEYS, where=f"{schema}: views.related[{index}]") |
| 813 | capabilities = payload.get("capabilities") |
| 814 | if isinstance(capabilities, Mapping): |
| 815 | for key, value in capabilities.items(): |
| 816 | if not isinstance(value, bool): |
| 817 | raise ValueError(f"{schema}: capabilities.{key} must be true or false, not {value!r}") |
| 818 | fields = payload.get("fields") |
| 819 | for index, field in enumerate(fields if isinstance(fields, list) else []): |
| 820 | if not isinstance(field, Mapping): |
| 821 | continue |
| 822 | name = field.get("name") |
| 823 | where = f"{schema}: field {name!r}" if isinstance(name, str) else f"{schema}: fields[{index}]" |
| 824 | _refuse_unknown_keys(field, DECLARED_FIELD_KEYS, where=where, synonyms=FIELD_SYNONYMS) |
| 825 | field_type = field.get("type") |
| 826 | if "type" in field and field_type not in DECLARED_FIELD_TYPES: |
| 827 | if isinstance(field_type, str) and field_type.strip().lower() in DECLARED_FIELD_TYPES: |
| 828 | raise ValueError( |
| 829 | f"{where}: type {field_type!r} is not DRON; write {field_type.strip().lower()!r}") |
| 830 | hint = _did_you_mean(field_type, DECLARED_FIELD_TYPES) if isinstance(field_type, str) else "" |
| 831 | raise ValueError( |
| 832 | f"{where}: unknown type {field_type!r}{hint} (an unknown type used to be " |
| 833 | "stored as unchecked text)") |
| 834 | if "enum" in field and not isinstance(field["enum"], list): |
| 835 | if isinstance(field["enum"], Mapping) and "values" in field["enum"]: |
| 836 | raise ValueError( |
| 837 | f'{where}: enum {{"values": [...]}} is not DRON; write the list itself, ' |
| 838 | '"enum": ["draft", "posted"]') |
| 839 | raise ValueError(f"{where}: enum must be a list of the allowed values") |
| 840 | # bool("no") is True: a flag written as text made the field required. |
| 841 | for flag in ("required", "read_only"): |
| 842 | if flag in field and not isinstance(field[flag], bool): |
| 843 | raise ValueError(f"{where}: {flag} must be true or false, not {field[flag]!r}") |
| 844 | validation = field.get("validation") |
| 845 | if isinstance(validation, Mapping): |
| 846 | _refuse_unknown_keys( |
| 847 | validation, DECLARED_VALIDATION_KEYS, where=f"{where} validation", |
| 848 | synonyms=VALIDATION_SYNONYMS) |
| 849 | # The loader left these to the first write, which then refused |
| 850 | # every value of the field. (exclusive_min and exclusive_max are |
| 851 | # already judged when the schema is normalized.) |
| 852 | for key in ("min", "max", "exclusive_min", "exclusive_max"): |
| 853 | if key in validation and not _is_numeric_bound(validation[key]): |
| 854 | raise ValueError( |
| 855 | f"{where} validation: {key} must be a number such as 1 or 2.5, " |
| 856 | f"not {validation[key]!r} (every value of the field would be refused)") |
| 857 | _check_validation_text_rules(validation, where=f"{where} validation") |
| 858 | for key, allowed in _DECLARED_FIELD_OBJECTS.items(): |
| 859 | if isinstance(field.get(key), Mapping): |
| 860 | _refuse_unknown_keys(field[key], allowed, where=f"{where} {key}") |
| 861 | _check_field_values(field, where=where) |
| 862 | _check_computed(field, where=where) |
| 863 | if "relation" in field: |
| 864 | _check_relation(field["relation"], where=where) |
| 865 | if "permissions" in field: |
| 866 | _check_field_permissions(field["permissions"], where=where) |
| 867 | _check_guard_variables(field.get("transitions"), where=where) |
| 868 | |
| 869 | |
| 870 | # The regular-expression dialect of `validation.pattern` (docs/dron.md, |
| 871 | # "Regular expressions"). A pattern is written in a subset that Python's `re` |
| 872 | # and ECMAScript (with the `u` flag, which JSON Schema names) read alike, and |
| 873 | # its meaning is fixed here, not left to the engine underneath: |
| 874 | # |
| 875 | # - the WHOLE value must match (ECMAScript: `^(?:pattern)$`); |
| 876 | # - `$` is the end of the value only (Python's `$` also matches before a |
| 877 | # final newline, so it is compiled as `\Z`); |
| 878 | # - `.` is any character but the four line ends ECMAScript names |
| 879 | # (Python's leaves out only `\n`); |
| 880 | # - `\d` and `\w` are ASCII (`re.ASCII`); `\s` is ECMAScript's white space, |
| 881 | # which neither of Python's two readings of `\s` is, so it is spelt out. |
| 882 | # |
| 883 | # `portable_pattern_source` is both the check and the translation: it raises |
| 884 | # PatternNotPortable with the reason, or returns the source Python compiles. |
| 885 | PATTERN_DIALECT = "DRON regular expression" |
| 886 | PATTERN_DIALECT_DOC = 'docs/dron.md, "Regular expressions"' |
| 887 | |
| 888 | # ECMAScript's WhiteSpace and LineTerminator, as the body of a Python class. |
| 889 | _PATTERN_SPACE = ( |
| 890 | r"\t\n\x0b\x0c\r \xa0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff") |
| 891 | _PATTERN_DOT = r"[^\n\r\u2028\u2029]" |
| 892 | # The characters a backslash may make literal: ECMAScript's syntax characters |
| 893 | # and `/`. Inside a class, `-` too. |
| 894 | _PATTERN_SYNTAX_CHARACTERS = "^$\\.*+?()[]{}|/" |
| 895 | _PATTERN_COUNT_RE = re.compile(r"\{([0-9]+)(,([0-9]*))?\}") |
| 896 | _PATTERN_HEX = frozenset("0123456789abcdefABCDEF") |
| 897 | _PATTERN_ESCAPES_REFUSED = { |
| 898 | "b": "\\b (a word boundary) is not in the dialect", |
| 899 | "B": "\\B (not a word boundary) is not in the dialect", |
| 900 | "A": "\\A is not in the dialect; write ^", |
| 901 | "Z": "\\Z is not in the dialect; write $", |
| 902 | "z": "\\z is not in the dialect; write $", |
| 903 | "k": "a named backreference (\\k) is not in the dialect", |
| 904 | "p": "a Unicode property (\\p) is not in the dialect; write the characters or ranges", |
| 905 | "P": "a Unicode property (\\P) is not in the dialect; write the characters or ranges", |
| 906 | "c": "a control escape (\\c) is not in the dialect; write \\xHH", |
| 907 | "N": "a named character (\\N) is not in the dialect; write \\uXXXX", |
| 908 | "U": "\\U is not in the dialect; write the character itself", |
| 909 | "a": "\\a is not in the dialect; write \\x07", |
| 910 | "e": "\\e is not in the dialect; write \\x1b", |
| 911 | } |
| 912 | |
| 913 | |
| 914 | class PatternNotPortable(ValueError): |
| 915 | """A pattern outside the DRON regular-expression dialect; the text is the reason.""" |
| 916 | |
| 917 | |
| 918 | def _pattern_character(code: int) -> str: |
| 919 | """One literal character, written so that nothing in it is special to `re`.""" |
| 920 | char = chr(code) |
| 921 | if char.isascii() and char.isalnum(): |
| 922 | return char |
| 923 | if code <= 0xFF: |
| 924 | return f"\\x{code:02x}" |
| 925 | if code <= 0xFFFF: |
| 926 | return f"\\u{code:04x}" |
| 927 | return f"\\U{code:08x}" |
| 928 | |
| 929 | |
| 930 | def _pattern_escape(pattern: str, at: int, *, in_class: bool) -> tuple[str, Any, int]: |
| 931 | """Read the escape whose backslash is at `at`. Returns (kind, value, next |
| 932 | index): kind "char" with a code point, or "set" with one of d D w W s S.""" |
| 933 | if at + 1 >= len(pattern): |
| 934 | raise PatternNotPortable("it ends in a backslash with nothing after it") |
| 935 | char = pattern[at + 1] |
| 936 | if char in "dDwWsS": |
| 937 | return "set", char, at + 2 |
| 938 | if char in "tnrfv": |
| 939 | return "char", ord({"t": "\t", "n": "\n", "r": "\r", "f": "\f", "v": "\v"}[char]), at + 2 |
| 940 | if char in "xu": |
| 941 | width = 2 if char == "x" else 4 |
| 942 | digits = pattern[at + 2:at + 2 + width] |
| 943 | if len(digits) != width or not set(digits) <= _PATTERN_HEX: |
| 944 | if char == "u" and pattern[at + 2:at + 3] == "{": |
| 945 | raise PatternNotPortable( |
| 946 | f"\\u{{...}} at position {at} is not in the dialect; write \\uXXXX or the character itself") |
| 947 | raise PatternNotPortable( |
| 948 | f"\\{char} at position {at} must be followed by exactly {width} hexadecimal digits") |
| 949 | code = int(digits, 16) |
| 950 | if 0xD800 <= code <= 0xDFFF: |
| 951 | raise PatternNotPortable( |
| 952 | f"\\u{digits} at position {at} is half of a surrogate pair; write the character itself") |
| 953 | return "char", code, at + 2 + width |
| 954 | if char in _PATTERN_SYNTAX_CHARACTERS or (in_class and char == "-"): |
| 955 | return "char", ord(char), at + 2 |
| 956 | if char in "0123456789": |
| 957 | if char == "0": |
| 958 | raise PatternNotPortable(f"\\0 at position {at} is not in the dialect; write \\x00") |
| 959 | raise PatternNotPortable(f"a backreference (\\{char} at position {at}) is not in the dialect") |
| 960 | if in_class and char == "b": |
| 961 | raise PatternNotPortable(f"\\b at position {at} is not in the dialect; write \\x08 for a backspace") |
| 962 | if char in _PATTERN_ESCAPES_REFUSED: |
| 963 | raise PatternNotPortable(f"{_PATTERN_ESCAPES_REFUSED[char]} (position {at})") |
| 964 | if char.isascii() and char.isalnum(): |
| 965 | raise PatternNotPortable(f"the escape \\{char} at position {at} is not in the dialect") |
| 966 | raise PatternNotPortable( |
| 967 | f"the escape \\{char} at position {at} is not in the dialect; write {char!r} without the backslash") |
| 968 | |
| 969 | |
| 970 | def _pattern_class(pattern: str, at: int) -> tuple[str, int]: |
| 971 | """Read the class whose `[` is at `at`. Returns (Python source, next index).""" |
| 972 | index = at + 1 |
| 973 | out = ["["] |
| 974 | if pattern.startswith("^", index): |
| 975 | out.append("^") |
| 976 | index += 1 |
| 977 | if pattern.startswith("]", index): |
| 978 | raise PatternNotPortable( |
| 979 | f"the class at position {at} is empty, or starts with a ]; write \\] for a literal ]") |
| 980 | first = True |
| 981 | while True: |
| 982 | if index >= len(pattern): |
| 983 | raise PatternNotPortable(f"the [ at position {at} is never closed") |
| 984 | char = pattern[index] |
| 985 | if char == "]": |
| 986 | out.append("]") |
| 987 | return "".join(out), index + 1 |
| 988 | if 0xD800 <= ord(char) <= 0xDFFF: |
| 989 | raise PatternNotPortable(f"half of a surrogate pair at position {index} is not a character") |
| 990 | if char == "[": |
| 991 | raise PatternNotPortable(f"a literal [ inside a class is written \\[ (position {index})") |
| 992 | if char in "&|~" and pattern.startswith(char, index + 1): |
| 993 | raise PatternNotPortable( |
| 994 | f"{char}{char} inside a class (position {index}) is not in the dialect") |
| 995 | if char == "-" and not first and index + 1 < len(pattern) and pattern[index + 1] != "]": |
| 996 | raise PatternNotPortable( |
| 997 | f"a literal - inside a class is written first, last or as \\- (position {index})") |
| 998 | if char == "\\": |
| 999 | kind, value, index = _pattern_escape(pattern, index, in_class=True) |
| 1000 | else: |
| 1001 | kind, value, index = "char", ord(char), index + 1 |
| 1002 | first = False |
| 1003 | is_range = (pattern.startswith("-", index) and index + 1 < len(pattern) |
| 1004 | and pattern[index + 1] != "]") |
| 1005 | if kind == "set": |
| 1006 | if is_range: |
| 1007 | raise PatternNotPortable( |
| 1008 | f"\\{value} cannot start a range; write the - last or as \\- (position {index})") |
| 1009 | if value == "S": |
| 1010 | raise PatternNotPortable( |
| 1011 | "\\S inside a class is not in the dialect; write \\S outside a class, or [^\\s]") |
| 1012 | out.append(_PATTERN_SPACE if value == "s" else f"\\{value}") |
| 1013 | continue |
| 1014 | if not is_range: |
| 1015 | out.append(_pattern_character(value)) |
| 1016 | continue |
| 1017 | dash = index |
| 1018 | index += 1 |
| 1019 | if pattern[index] == "[": |
| 1020 | raise PatternNotPortable(f"a literal [ inside a class is written \\[ (position {index})") |
| 1021 | if pattern[index] == "\\": |
| 1022 | kind, high, index = _pattern_escape(pattern, index, in_class=True) |
| 1023 | else: |
| 1024 | kind, high, index = "char", ord(pattern[index]), index + 1 |
| 1025 | if kind == "set": |
| 1026 | raise PatternNotPortable( |
| 1027 | f"\\{high} cannot end a range; write the - last or as \\- (position {dash})") |
| 1028 | if high < value: |
| 1029 | raise PatternNotPortable( |
| 1030 | f"the range {chr(value)}-{chr(high)} at position {dash - 1} is out of order") |
| 1031 | out.append(f"{_pattern_character(value)}-{_pattern_character(high)}") |
| 1032 | |
| 1033 | |
| 1034 | def _pattern_group_opening(pattern: str, at: int) -> tuple[str, str]: |
| 1035 | """The `(` at `at`: (the text that opens the group, "group" or "lookahead").""" |
| 1036 | if not pattern.startswith("?", at + 1): |
| 1037 | return "(", "group" |
| 1038 | mark = pattern[at + 2:at + 3] |
| 1039 | if mark == ":": |
| 1040 | return "(?:", "group" |
| 1041 | if mark in ("=", "!"): |
| 1042 | return "(?" + mark, "lookahead" |
| 1043 | if mark == "<" and pattern[at + 3:at + 4] in ("=", "!"): |
| 1044 | raise PatternNotPortable(f"a lookbehind ({pattern[at:at + 4]} at position {at}) is not in the dialect") |
| 1045 | if mark in ("<", "P", "'"): |
| 1046 | raise PatternNotPortable(f"a named group (position {at}) is not in the dialect; write ( or (?:") |
| 1047 | if mark == "#": |
| 1048 | raise PatternNotPortable(f"a comment (?#...) (position {at}) is not in the dialect") |
| 1049 | if mark == ">": |
| 1050 | raise PatternNotPortable(f"an atomic group (?>...) (position {at}) is not in the dialect") |
| 1051 | if mark == "(": |
| 1052 | raise PatternNotPortable(f"a conditional (?(...) (position {at}) is not in the dialect") |
| 1053 | if mark == "": |
| 1054 | raise PatternNotPortable(f"the ( at position {at} is never closed") |
| 1055 | raise PatternNotPortable( |
| 1056 | f"an inline flag ({pattern[at:at + 3]} at position {at}) is not in the dialect; " |
| 1057 | "write both cases, as in [Aa]") |
| 1058 | |
| 1059 | |
| 1060 | def portable_pattern_source(pattern: str) -> str: |
| 1061 | """The Python `re` source (to compile with `re.ASCII`) that gives `pattern` |
| 1062 | its DRON meaning. Raises PatternNotPortable, with the reason, for a pattern |
| 1063 | outside the dialect.""" |
| 1064 | out: list[str] = [] |
| 1065 | groups: list[tuple[str, int]] = [] |
| 1066 | # What stands just before: "atom" (something a quantifier may repeat), |
| 1067 | # "quantifier", "lazy", or "" / "anchor" / "lookahead" (nothing to repeat). |
| 1068 | before = "" |
| 1069 | index = 0 |
| 1070 | length = len(pattern) |
| 1071 | while index < length: |
| 1072 | char = pattern[index] |
| 1073 | if 0xD800 <= ord(char) <= 0xDFFF: |
| 1074 | raise PatternNotPortable(f"half of a surrogate pair at position {index} is not a character") |
| 1075 | count = _PATTERN_COUNT_RE.match(pattern, index) if char == "{" else None |
| 1076 | if char in "*+?" or count: |
| 1077 | if before == "quantifier" and char == "?": |
| 1078 | out.append("?") |
| 1079 | before = "lazy" |
| 1080 | index += 1 |
| 1081 | continue |
| 1082 | if before == "quantifier" and char == "+": |
| 1083 | raise PatternNotPortable( |
| 1084 | f"a possessive quantifier (the + at position {index}) is not in the dialect") |
| 1085 | if before != "atom": |
| 1086 | what = {"anchor": "an anchor cannot be repeated", |
| 1087 | "lookahead": "a lookahead cannot be repeated", |
| 1088 | "": f"write \\{char} for a literal {char}"}.get(before, "it follows another quantifier") |
| 1089 | raise PatternNotPortable( |
| 1090 | f"the {char} at position {index} has nothing to repeat ({what})") |
| 1091 | if count: |
| 1092 | low, high = count.group(1), count.group(3) |
| 1093 | if high and int(high) < int(low): |
| 1094 | raise PatternNotPortable( |
| 1095 | f"the count {count.group(0)} at position {index} has its numbers out of order") |
| 1096 | out.append(count.group(0)) |
| 1097 | index = count.end() |
| 1098 | else: |
| 1099 | out.append(char) |
| 1100 | index += 1 |
| 1101 | before = "quantifier" |
| 1102 | continue |
| 1103 | if char == "{": |
| 1104 | raise PatternNotPortable( |
| 1105 | f"the {{ at position {index} is not a count such as {{2}}, {{2,}} or {{2,5}}; " |
| 1106 | "write \\{ for a literal {") |
| 1107 | if char in "}]": |
| 1108 | raise PatternNotPortable(f"a literal {char} is written \\{char} (position {index})") |
| 1109 | if char == "\\": |
| 1110 | kind, value, index = _pattern_escape(pattern, index, in_class=False) |
| 1111 | if kind == "char": |
| 1112 | out.append(_pattern_character(value)) |
| 1113 | elif value in "sS": |
| 1114 | out.append(f"[{'^' if value == 'S' else ''}{_PATTERN_SPACE}]") |
| 1115 | else: |
| 1116 | out.append(f"\\{value}") |
| 1117 | before = "atom" |
| 1118 | continue |
| 1119 | if char == "[": |
| 1120 | source, index = _pattern_class(pattern, index) |
| 1121 | out.append(source) |
| 1122 | before = "atom" |
| 1123 | continue |
| 1124 | if char == "(": |
| 1125 | opening, kind = _pattern_group_opening(pattern, index) |
| 1126 | groups.append((kind, index)) |
| 1127 | out.append(opening) |
| 1128 | index += len(opening) |
| 1129 | before = "" |
| 1130 | continue |
| 1131 | if char == ")": |
| 1132 | if not groups: |
| 1133 | raise PatternNotPortable(f"the ) at position {index} closes nothing; write \\) for a literal )") |
| 1134 | kind, _ = groups.pop() |
| 1135 | out.append(")") |
| 1136 | index += 1 |
| 1137 | # ECMAScript refuses a repeated lookahead; Python allows it. |
| 1138 | before = "atom" if kind == "group" else "lookahead" |
| 1139 | continue |
| 1140 | if char == "|": |
| 1141 | out.append("|") |
| 1142 | before = "" |
| 1143 | elif char == "^": |
| 1144 | out.append("^") |
| 1145 | before = "anchor" |
| 1146 | elif char == "$": |
| 1147 | out.append("\\Z") |
| 1148 | before = "anchor" |
| 1149 | elif char == ".": |
| 1150 | out.append(_PATTERN_DOT) |
| 1151 | before = "atom" |
| 1152 | else: |
| 1153 | out.append(_pattern_character(ord(char))) |
| 1154 | before = "atom" |
| 1155 | index += 1 |
| 1156 | if groups: |
| 1157 | raise PatternNotPortable(f"the ( at position {groups[-1][1]} is never closed") |
| 1158 | return "".join(out) |
| 1159 | |
| 1160 | |
| 1161 | def pattern_problem(pattern: Any) -> str | None: |
| 1162 | """Why `pattern` is not a DRON regular expression, or None when it is one.""" |
| 1163 | if not isinstance(pattern, str): |
| 1164 | return f"it must be text, not {pattern!r}" |
| 1165 | try: |
| 1166 | source = portable_pattern_source(pattern) |
| 1167 | except PatternNotPortable as exc: |
| 1168 | return str(exc) |
| 1169 | try: |
| 1170 | re.compile(source, re.ASCII) |
| 1171 | except (re.error, OverflowError, RecursionError) as exc: |
| 1172 | return f"it does not compile ({exc})" |
| 1173 | return None |
| 1174 | |
| 1175 | |
| 1176 | _PATTERN_CACHE: dict[str, "re.Pattern[str]"] = {} |
| 1177 | _PATTERN_CACHE_LIMIT = 512 |
| 1178 | |
| 1179 | |
| 1180 | def compile_pattern(pattern: str) -> "re.Pattern[str]": |
| 1181 | """The compiled form the engine matches a value against, with `fullmatch`. |
| 1182 | |
| 1183 | A pattern in the dialect gets the dialect's meaning. One outside it can |
| 1184 | only come from a schema already stored on the box or saved through the |
| 1185 | schema API (a package declaring it is refused at install): it is read with |
| 1186 | Python's `re` exactly as it was before the dialect existed, so a box keeps |
| 1187 | reading its own schemas. Raises `re.error` for a pattern `re` refuses.""" |
| 1188 | compiled = _PATTERN_CACHE.get(pattern) |
| 1189 | if compiled is None: |
| 1190 | try: |
| 1191 | compiled = re.compile(portable_pattern_source(pattern), re.ASCII) |
| 1192 | except (PatternNotPortable, re.error, OverflowError, RecursionError): |
| 1193 | compiled = re.compile(pattern) |
| 1194 | if len(_PATTERN_CACHE) >= _PATTERN_CACHE_LIMIT: |
| 1195 | _PATTERN_CACHE.clear() |
| 1196 | _PATTERN_CACHE[pattern] = compiled |
| 1197 | return compiled |
| 1198 | |
| 1199 | |
| 1200 | def pattern_matches(pattern: str, value: str) -> bool: |
| 1201 | """Whether the whole of `value` matches `pattern` (docs/dron.md, "Regular |
| 1202 | expressions"). Raises `re.error` for a pattern that cannot be compiled.""" |
| 1203 | return compile_pattern(pattern).fullmatch(value) is not None |
| 1204 | |
| 1205 | |
| 1206 | def _check_validation_text_rules(validation: Mapping[str, Any], *, where: str) -> None: |
| 1207 | """`min_length` and `max_length` are whole numbers of at least 0, and |
| 1208 | `pattern` is a regular expression. The engine cut 2.5 to 2, read "3" as 3 |
| 1209 | and True as 1, and refused every write of the field for a pattern that |
| 1210 | would not compile.""" |
| 1211 | for key in ("min_length", "max_length"): |
| 1212 | if key not in validation: |
| 1213 | continue |
| 1214 | value = validation[key] |
| 1215 | whole = isinstance(value, int) and not isinstance(value, bool) or ( |
| 1216 | isinstance(value, float) and value.is_integer()) |
| 1217 | if not whole or value < 0: |
| 1218 | raise ValueError( |
| 1219 | f"{where}: {key} must be a whole number of at least 0 such as 3, not {value!r}") |
| 1220 | if "pattern" in validation: |
| 1221 | pattern = validation["pattern"] |
| 1222 | if not isinstance(pattern, str): |
| 1223 | raise ValueError(f"{where}: pattern must be text holding a regular expression, not {pattern!r}") |
| 1224 | problem = pattern_problem(pattern) |
| 1225 | if problem: |
| 1226 | raise ValueError( |
| 1227 | f"{where}: pattern {pattern!r} is not a {PATTERN_DIALECT}: {problem}. " |
| 1228 | f"The dialect is in {PATTERN_DIALECT_DOC}") |
| 1229 | |
| 1230 | |
| 1231 | def _check_field_values(field: Mapping[str, Any], *, where: str) -> None: |
| 1232 | """The plain values of a field are the kind DRON gives them. The loader |
| 1233 | stored a label that was a number, a default that was a list, a ui that was |
| 1234 | text and a validation that was not an object, and the engine then ignored |
| 1235 | or tripped over them.""" |
| 1236 | for key in ("label", "help", "placeholder", "description"): |
| 1237 | if key in field and not isinstance(field[key], str): |
| 1238 | raise ValueError(f"{where}: {key} must be text, not {field[key]!r}") |
| 1239 | if "default" in field and not ( |
| 1240 | field["default"] is None or isinstance(field["default"], (str, int, float, bool)) |
| 1241 | ): |
| 1242 | raise ValueError( |
| 1243 | f"{where}: default must be one text, number or true/false value (or null), " |
| 1244 | f"not {field['default']!r}") |
| 1245 | for key in ("ui", "layout", "validation"): |
| 1246 | if key in field and not isinstance(field[key], Mapping): |
| 1247 | raise ValueError(f"{where}: {key} must be an object, not {field[key]!r}") |
| 1248 | if "enum" in field and isinstance(field["enum"], list): |
| 1249 | values = field["enum"] |
| 1250 | if not values: |
| 1251 | raise ValueError(f"{where}: enum must list at least one allowed value") |
| 1252 | for index, value in enumerate(values): |
| 1253 | if not isinstance(value, (str, int, float, bool)): |
| 1254 | raise ValueError( |
| 1255 | f"{where}: enum value {value!r} must be text, a number or true/false") |
| 1256 | if any(type(value) is type(other) and value == other for other in values[:index]): |
| 1257 | raise ValueError(f"{where}: enum value {value!r} is listed twice") |
| 1258 | if "store" in field and field["store"] != "extra": |
| 1259 | raise ValueError(f'{where}: store must be "extra" (the only value DRON defines), not {field["store"]!r}') |
| 1260 | if "visible_when" in field: |
| 1261 | _check_visible_when(field["visible_when"], where=where) |
| 1262 | |
| 1263 | |
| 1264 | def _check_visible_when(rule: Any, *, where: str) -> None: |
| 1265 | here = f"{where} visible_when" |
| 1266 | if not isinstance(rule, Mapping): |
| 1267 | raise ValueError( |
| 1268 | f'{here} must be an object such as {{"field": "kind", "equals": "asset"}}, not {rule!r}') |
| 1269 | if "field" not in rule: |
| 1270 | raise ValueError(f"{here}: no field (the field whose value decides whether this one shows)") |
| 1271 | _require_field_name(rule["field"], where=here, key="field", why="name another field of this collection") |
| 1272 | if "equals" in rule and not isinstance(rule["equals"], str): |
| 1273 | raise ValueError(f"{here}: equals must be text, not {rule['equals']!r}") |
| 1274 | if "in" in rule: |
| 1275 | listed = rule["in"] |
| 1276 | if not (isinstance(listed, list) and all(isinstance(item, str) for item in listed)): |
| 1277 | raise ValueError(f"{here}: in must be a list of text values, not {listed!r}") |
| 1278 | |
| 1279 | |
| 1280 | FIELD_NAME_RULE = "letters, digits and underscores, not starting with a digit, 1 to 64 characters" |
| 1281 | COLLECTION_NAME_RULE = "letters, digits and underscores, 1 to 64 characters" |
| 1282 | |
| 1283 | |
| 1284 | def _require_field_name(value: Any, *, where: str, key: str, why: str) -> None: |
| 1285 | if not (isinstance(value, str) and _FIELD_NAME_RE.fullmatch(value)): |
| 1286 | raise ValueError(f"{where}: {key} {value!r} is not a field name ({FIELD_NAME_RULE}); {why}") |
| 1287 | |
| 1288 | |
| 1289 | def _require_collection_name(value: Any, *, where: str, key: str, why: str) -> None: |
| 1290 | if not (isinstance(value, str) and object_collections.validate_collection_name(value)): |
| 1291 | raise ValueError(f"{where}: {key} {value!r} is not a collection name ({COLLECTION_NAME_RULE}); {why}") |
| 1292 | |
| 1293 | |
| 1294 | def _check_computed(field: Mapping[str, Any], *, where: str) -> None: |
| 1295 | """A formula or a rollup is filled in only on a computed field (the engine |
| 1296 | kept the key on any other and the field stayed blank), and a rollup the |
| 1297 | engine cannot compute (no collection, fk_field or op, an op it does not |
| 1298 | know, a sum with no field) was skipped without a word.""" |
| 1299 | field_type = field.get("type") |
| 1300 | for key in ("formula", "rollup"): |
| 1301 | if key in field and field_type != "computed": |
| 1302 | shown = f"type {field_type!r}" if "type" in field else "type 'text' (the default)" |
| 1303 | raise ValueError( |
| 1304 | f'{where}: {key} is only evaluated on a field with "type": "computed", ' |
| 1305 | f'and this one is {shown}') |
| 1306 | if "rollup" not in field: |
| 1307 | return |
| 1308 | if "formula" in field: |
| 1309 | # Rollups are applied first and then formulas, so the formula's result |
| 1310 | # replaced the rollup's: one of the two never showed. |
| 1311 | raise ValueError( |
| 1312 | f"{where}: has both a formula and a rollup; a computed field has one or the other " |
| 1313 | "(the formula's result would replace the rollup's)") |
| 1314 | rollup = field["rollup"] |
| 1315 | here = f"{where} rollup" |
| 1316 | ops = _one_of(sorted(object_computed.ROLLUP_OPS)) |
| 1317 | if not isinstance(rollup, Mapping): |
| 1318 | raise ValueError( |
| 1319 | f"{here} must be an object with collection, fk_field and op, not {rollup!r}") |
| 1320 | for key, meaning in ( |
| 1321 | ("collection", "the child collection to aggregate"), |
| 1322 | ("fk_field", "the child field that holds this record's id"), |
| 1323 | ("op", f"write one of {ops}"), |
| 1324 | ): |
| 1325 | if key not in rollup: |
| 1326 | raise ValueError(f"{here}: no {key} ({meaning})") |
| 1327 | op = rollup["op"] |
| 1328 | if op not in object_computed.ROLLUP_OPS: |
| 1329 | if isinstance(op, str) and op.strip().lower() in object_computed.ROLLUP_OPS: |
| 1330 | raise ValueError(f"{here}: op {op!r} is not DRON; write {op.strip().lower()!r}") |
| 1331 | hint = _did_you_mean(op, object_computed.ROLLUP_OPS) if isinstance(op, str) else "" |
| 1332 | raise ValueError(f"{here}: op {op!r} is not a rollup op; write one of {ops}{hint}") |
| 1333 | if op != "count" and "field" not in rollup: |
| 1334 | raise ValueError( |
| 1335 | f"{here}: op {op!r} needs a field, the child field it aggregates " |
| 1336 | "(only count works without one)") |
| 1337 | # The three names the engine would look up in the child collection. |
| 1338 | _require_collection_name( |
| 1339 | rollup["collection"], where=here, key="collection", why="no such collection can exist") |
| 1340 | _require_field_name( |
| 1341 | rollup["fk_field"], where=here, key="fk_field", why="no such field can exist") |
| 1342 | if "field" in rollup: |
| 1343 | _require_field_name(rollup["field"], where=here, key="field", why="no such field can exist") |
| 1344 | if "where" in rollup: |
| 1345 | narrow = rollup["where"] |
| 1346 | if not isinstance(narrow, Mapping): |
| 1347 | raise ValueError( |
| 1348 | f'{here}: where must be an object of child field to the one value it must equal, ' |
| 1349 | f'such as {{"status": "paid"}}, not {narrow!r} (it would be ignored and every child row counted)') |
| 1350 | for name, wanted in narrow.items(): |
| 1351 | _require_field_name(name, where=here, key="where field", why="no such field can exist") |
| 1352 | if not isinstance(wanted, (str, int, float)): # a bool is an int |
| 1353 | raise ValueError( |
| 1354 | f"{here}: where.{name} must be one text, number or true/false value, not {wanted!r}") |
| 1355 | |
| 1356 | |
| 1357 | def _check_relation(relation: Any, *, where: str) -> None: |
| 1358 | """A relation names the collection its ids must exist in: a bare name, or |
| 1359 | {"collection": name, ...}. Without one the loader read the field as fine |
| 1360 | and refused every record written to it ("has an invalid collection").""" |
| 1361 | if isinstance(relation, Mapping): |
| 1362 | if "collection" not in relation: |
| 1363 | raise ValueError( |
| 1364 | f"{where} relation: no collection (name the collection the id must exist in, " |
| 1365 | '{"collection": "projects"})') |
| 1366 | target = relation["collection"] |
| 1367 | elif isinstance(relation, str): |
| 1368 | target = relation |
| 1369 | else: |
| 1370 | raise ValueError( |
| 1371 | f"{where} relation must be a collection name or an object with a collection, " |
| 1372 | f"not {relation!r}") |
| 1373 | if not (isinstance(target, str) and object_collections.validate_collection_name(target)): |
| 1374 | raise ValueError( |
| 1375 | f"{where} relation: collection {target!r} is not a collection name " |
| 1376 | "(letters, digits and underscores, 1 to 64 characters)") |
| 1377 | if isinstance(relation, Mapping) and "display_field" in relation: |
| 1378 | _require_field_name( |
| 1379 | relation["display_field"], where=f"{where} relation", key="display_field", |
| 1380 | why="it names the field of the related record shown in its place") |
| 1381 | |
| 1382 | |
| 1383 | # The three access levels of a field's `permissions` (DRON's fieldAccess). |
| 1384 | FIELD_ACCESS_LEVELS = ("edit", "read", "hidden") |
| 1385 | |
| 1386 | |
| 1387 | def _check_access_level(value: Any, *, where: str) -> None: |
| 1388 | if isinstance(value, str) and value in FIELD_ACCESS_LEVELS: |
| 1389 | return |
| 1390 | if not isinstance(value, str): |
| 1391 | raise ValueError(f"{where}: access must be edit, read or hidden, not {value!r}") |
| 1392 | import object_field_permissions # it imports this module, so not at the top |
| 1393 | |
| 1394 | engine_level = object_field_permissions.access_level(value) |
| 1395 | if engine_level is not None: |
| 1396 | raise ValueError(f"{where}: {value!r} is not DRON; write {engine_level!r}") |
| 1397 | raise ValueError( |
| 1398 | f"{where}: {value!r} is not an access level; write edit, read or hidden" |
| 1399 | f"{_did_you_mean(value, FIELD_ACCESS_LEVELS)}") |
| 1400 | |
| 1401 | |
| 1402 | def _engine_access_level(spelling: str) -> str | None: |
| 1403 | import object_field_permissions # it imports this module, so not at the top |
| 1404 | |
| 1405 | return object_field_permissions.access_level(spelling) |
| 1406 | |
| 1407 | |
| 1408 | def _check_field_permissions(permissions: Any, *, where: str) -> None: |
| 1409 | """A field's `permissions` is an access level for everyone, or an object of |
| 1410 | principal to level (plus `default` and `roles`). The loader read a level it |
| 1411 | did not know only when a request first touched the field, and then failed.""" |
| 1412 | if isinstance(permissions, str): |
| 1413 | return _check_access_level(permissions, where=f"{where} permissions") |
| 1414 | if not isinstance(permissions, Mapping): |
| 1415 | raise ValueError( |
| 1416 | f"{where} permissions must be an access level (edit, read or hidden) " |
| 1417 | f"or an object of principal to level, not {permissions!r}") |
| 1418 | for key, value in permissions.items(): |
| 1419 | here = f"{where} permissions.{key}" |
| 1420 | if key == "roles": |
| 1421 | if not isinstance(value, Mapping): |
| 1422 | raise ValueError(f"{here}: must be an object of role name to access level") |
| 1423 | for role, level in value.items(): |
| 1424 | _check_access_level(level, where=f"{here}.{role}") |
| 1425 | elif isinstance(value, list) and key != "default": |
| 1426 | # An access level mapped to the principals it applies to. The |
| 1427 | # engine reads a list only under these three keys; under any other |
| 1428 | # it raised at the first request that touched the field. |
| 1429 | if key not in FIELD_ACCESS_LEVELS: |
| 1430 | engine_level = _engine_access_level(key) |
| 1431 | if engine_level is not None: |
| 1432 | raise ValueError(f"{here}: {key!r} is not DRON; write {engine_level!r} for a list of principals") |
| 1433 | raise ValueError( |
| 1434 | f"{here}: a list of principals belongs under edit, read or hidden, as " |
| 1435 | f'{{"edit": [{key!r}]}}; give a principal one access level instead, as {{{key!r}: "read"}}') |
| 1436 | if not all(isinstance(item, str) and item for item in value): |
| 1437 | raise ValueError(f"{here}: a principal must be non-empty text, in {value!r}") |
| 1438 | else: |
| 1439 | _check_access_level(value, where=here) |
| 1440 | |
| 1441 | |
| 1442 | def _check_guard_variables(transitions: Any, *, where: str) -> None: |
| 1443 | """A guard value starting with $ must be one of the row-filter variables. |
| 1444 | Anything else ("$userid") is compared literally, so the move can never |
| 1445 | happen; DRON refuses it, and so does a package install.""" |
| 1446 | if not isinstance(transitions, Mapping): |
| 1447 | return |
| 1448 | for from_value, entries in transitions.items(): |
| 1449 | for entry in entries if isinstance(entries, list) else []: |
| 1450 | when = entry.get("when") if isinstance(entry, Mapping) else None |
| 1451 | for key, value in (when.items() if isinstance(when, Mapping) else ()): |
| 1452 | if isinstance(value, str) and value.startswith("$") and ( |
| 1453 | value not in object_permissions.FILTER_VARIABLES |
| 1454 | ): |
| 1455 | raise ValueError( |
| 1456 | f"{where} transitions[{from_value!r}] when.{key}: {value!r} is not a " |
| 1457 | f"$-variable{_did_you_mean(value, object_permissions.FILTER_VARIABLES)} " |
| 1458 | "(it would be compared literally and the move could never happen)" |
| 1459 | ) |
| 1460 | |
| 1461 | |
| 1462 | def normalize_declaration(schema: str, payload: Any) -> dict[str, Any]: |
| 1463 | """A package's schema file: held to DRON, then normalized.""" |
| 1464 | check_declaration(schema, payload) |
| 1465 | return normalize_schema(schema, payload, source="manual") |
| 1466 | |
| 1467 | |
| 1468 | _UNIQUE_KEYS = frozenset({"fields", "scope", "ignore_case", "message"}) |
| 1469 | |
| 1470 | |
| 1471 | def _normalize_unique( |
| 1472 | value: Any, |
| 1473 | *, |
| 1474 | schema: str, |
| 1475 | fields: list[dict[str, Any]], |
| 1476 | ) -> list[dict[str, Any]]: |
| 1477 | """Validate a root-level ``unique`` declaration; return its canonical form. |
| 1478 | |
| 1479 | "unique": [ |
| 1480 | {"fields": ["event_id"], "scope": ["owner_id"]}, |
| 1481 | {"fields": ["code"], "ignore_case": true, "message": "..."} |
| 1482 | ] |
| 1483 | |
| 1484 | Each entry says: no two records may hold the same ``fields`` values |
| 1485 | (within the same ``scope`` values, when a scope is given). It is |
| 1486 | enforced by object_records inside the write lock -- see |
| 1487 | object_records._check_unique_constraints for what counts as "the same" |
| 1488 | and why a hook could not do this. |
| 1489 | |
| 1490 | Unlike the keys below, this one is INTERPRETED, and it is a gate, so |
| 1491 | it is validated strictly and anything unenforceable is an error rather |
| 1492 | than a constraint that quietly is not there: |
| 1493 | |
| 1494 | - An entry must be an object. A bare name or list of names is refused |
| 1495 | because it has two readings (`["owner_id", "event_id"]`: one |
| 1496 | compound key, or two keys?) and the wrong one makes owner_id unique |
| 1497 | -- every owner limited to one row. |
| 1498 | - Unknown keys are refused: `ignore_cas` must not load as |
| 1499 | case-sensitive. |
| 1500 | - `id` is refused (already unique). A computed field is refused (the |
| 1501 | server writes it, and a rollup recompute is not a moment to refuse a |
| 1502 | write). A `store: extra` field is refused (its value lives inside |
| 1503 | the JSON `extra` column, which the index does not read). |
| 1504 | |
| 1505 | A named field does NOT have to be declared in ``fields``: records |
| 1506 | accept undeclared columns, and a constraint over one is enforceable. |
| 1507 | The canonical form always carries `scope` and `ignore_case`, so a |
| 1508 | stored (already normalized) schema normalizes to itself. |
| 1509 | """ |
| 1510 | where = f"Schema unique constraint in {schema}" |
| 1511 | if not isinstance(value, list): |
| 1512 | raise ValueError(f"{where} must be a list of objects") |
| 1513 | |
| 1514 | by_name = {field["name"]: field for field in fields} |
| 1515 | normalized: list[dict[str, Any]] = [] |
| 1516 | for entry in value: |
| 1517 | if not isinstance(entry, Mapping): |
| 1518 | raise ValueError( |
| 1519 | f'{where} must be an object like {{"fields": ["a"], "scope": ["b"]}}, ' |
| 1520 | f"got {entry!r}" |
| 1521 | ) |
| 1522 | unknown = sorted(str(key) for key in entry if key not in _UNIQUE_KEYS) |
| 1523 | if unknown: |
| 1524 | raise ValueError(f"{where} has unknown keys: {', '.join(unknown)}") |
| 1525 | |
| 1526 | names: dict[str, list[str]] = {} |
| 1527 | for key in ("fields", "scope"): |
| 1528 | listed = entry.get(key, []) |
| 1529 | if not isinstance(listed, list) or not all( |
| 1530 | isinstance(name, str) and _FIELD_NAME_RE.fullmatch(name) for name in listed |
| 1531 | ): |
| 1532 | raise ValueError(f"{where}: '{key}' must be a list of field names") |
| 1533 | names[key] = list(listed) |
| 1534 | if not names["fields"]: |
| 1535 | raise ValueError(f"{where}: 'fields' must name at least one field") |
| 1536 | |
| 1537 | every = names["fields"] + names["scope"] |
| 1538 | if len(set(every)) != len(every): |
| 1539 | raise ValueError(f"{where} names a field more than once: {', '.join(every)}") |
| 1540 | for name in every: |
| 1541 | if name == "id": |
| 1542 | raise ValueError(f"{where}: 'id' is already unique") |
| 1543 | declared = by_name.get(name) |
| 1544 | if declared is None: |
| 1545 | continue |
| 1546 | if str(declared.get("type") or "").lower() == "computed" or declared.get("computed"): |
| 1547 | raise ValueError(f"{where}: '{name}' is computed and cannot be constrained") |
| 1548 | if declared.get("store") == "extra": |
| 1549 | raise ValueError( |
| 1550 | f"{where}: '{name}' is stored in extra and cannot be constrained" |
| 1551 | ) |
| 1552 | |
| 1553 | ignore_case = entry.get("ignore_case", False) |
| 1554 | if not isinstance(ignore_case, bool): |
| 1555 | raise ValueError(f"{where}: 'ignore_case' must be true or false") |
| 1556 | constraint: dict[str, Any] = { |
| 1557 | "fields": names["fields"], |
| 1558 | "scope": names["scope"], |
| 1559 | "ignore_case": ignore_case, |
| 1560 | } |
| 1561 | if entry.get("message") is not None: |
| 1562 | message = entry["message"] |
| 1563 | if not isinstance(message, str) or not message.strip(): |
| 1564 | raise ValueError(f"{where}: 'message' must be a non-empty string") |
| 1565 | constraint["message"] = message.strip() |
| 1566 | normalized.append(constraint) |
| 1567 | return normalized |
| 1568 | |
| 1569 | |
| 1570 | _LOCKED_WHEN_KEYS = frozenset({"when", "except", "fields", "allow_delete", "message"}) |
| 1571 | |
| 1572 | |
| 1573 | def _normalize_locked_when( |
| 1574 | value: Any, *, schema: str, declared: Iterable[str] | None = None |
| 1575 | ) -> list[dict[str, Any]]: |
| 1576 | """Validate a root-level ``locked_when`` declaration; return its canonical form. |
| 1577 | |
| 1578 | "locked_when": [ |
| 1579 | {"when": {"status": ["approved", "billed"]}, |
| 1580 | "except": ["status", "invoice_id", "notes"]} |
| 1581 | ] |
| 1582 | |
| 1583 | Each rule says: while the stored record has ``when`` (every named field |
| 1584 | holding one of its listed values), an update may change only the |
| 1585 | ``except`` fields, and the record cannot be deleted unless |
| 1586 | ``allow_delete`` is true. Enforced by object_records inside the write |
| 1587 | lock -- see object_records._check_record_locks. |
| 1588 | |
| 1589 | This is docs/logic-decisions.md #5's "working name `locked_when`", |
| 1590 | promoted from the per-module hooks once three of them carried the same |
| 1591 | allow-list, and its three open questions answered by what those hooks |
| 1592 | actually do: it locks per RECORD with an allow-list of fields (not a |
| 1593 | list of locked fields -- a new field added to the schema is frozen by |
| 1594 | default, which is the safe direction); nobody bypasses it; and it |
| 1595 | composes with `transitions` by leaving `status` to them (put the state |
| 1596 | field in ``except`` and the transitions map decides which moves out of |
| 1597 | the state are legal -- leave it out and the state is terminal). |
| 1598 | |
| 1599 | Validated strictly, like `unique`: this is a gate, so a rule that |
| 1600 | cannot be read is an error, never "no rule". In particular ``when`` |
| 1601 | must name at least one field -- an always-true rule is not a state, |
| 1602 | and `{"when": {}}` is what a mistyped rule looks like. |
| 1603 | |
| 1604 | The opposite form freezes only some fields: ``"fields": ["title", |
| 1605 | "description"]`` means an update to a settled record may change anything |
| 1606 | EXCEPT those. A rule names ``except`` (an allow-list: everything else is |
| 1607 | frozen, new fields included) or ``fields`` (a deny-list: only these are |
| 1608 | frozen, new fields stay editable), never both. ``fields`` must be a |
| 1609 | non-empty list of declared fields (``declared``, when the caller knows |
| 1610 | them): a misspelt name there would leave the field editable, the |
| 1611 | dangerous direction, so it is refused rather than ignored. |
| 1612 | |
| 1613 | Canonical form: ``when`` values are always lists; ``allow_delete`` is |
| 1614 | always present; a rule carries ``except`` (always, default ``[]``) or, |
| 1615 | when it was written with ``fields``, ``fields`` and no ``except``. |
| 1616 | """ |
| 1617 | where = f"Schema locked_when rule in {schema}" |
| 1618 | declared_names = None if declared is None else set(declared) |
| 1619 | if not isinstance(value, list): |
| 1620 | raise ValueError(f"{where} must be a list of objects") |
| 1621 | |
| 1622 | normalized: list[dict[str, Any]] = [] |
| 1623 | for entry in value: |
| 1624 | if not isinstance(entry, Mapping): |
| 1625 | raise ValueError( |
| 1626 | f'{where} must be an object like {{"when": {{"status": "posted"}}}}, got {entry!r}' |
| 1627 | ) |
| 1628 | unknown = sorted(str(key) for key in entry if key not in _LOCKED_WHEN_KEYS) |
| 1629 | if unknown: |
| 1630 | raise ValueError(f"{where} has unknown keys: {', '.join(unknown)}") |
| 1631 | |
| 1632 | when_payload = entry.get("when") |
| 1633 | if not isinstance(when_payload, Mapping) or not when_payload: |
| 1634 | raise ValueError(f"{where}: 'when' must name at least one field and its value(s)") |
| 1635 | when: dict[str, list[str]] = {} |
| 1636 | for name, wanted in when_payload.items(): |
| 1637 | if not isinstance(name, str) or not _FIELD_NAME_RE.fullmatch(name): |
| 1638 | raise ValueError(f"{where}: 'when' has an invalid field name: {name!r}") |
| 1639 | values = [wanted] if isinstance(wanted, str) else wanted |
| 1640 | if ( |
| 1641 | not isinstance(values, list) |
| 1642 | or not values |
| 1643 | or not all(isinstance(item, str) for item in values) |
| 1644 | ): |
| 1645 | raise ValueError( |
| 1646 | f"{where}: 'when.{name}' must be a string or a non-empty list of strings" |
| 1647 | ) |
| 1648 | when[name] = list(values) |
| 1649 | |
| 1650 | if "fields" in entry and "except" in entry: |
| 1651 | raise ValueError( |
| 1652 | f"{where}: use 'except' (freeze everything but these) or 'fields' " |
| 1653 | "(freeze only these), not both" |
| 1654 | ) |
| 1655 | allow_delete = entry.get("allow_delete", False) |
| 1656 | if not isinstance(allow_delete, bool): |
| 1657 | raise ValueError(f"{where}: 'allow_delete' must be true or false") |
| 1658 | |
| 1659 | if "fields" in entry: |
| 1660 | frozen = entry["fields"] |
| 1661 | if ( |
| 1662 | not isinstance(frozen, list) |
| 1663 | or not frozen |
| 1664 | or not all( |
| 1665 | isinstance(name, str) and _FIELD_NAME_RE.fullmatch(name) for name in frozen |
| 1666 | ) |
| 1667 | ): |
| 1668 | raise ValueError(f"{where}: 'fields' must be a non-empty list of field names") |
| 1669 | if "id" in frozen: |
| 1670 | raise ValueError(f"{where}: 'fields' cannot name 'id'") |
| 1671 | if declared_names is not None: |
| 1672 | unknown = sorted({name for name in frozen if name not in declared_names}) |
| 1673 | if unknown: |
| 1674 | raise ValueError( |
| 1675 | f"{where}: 'fields' names {', '.join(unknown)}, " |
| 1676 | f"which is not a field of {schema}" |
| 1677 | ) |
| 1678 | rule: dict[str, Any] = { |
| 1679 | "when": when, |
| 1680 | "fields": list(dict.fromkeys(frozen)), |
| 1681 | "allow_delete": allow_delete, |
| 1682 | } |
| 1683 | else: |
| 1684 | allowed = entry.get("except", []) |
| 1685 | if not isinstance(allowed, list) or not all( |
| 1686 | isinstance(name, str) and _FIELD_NAME_RE.fullmatch(name) for name in allowed |
| 1687 | ): |
| 1688 | raise ValueError(f"{where}: 'except' must be a list of field names") |
| 1689 | rule = { |
| 1690 | "when": when, |
| 1691 | "except": list(allowed), |
| 1692 | "allow_delete": allow_delete, |
| 1693 | } |
| 1694 | if entry.get("message") is not None: |
| 1695 | message = entry["message"] |
| 1696 | if not isinstance(message, str) or not message.strip(): |
| 1697 | raise ValueError(f"{where}: 'message' must be a non-empty string") |
| 1698 | rule["message"] = message.strip() |
| 1699 | normalized.append(rule) |
| 1700 | return normalized |
| 1701 | |
| 1702 | |
| 1703 | _LOCKED_CHECK_KEYS = frozenset({"name", "object", "function", "reads", "lock", "on"}) |
| 1704 | _LOCKED_CHECK_ON_KEYS = frozenset({"create", "update", "delete"}) |
| 1705 | _LOCKED_CHECK_NAME_RE = re.compile(r"^[A-Za-z0-9_]{1,64}$") |
| 1706 | _LOCK_NAME_RE = re.compile(r"^[a-z0-9_]{1,64}$") |
| 1707 | _FUNCTION_NAME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]{0,63}$") |
| 1708 | # What a check function may NOT be: an object's request verbs and its |
| 1709 | # pre-write hook are code paths that answer callers and may write. A check |
| 1710 | # is its own, read-only function. |
| 1711 | _NOT_A_CHECK_FUNCTION = frozenset({"GET", "POST", "PUT", "PATCH", "DELETE", "COUNT", |
| 1712 | "BEFORE_WRITE"}) |
| 1713 | DEFAULT_CHECK_FUNCTION = "LOCKED_CHECK" |
| 1714 | |
| 1715 | |
| 1716 | def _normalize_locked_checks(value: Any, *, schema: str) -> list[dict[str, Any]]: |
| 1717 | """Validate a root-level ``locked_checks`` declaration; return its canonical form. |
| 1718 | |
| 1719 | "locked_checks": [ |
| 1720 | {"name": "overpayment", |
| 1721 | "object": "hook_payments", |
| 1722 | "function": "LOCKED_CHECK", |
| 1723 | "reads": ["invoices", "invoice_lines", "refunds"], |
| 1724 | "lock": "ledger", |
| 1725 | "on": {"create": true, "update": ["amount_cents", "invoice_id"], "delete": true}} |
| 1726 | ] |
| 1727 | |
| 1728 | Each entry names a read-only function an installed object ships, which |
| 1729 | object_records calls INSIDE the write lock for the writes ``on`` selects |
| 1730 | -- every writer, hooked or not -- with every collection in ``reads`` |
| 1731 | held still by the named ``lock`` (see object_records._run_locked_checks |
| 1732 | and docs/validation-and-logic.md, "Locked checks"). |
| 1733 | |
| 1734 | Validated strictly, like `unique`: an unreadable declaration is an |
| 1735 | error, never "no check". ``reads`` is what decides which OTHER writers |
| 1736 | take the lock, so a misspelled collection there would silently leave a |
| 1737 | ceiling input unlocked; it must be a list of valid collection names. |
| 1738 | |
| 1739 | Canonical form: every key present; ``reads`` sorted without repeats; |
| 1740 | ``lock`` defaults to the declaring collection's name, ``function`` to |
| 1741 | LOCKED_CHECK, ``name`` to the object id; ``on`` keys default to true and |
| 1742 | ``on.update`` is true (any change) or a sorted list of field names. |
| 1743 | """ |
| 1744 | where = f"Schema locked_checks entry in {schema}" |
| 1745 | if not isinstance(value, list): |
| 1746 | raise ValueError(f"{where} must be a list of objects") |
| 1747 | |
| 1748 | normalized: list[dict[str, Any]] = [] |
| 1749 | seen: set[str] = set() |
| 1750 | for entry in value: |
| 1751 | if not isinstance(entry, Mapping): |
| 1752 | raise ValueError(f'{where} must be an object like {{"object": "hook_x", ' |
| 1753 | f'"reads": ["y"]}}, got {entry!r}') |
| 1754 | unknown = sorted(str(key) for key in entry if key not in _LOCKED_CHECK_KEYS) |
| 1755 | if unknown: |
| 1756 | raise ValueError(f"{where} has unknown keys: {', '.join(unknown)}") |
| 1757 | |
| 1758 | object_id = entry.get("object") |
| 1759 | if not isinstance(object_id, str) or not object_collections.validate_object_id(object_id): |
| 1760 | raise ValueError(f"{where}: 'object' must name an installed object") |
| 1761 | name = entry.get("name", object_id) |
| 1762 | if not isinstance(name, str) or not _LOCKED_CHECK_NAME_RE.fullmatch(name): |
| 1763 | raise ValueError(f"{where}: 'name' must be letters, digits and underscores") |
| 1764 | if name in seen: |
| 1765 | raise ValueError(f"{where}: two checks are named {name!r}") |
| 1766 | seen.add(name) |
| 1767 | |
| 1768 | function = entry.get("function", DEFAULT_CHECK_FUNCTION) |
| 1769 | if not isinstance(function, str) or not _FUNCTION_NAME_RE.fullmatch(function): |
| 1770 | raise ValueError(f"{where}: 'function' must be a function name") |
| 1771 | if function.upper() in _NOT_A_CHECK_FUNCTION: |
| 1772 | raise ValueError(f"{where}: 'function' may not be {function}; a check is its own " |
| 1773 | "read-only function, not a request handler or a hook") |
| 1774 | |
| 1775 | reads = entry.get("reads", []) |
| 1776 | if not isinstance(reads, list) or not all( |
| 1777 | isinstance(item, str) and object_collections.validate_collection_name(item) |
| 1778 | for item in reads |
| 1779 | ): |
| 1780 | raise ValueError(f"{where}: 'reads' must be a list of collection names") |
| 1781 | |
| 1782 | lock = entry.get("lock", schema) |
| 1783 | if not isinstance(lock, str) or not _LOCK_NAME_RE.fullmatch(lock): |
| 1784 | raise ValueError(f"{where}: 'lock' must be lower-case letters, digits and underscores") |
| 1785 | |
| 1786 | on_payload = entry.get("on", {}) |
| 1787 | if not isinstance(on_payload, Mapping): |
| 1788 | raise ValueError(f"{where}: 'on' must be an object") |
| 1789 | unknown = sorted(str(key) for key in on_payload if key not in _LOCKED_CHECK_ON_KEYS) |
| 1790 | if unknown: |
| 1791 | raise ValueError(f"{where}: 'on' has unknown keys: {', '.join(unknown)}") |
| 1792 | on: dict[str, Any] = {} |
| 1793 | for key in ("create", "delete"): |
| 1794 | flag = on_payload.get(key, True) |
| 1795 | if not isinstance(flag, bool): |
| 1796 | raise ValueError(f"{where}: 'on.{key}' must be true or false") |
| 1797 | on[key] = flag |
| 1798 | update = on_payload.get("update", True) |
| 1799 | if isinstance(update, list): |
| 1800 | if not update or not all( |
| 1801 | isinstance(item, str) and _FIELD_NAME_RE.fullmatch(item) for item in update |
| 1802 | ): |
| 1803 | raise ValueError(f"{where}: 'on.update' must be true, false or a non-empty " |
| 1804 | "list of field names") |
| 1805 | update = sorted(set(update)) |
| 1806 | elif not isinstance(update, bool): |
| 1807 | raise ValueError(f"{where}: 'on.update' must be true, false or a list of field names") |
| 1808 | on["update"] = update |
| 1809 | if not (on["create"] or on["delete"] or on["update"]): |
| 1810 | raise ValueError(f"{where}: 'on' selects no write at all") |
| 1811 | |
| 1812 | normalized.append({ |
| 1813 | "name": name, |
| 1814 | "object": object_id, |
| 1815 | "function": function, |
| 1816 | "reads": sorted(set(reads)), |
| 1817 | "lock": lock, |
| 1818 | "on": on, |
| 1819 | }) |
| 1820 | return normalized |
| 1821 | |
| 1822 | |
| 1823 | def _normalize_field(payload: Any, *, schema: str) -> dict[str, Any]: |
| 1824 | if not isinstance(payload, Mapping): |
| 1825 | raise ValueError(f"Schema field must be an object: {schema}") |
| 1826 | |
| 1827 | name = _optional_string(payload.get("name")) |
| 1828 | if name is None or not _FIELD_NAME_RE.fullmatch(name): |
| 1829 | raise ValueError(f"Schema field has invalid name: {schema}") |
| 1830 | if name == "_op": |
| 1831 | # Reserved for the append-only storage engine's internal op column |
| 1832 | # (docs/append-only-storage-design.md) -- never a real schema |
| 1833 | # field, so a schema field literally named "_op" can never collide |
| 1834 | # with it once a collection opts into "storage": "append". |
| 1835 | raise ValueError(f"Schema field name is reserved: {schema}._op") |
| 1836 | |
| 1837 | field: dict[str, Any] = { |
| 1838 | "name": name, |
| 1839 | "type": _optional_string(payload.get("type")) or "text", |
| 1840 | "required": bool(payload.get("required", False)), |
| 1841 | } |
| 1842 | |
| 1843 | metadata_keys = ( |
| 1844 | "label", |
| 1845 | "description", |
| 1846 | "relation", |
| 1847 | "validation", |
| 1848 | "default", |
| 1849 | "enum", |
| 1850 | "computed", |
| 1851 | "read_only", |
| 1852 | "readonly", |
| 1853 | "readOnly", |
| 1854 | "ui", |
| 1855 | "layout", |
| 1856 | "permissions", |
| 1857 | "placeholder", |
| 1858 | "help", |
| 1859 | "store", |
| 1860 | # Conditional field visibility (Stage-6 extraction): a field may |
| 1861 | # declare `visible_when` = {field, equals|in} so the /form renderer |
| 1862 | # shows it only when another field on the record holds a given value |
| 1863 | # (e.g. product asset fields visible only when product_type == |
| 1864 | # "asset"). Must survive normalization or install would strip it and |
| 1865 | # every field would always show. Whitelisted, not interpreted here -- |
| 1866 | # same posture as the root-level `blocks`/`flow`/`views` keys. |
| 1867 | "visible_when", |
| 1868 | # Formula & rollup declarations on `type: computed` fields |
| 1869 | # (plan/formula-rollup-spec.md): `formula` is a tiny expression over |
| 1870 | # sibling fields, `rollup` aggregates a child collection. Interpreted |
| 1871 | # by object_records/_apply_computed_fields at write time; must survive |
| 1872 | # normalization or derived values silently never compute. |
| 1873 | "formula", |
| 1874 | "rollup", |
| 1875 | ) |
| 1876 | for key in metadata_keys: |
| 1877 | if key in payload: |
| 1878 | field[key] = _json_compatible(payload[key], field_name=f"{schema}.{name}.{key}") |
| 1879 | if "transitions" in payload: |
| 1880 | field["transitions"] = _normalize_transitions( |
| 1881 | payload["transitions"], field_name=f"{schema}.{name}.transitions" |
| 1882 | ) |
| 1883 | if isinstance(field.get("validation"), dict): |
| 1884 | field["validation"] = _normalize_validation_declarations( |
| 1885 | field["validation"], field=field, schema=schema |
| 1886 | ) |
| 1887 | relation = field.get("relation") |
| 1888 | if isinstance(relation, dict) and "requires" in relation: |
| 1889 | # What the HTTP writer must be allowed to do to the record the |
| 1890 | # pointer names (object_server._refuse_unreachable_relations). A |
| 1891 | # typo here would check nothing while reading as if it did. |
| 1892 | if relation["requires"] not in RELATION_REQUIRES: |
| 1893 | raise ValueError( |
| 1894 | f"Schema field {schema}.{name}: relation 'requires' must be one of " |
| 1895 | f"{', '.join(sorted(RELATION_REQUIRES))}" |
| 1896 | ) |
| 1897 | if "subject" in payload: |
| 1898 | field["subject"] = _normalize_subject(payload["subject"], field=field, schema=schema) |
| 1899 | |
| 1900 | return field |
| 1901 | |
| 1902 | |
| 1903 | # What a field says about the data subject a privacy export looks for |
| 1904 | # (packages/app-privacy action_export_subject_data; docs/package-authoring.md, |
| 1905 | # "Personal data: the subject export"): "email" -- this field holds the |
| 1906 | # person's email address; "relation" -- this relation points at a record |
| 1907 | # already proven to be theirs, so the row is theirs too. |
| 1908 | SUBJECT_KINDS = frozenset({"email", "relation"}) |
| 1909 | |
| 1910 | |
| 1911 | def _normalize_subject(value: Any, *, field: dict[str, Any], schema: str) -> str: |
| 1912 | """Validate a field's ``subject`` declaration. |
| 1913 | |
| 1914 | Strict, like `relation.requires`: this decides what a subject access |
| 1915 | request returns, so a typo must fail at load rather than quietly leave a |
| 1916 | person's records out of the answer. ``relation`` needs a relation to |
| 1917 | follow (a bare string or ``{"collection": ...}``).""" |
| 1918 | where = f"Schema field {schema}.{field['name']}" |
| 1919 | if value not in SUBJECT_KINDS: |
| 1920 | raise ValueError(f"{where}: 'subject' must be one of {', '.join(sorted(SUBJECT_KINDS))}") |
| 1921 | if value == "relation": |
| 1922 | relation = field.get("relation") |
| 1923 | target = relation if isinstance(relation, str) else ( |
| 1924 | relation.get("collection") if isinstance(relation, dict) else None) |
| 1925 | if not isinstance(target, str) or not target.strip(): |
| 1926 | raise ValueError(f"{where}: 'subject': 'relation' needs a relation to a collection") |
| 1927 | return value |
| 1928 | |
| 1929 | |
| 1930 | # The actions a relation may require of its writer on the target record. |
| 1931 | RELATION_REQUIRES = frozenset({"read", "update"}) |
| 1932 | |
| 1933 | |
| 1934 | _NUMERIC_FIELD_TYPES = frozenset({"int", "integer", "float", "number", "currency"}) |
| 1935 | |
| 1936 | |
| 1937 | def _validation_number(value: Any, *, where: str, key: str) -> Decimal: |
| 1938 | """A bound as an exact Decimal: a JSON number or a numeric string, finite. |
| 1939 | A bool is refused (``True`` would load as the bound 1).""" |
| 1940 | if isinstance(value, bool) or not isinstance(value, (int, float, str)): |
| 1941 | raise ValueError(f"{where}: '{key}' must be a number") |
| 1942 | try: |
| 1943 | number = Decimal(str(value).strip()) |
| 1944 | except InvalidOperation: |
| 1945 | raise ValueError(f"{where}: '{key}' must be a number") from None |
| 1946 | if not number.is_finite(): |
| 1947 | raise ValueError(f"{where}: '{key}' must be a finite number") |
| 1948 | return number |
| 1949 | |
| 1950 | |
| 1951 | def _normalize_validation_declarations( |
| 1952 | validation: dict[str, Any], |
| 1953 | *, |
| 1954 | field: dict[str, Any], |
| 1955 | schema: str, |
| 1956 | ) -> dict[str, Any]: |
| 1957 | """Check the declarations of a field's ``validation`` that are judged at |
| 1958 | load: ``exclusive_min`` / ``exclusive_max`` and ``required_when``. The older |
| 1959 | keys (``min``, ``pattern`` ...) are judged at write time and untouched. |
| 1960 | |
| 1961 | Strict, like `unique` and `locked_when`: these are gates, so a declaration |
| 1962 | that cannot be enforced is an error and never "no rule". |
| 1963 | |
| 1964 | - ``exclusive_min`` / ``exclusive_max`` are numbers, on a numeric field |
| 1965 | (a text field would refuse every write with "must be a number"), and |
| 1966 | together with ``min`` / ``max`` they must leave at least one value. |
| 1967 | - ``required_when`` is ``{field: value | [values]}``, the shape |
| 1968 | `locked_when.when` uses: at least one field, each a string or a |
| 1969 | non-empty list of strings, never the field itself, never a computed or |
| 1970 | read-only field (nobody can supply one). Canonical form: values are |
| 1971 | always lists. That the named fields exist is checked once the whole |
| 1972 | field list is known (`_check_required_when_fields`). |
| 1973 | """ |
| 1974 | name = field["name"] |
| 1975 | where = f"Schema field {schema}.{name} validation" |
| 1976 | result = dict(validation) |
| 1977 | |
| 1978 | bounds: dict[str, Decimal] = {} |
| 1979 | for key in ("min", "max", "exclusive_min", "exclusive_max"): |
| 1980 | if key not in validation: |
| 1981 | continue |
| 1982 | if key.startswith("exclusive_"): |
| 1983 | if str(field.get("type") or "text").lower() not in _NUMERIC_FIELD_TYPES: |
| 1984 | raise ValueError( |
| 1985 | f"{where}: '{key}' needs a numeric field (integer, number or currency)" |
| 1986 | ) |
| 1987 | bounds[key] = _validation_number(validation[key], where=where, key=key) |
| 1988 | else: |
| 1989 | try: |
| 1990 | number = Decimal(str(validation[key]).strip()) |
| 1991 | except InvalidOperation: |
| 1992 | continue # judged (and refused) at write time, as before |
| 1993 | if number.is_finite(): |
| 1994 | bounds[key] = number |
| 1995 | if any(key.startswith("exclusive_") for key in bounds): |
| 1996 | lows = [(v, key.startswith("exclusive_")) for key, v in bounds.items() if "min" in key] |
| 1997 | highs = [(v, key.startswith("exclusive_")) for key, v in bounds.items() if "max" in key] |
| 1998 | for low, low_open in lows: |
| 1999 | for high, high_open in highs: |
| 2000 | if low > high or (low == high and (low_open or high_open)): |
| 2001 | raise ValueError(f"{where}: the bounds leave no value that is allowed") |
| 2002 | |
| 2003 | if "required_when" in validation: |
| 2004 | when = validation["required_when"] |
| 2005 | if not isinstance(when, Mapping) or not when: |
| 2006 | raise ValueError( |
| 2007 | f'{where}: \'required_when\' must be like {{"status": ["matched"]}} ' |
| 2008 | "and name at least one field" |
| 2009 | ) |
| 2010 | if field.get("type") == "computed" or field.get("computed") or any( |
| 2011 | field.get(key) for key in ("read_only", "readonly", "readOnly") |
| 2012 | ): |
| 2013 | raise ValueError( |
| 2014 | f"{where}: 'required_when' on a computed or read-only field " |
| 2015 | "can never be satisfied" |
| 2016 | ) |
| 2017 | canonical: dict[str, list[str]] = {} |
| 2018 | for other, wanted in when.items(): |
| 2019 | if not isinstance(other, str) or not _FIELD_NAME_RE.fullmatch(other): |
| 2020 | raise ValueError(f"{where}: 'required_when' has an invalid field name: {other!r}") |
| 2021 | if other == name: |
| 2022 | raise ValueError(f"{where}: 'required_when' cannot depend on the field itself") |
| 2023 | values = [wanted] if isinstance(wanted, str) else wanted |
| 2024 | if ( |
| 2025 | not isinstance(values, list) |
| 2026 | or not values |
| 2027 | or not all(isinstance(item, str) for item in values) |
| 2028 | ): |
| 2029 | raise ValueError( |
| 2030 | f"{where}: 'required_when.{other}' must be a string or a " |
| 2031 | "non-empty list of strings" |
| 2032 | ) |
| 2033 | canonical[other] = list(values) |
| 2034 | result["required_when"] = canonical |
| 2035 | return result |
| 2036 | |
| 2037 | |
| 2038 | def _check_required_when_fields(fields: list[dict[str, Any]], *, schema: str) -> None: |
| 2039 | """A ``required_when`` that names a field the schema does not declare would |
| 2040 | load as a rule that never applies (a typo is the usual cause).""" |
| 2041 | declared = {field["name"] for field in fields} |
| 2042 | for field in fields: |
| 2043 | validation = field.get("validation") |
| 2044 | if not isinstance(validation, dict) or "required_when" not in validation: |
| 2045 | continue |
| 2046 | for other in validation["required_when"]: |
| 2047 | if other not in declared: |
| 2048 | raise ValueError( |
| 2049 | f"Schema field {schema}.{field['name']} validation: " |
| 2050 | f"'required_when' names '{other}', which is not a field of {schema}" |
| 2051 | ) |
| 2052 | |
| 2053 | |
| 2054 | def _normalize_transitions(value: Any, *, field_name: str) -> dict[str, list[Any]]: |
| 2055 | """Normalize a field's ``transitions`` map, validating the new guarded shape. |
| 2056 | |
| 2057 | Each current-value key maps to a list where an entry is either a plain |
| 2058 | string (allowed for any caller who may update the record) or an object |
| 2059 | ``{"to": "<value>", "when": {<field>: <$var or literal>, ...}}`` whose |
| 2060 | move is only allowed once a subject is available and every ``when`` |
| 2061 | clause matches (see object_records._validate_field_transitions). This |
| 2062 | only validates shape; the closed set of $-variables is resolved later, |
| 2063 | against the record and subject, by object_permissions. |
| 2064 | """ |
| 2065 | if not isinstance(value, Mapping): |
| 2066 | raise ValueError(f"Schema field '{field_name}' must be an object") |
| 2067 | |
| 2068 | normalized: dict[str, list[Any]] = {} |
| 2069 | for from_value, entries in value.items(): |
| 2070 | if not isinstance(from_value, str): |
| 2071 | raise ValueError(f"Schema field '{field_name}' keys must be strings") |
| 2072 | if not isinstance(entries, list): |
| 2073 | raise ValueError(f"Schema field '{field_name}[{from_value!r}]' must be a list") |
| 2074 | |
| 2075 | normalized_entries: list[Any] = [] |
| 2076 | for entry in entries: |
| 2077 | if isinstance(entry, str): |
| 2078 | normalized_entries.append(entry) |
| 2079 | continue |
| 2080 | if isinstance(entry, Mapping): |
| 2081 | to_value = entry.get("to") |
| 2082 | if not isinstance(to_value, str) or not to_value: |
| 2083 | raise ValueError( |
| 2084 | f"Schema field '{field_name}[{from_value!r}]' entry is missing a " |
| 2085 | "string 'to' value" |
| 2086 | ) |
| 2087 | normalized_entry: dict[str, Any] = {"to": to_value} |
| 2088 | if "when" in entry: |
| 2089 | when = entry["when"] |
| 2090 | if not isinstance(when, Mapping) or not when: |
| 2091 | raise ValueError( |
| 2092 | f"Schema field '{field_name}[{from_value!r}]' 'when' must be a " |
| 2093 | "non-empty object" |
| 2094 | ) |
| 2095 | normalized_when: dict[str, str] = {} |
| 2096 | for when_key, when_value in when.items(): |
| 2097 | if not isinstance(when_key, str) or not when_key: |
| 2098 | raise ValueError( |
| 2099 | f"Schema field '{field_name}[{from_value!r}]' 'when' keys " |
| 2100 | "must be non-empty strings" |
| 2101 | ) |
| 2102 | if not isinstance(when_value, str) or not when_value: |
| 2103 | raise ValueError( |
| 2104 | f"Schema field '{field_name}[{from_value!r}]' 'when' values " |
| 2105 | "must be non-empty strings" |
| 2106 | ) |
| 2107 | normalized_when[when_key] = when_value |
| 2108 | normalized_entry["when"] = normalized_when |
| 2109 | extra_keys = sorted(set(entry.keys()) - {"to", "when"}) |
| 2110 | if extra_keys: |
| 2111 | raise ValueError( |
| 2112 | f"Schema field '{field_name}[{from_value!r}]' has unexpected keys: " |
| 2113 | f"{extra_keys}" |
| 2114 | ) |
| 2115 | normalized_entries.append(normalized_entry) |
| 2116 | continue |
| 2117 | raise ValueError( |
| 2118 | f"Schema field '{field_name}[{from_value!r}]' entries must be strings or objects" |
| 2119 | ) |
| 2120 | normalized[from_value] = normalized_entries |
| 2121 | |
| 2122 | return normalized |
| 2123 | |
| 2124 | |
| 2125 | def _schema_root(base_dir: Path) -> Path: |
| 2126 | return base_dir / SCHEMAS_DIR |
| 2127 | |
| 2128 | |
| 2129 | def _schema_path(schema: str, base_dir: Path) -> Path: |
| 2130 | if not validate_schema_name(schema): |
| 2131 | raise InvalidSchemaNameError(f"Invalid schema name: {schema}") |
| 2132 | |
| 2133 | root = _schema_root(base_dir) |
| 2134 | path = root / f"{schema}.json" |
| 2135 | resolved_root = root.resolve(strict=False) |
| 2136 | resolved_path = path.resolve(strict=False) |
| 2137 | |
| 2138 | try: |
| 2139 | resolved_path.relative_to(resolved_root) |
| 2140 | except ValueError as exc: |
| 2141 | raise InvalidSchemaNameError(f"Schema path escapes schema directory: {schema}") from exc |
| 2142 | |
| 2143 | return path |
| 2144 | |
| 2145 | |
| 2146 | def _title_from_name(name: str) -> str: |
| 2147 | return name.replace("_", " ").title() |
| 2148 | |
| 2149 | |
| 2150 | def _optional_string(value: Any) -> str | None: |
| 2151 | if value is None: |
| 2152 | return None |
| 2153 | if not isinstance(value, str): |
| 2154 | raise ValueError("Schema string fields must be strings") |
| 2155 | text = value.strip() |
| 2156 | return text or None |
| 2157 | |
| 2158 | |
| 2159 | def _optional_int(value: Any) -> int | None: |
| 2160 | if value is None: |
| 2161 | return None |
| 2162 | if isinstance(value, bool): |
| 2163 | raise ValueError("Schema version must be an integer") |
| 2164 | try: |
| 2165 | number = int(value) |
| 2166 | except (TypeError, ValueError) as exc: |
| 2167 | raise ValueError("Schema version must be an integer") from exc |
| 2168 | if number < 1: |
| 2169 | raise ValueError("Schema version must be at least 1") |
| 2170 | return number |
| 2171 | |
| 2172 | |
| 2173 | def _json_compatible(value: Any, *, field_name: str) -> Any: |
| 2174 | if value is None or isinstance(value, (str, int, float, bool)): |
| 2175 | return value |
| 2176 | if isinstance(value, list): |
| 2177 | return [_json_compatible(item, field_name=field_name) for item in value] |
| 2178 | if isinstance(value, Mapping): |
| 2179 | normalized = {} |
| 2180 | for key, item in value.items(): |
| 2181 | if not isinstance(key, str): |
| 2182 | raise ValueError(f"Schema field '{field_name}' contains a non-string key") |
| 2183 | normalized[key] = _json_compatible(item, field_name=field_name) |
| 2184 | return normalized |
| 2185 | raise ValueError(f"Schema field '{field_name}' is not JSON-compatible") |