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_namespace.py · 17.0 KB · 463 lines
| 1 | """Object source discovery and object ID resolution. |
| 2 | |
| 3 | This module is intentionally small and standalone while the public package |
| 4 | layout is being decided. It is the shared namespace contract for the daemon, |
| 5 | future HTTP server, tests, and companion tools. |
| 6 | """ |
| 7 | from __future__ import annotations |
| 8 | |
| 9 | import os |
| 10 | import re |
| 11 | import threading |
| 12 | import time |
| 13 | from dataclasses import dataclass |
| 14 | from pathlib import Path |
| 15 | from typing import Iterable, Literal |
| 16 | |
| 17 | |
| 18 | DEFAULT_OBJECTS_DIR = "objects" |
| 19 | OBJECTS_DIR_ENV = "DBBASIC_OBJECTS_DIR" |
| 20 | OVERRIDES_DIR_ENV = "DBBASIC_OVERRIDES_DIR" |
| 21 | |
| 22 | _OBJECT_ID_RE = re.compile(r"^[A-Za-z0-9_]{1,64}$") |
| 23 | _USER_OBJECT_RE = re.compile(r"^u_(\d+)_([A-Za-z][A-Za-z0-9_]{0,49})$") |
| 24 | |
| 25 | # iter_object_sources() listings, one per (roots, override root) asked for. |
| 26 | # The value is (tree signature, sources); see _tree_signature for what the |
| 27 | # signature is and why it is enough, and iter_object_sources for when a |
| 28 | # listing is stored at all. |
| 29 | _SOURCES_CACHE: dict[tuple, tuple[tuple, tuple["ObjectSource", ...]]] = {} |
| 30 | _SOURCES_CACHE_LOCK = threading.Lock() |
| 31 | _SOURCES_CACHE_MAX_KEYS = 32 |
| 32 | # A directory changed more recently than this when it was listed is not |
| 33 | # cached: a second change inside the filesystem's timestamp granularity would |
| 34 | # leave the same stat behind. The same margin object_identity's session cache |
| 35 | # uses, comfortably above coarse (4-10 ms) granularities. |
| 36 | _SOURCES_CACHE_RACY_NS = 50_000_000 |
| 37 | |
| 38 | |
| 39 | @dataclass(frozen=True) |
| 40 | class ObjectSource: |
| 41 | """A discovered object source file.""" |
| 42 | |
| 43 | object_id: str |
| 44 | path: Path |
| 45 | relative_path: Path |
| 46 | kind: Literal["system", "user", "override"] |
| 47 | |
| 48 | |
| 49 | def get_base_object_roots() -> list[Path]: |
| 50 | """Return the package/system object roots (never the override root). |
| 51 | |
| 52 | This is the root packages install into and reconcile against. It is |
| 53 | identical to the pre-override-support get_object_roots() body, so |
| 54 | install/baseline/reconcile logic always operates on the pristine, |
| 55 | upgradeable copy regardless of whether overrides are enabled. |
| 56 | """ |
| 57 | configured = os.environ.get(OBJECTS_DIR_ENV) |
| 58 | if configured: |
| 59 | return [Path(configured)] |
| 60 | return [Path(DEFAULT_OBJECTS_DIR)] |
| 61 | |
| 62 | |
| 63 | def get_override_root() -> Path | None: |
| 64 | """Return the override root when DBBASIC_OVERRIDES_DIR is set, else None. |
| 65 | |
| 66 | Overrides are strictly opt-in: when the env var is unset or empty, this |
| 67 | returns None and every override-aware code path behaves exactly as it |
| 68 | did before overrides existed. |
| 69 | """ |
| 70 | configured = os.environ.get(OVERRIDES_DIR_ENV) |
| 71 | if configured: |
| 72 | return Path(configured) |
| 73 | return None |
| 74 | |
| 75 | |
| 76 | def get_object_roots() -> list[Path]: |
| 77 | """Return object source roots in lookup order (override first, then base). |
| 78 | |
| 79 | When DBBASIC_OVERRIDES_DIR is unset this returns exactly |
| 80 | get_base_object_roots() — a single-element list identical to the |
| 81 | pre-override behavior of this function. |
| 82 | """ |
| 83 | override = get_override_root() |
| 84 | return ([override] if override is not None else []) + get_base_object_roots() |
| 85 | |
| 86 | |
| 87 | def validate_object_id(object_id: str) -> bool: |
| 88 | """Return True when an object ID is safe to resolve.""" |
| 89 | if not isinstance(object_id, str): |
| 90 | return False |
| 91 | return bool(_OBJECT_ID_RE.fullmatch(object_id)) |
| 92 | |
| 93 | |
| 94 | def parse_user_object_id(object_id: str) -> tuple[int, str] | None: |
| 95 | """Parse `u_{user_id}_{name}` object IDs.""" |
| 96 | if not validate_object_id(object_id): |
| 97 | return None |
| 98 | |
| 99 | match = _USER_OBJECT_RE.fullmatch(object_id) |
| 100 | if not match: |
| 101 | return None |
| 102 | return int(match.group(1)), match.group(2) |
| 103 | |
| 104 | |
| 105 | def is_user_object_id(object_id: str) -> bool: |
| 106 | """Return True when an object ID belongs to a user namespace.""" |
| 107 | return parse_user_object_id(object_id) is not None |
| 108 | |
| 109 | |
| 110 | def override_relative_path(object_id: str) -> Path | None: |
| 111 | """Return the canonical override-root-relative path for an object ID. |
| 112 | |
| 113 | Mirrors the first candidate form used by _candidate_system_paths. |
| 114 | Overrides only exist for system/package objects; user object IDs (and |
| 115 | any other invalid ID) are not supported and return None. |
| 116 | """ |
| 117 | if not validate_object_id(object_id) or is_user_object_id(object_id): |
| 118 | return None |
| 119 | if "_" in object_id: |
| 120 | category, name = object_id.split("_", 1) |
| 121 | return Path(category) / f"{name}.py" |
| 122 | return Path(f"{object_id}.py") |
| 123 | |
| 124 | |
| 125 | def override_path(object_id: str) -> Path | None: |
| 126 | """Return the absolute override path for an object ID, or None. |
| 127 | |
| 128 | None is returned when overrides are not enabled (no override root |
| 129 | configured) or when the object ID is not a valid override target. |
| 130 | """ |
| 131 | root = get_override_root() |
| 132 | if root is None: |
| 133 | return None |
| 134 | relative = override_relative_path(object_id) |
| 135 | if relative is None: |
| 136 | return None |
| 137 | return root / relative |
| 138 | |
| 139 | |
| 140 | def has_override(object_id: str) -> bool: |
| 141 | """Return True when an override file exists for this object ID.""" |
| 142 | path = override_path(object_id) |
| 143 | return path is not None and path.is_file() |
| 144 | |
| 145 | |
| 146 | def resolve_object_id(object_id: str, roots: Iterable[Path] | None = None) -> Path | None: |
| 147 | """Resolve an object ID to an existing source file.""" |
| 148 | if not validate_object_id(object_id): |
| 149 | return None |
| 150 | |
| 151 | search_roots = list(roots) if roots is not None else get_object_roots() |
| 152 | |
| 153 | parsed_user = parse_user_object_id(object_id) |
| 154 | if parsed_user: |
| 155 | user_id, name = parsed_user |
| 156 | for root in search_roots: |
| 157 | candidate = root / "users" / str(user_id) / f"{name}.py" |
| 158 | if _is_allowed_source_file(candidate, root): |
| 159 | return candidate |
| 160 | return None |
| 161 | |
| 162 | for candidate in _candidate_system_paths(object_id, search_roots): |
| 163 | # _is_allowed_source_file refuses a candidate that is not a file |
| 164 | # before anything else, and still checks it (existence, then |
| 165 | # containment) below. Asking first only skips resolving a missing |
| 166 | # candidate against every root, which most lookups are. |
| 167 | if not candidate.is_file(): |
| 168 | continue |
| 169 | root = _candidate_root(candidate, search_roots) |
| 170 | if root is not None and _is_allowed_source_file(candidate, root): |
| 171 | return candidate |
| 172 | |
| 173 | for source in iter_object_sources(search_roots): |
| 174 | if source.object_id == object_id: |
| 175 | return source.path |
| 176 | |
| 177 | return None |
| 178 | |
| 179 | |
| 180 | def find_trigger_file(trigger_name: str, roots: Iterable[Path] | None = None) -> Path | None: |
| 181 | """Find a known trigger object file under `objects/triggers/`.""" |
| 182 | if not _is_safe_source_stem(trigger_name): |
| 183 | return None |
| 184 | |
| 185 | search_roots = list(roots) if roots is not None else get_object_roots() |
| 186 | for root in search_roots: |
| 187 | candidate = root / "triggers" / f"{trigger_name}.py" |
| 188 | if _is_allowed_source_file(candidate, root): |
| 189 | return candidate |
| 190 | return None |
| 191 | |
| 192 | |
| 193 | def object_id_from_path(path: Path | str, root: Path | str) -> str: |
| 194 | """Return the object ID represented by a source path under a root.""" |
| 195 | source_path = Path(path) |
| 196 | source_root = Path(root) |
| 197 | rel = _relative_to_root(source_path, source_root) |
| 198 | return _object_id_from_relative(rel, source_path) |
| 199 | |
| 200 | |
| 201 | def _object_id_from_relative(rel: Path, source_path: Path) -> str: |
| 202 | """object_id_from_path's mapping, for a path already checked to lie |
| 203 | under its root (`rel` is the resolved path relative to the resolved |
| 204 | root).""" |
| 205 | if not _is_public_source_relative_path(rel): |
| 206 | raise ValueError(f"Not a public object source: {source_path}") |
| 207 | |
| 208 | parts = rel.parts |
| 209 | if parts[0] == "users": |
| 210 | if len(parts) != 3: |
| 211 | raise ValueError(f"Invalid user object source path: {source_path}") |
| 212 | user_id = parts[1] |
| 213 | name = Path(parts[2]).stem |
| 214 | object_id = f"u_{user_id}_{name}" |
| 215 | else: |
| 216 | path_without_suffix = rel.with_suffix("") |
| 217 | object_id = "_".join(path_without_suffix.parts) |
| 218 | |
| 219 | if not validate_object_id(object_id): |
| 220 | raise ValueError(f"Invalid object ID derived from path: {object_id}") |
| 221 | return object_id |
| 222 | |
| 223 | |
| 224 | def iter_object_sources(roots: Iterable[Path] | None = None) -> list[ObjectSource]: |
| 225 | """List object source files from configured roots in deterministic order. |
| 226 | |
| 227 | The listing is a recursive glob of every root (about 16 ms for the 160 |
| 228 | objects of a 57-package install) and it used to run on every call: once |
| 229 | per page for a site route the convention lookup misses, and again for |
| 230 | every collection question a schema-less name raises. It depends only on |
| 231 | which files and directories exist, so it is kept and re-used for as long |
| 232 | as every directory it walked still has the stat it had (_tree_signature). |
| 233 | |
| 234 | Nothing in this process is told about writes: the server may be several |
| 235 | workers, and the daemon, the package installer and an operator's editor |
| 236 | all create and delete object files. Each call re-stats the directories |
| 237 | (one stat each, a few dozen microseconds in all) and lists again when any |
| 238 | of them moved. A listing is NOT stored when it cannot be trusted to show |
| 239 | its own staleness: a directory changed within the last |
| 240 | _SOURCES_CACHE_RACY_NS, or a symlink anywhere in the tree (a link's |
| 241 | target can change without touching any directory walked here). Those |
| 242 | calls simply list every time, as all calls did before. |
| 243 | """ |
| 244 | search_roots = list(roots) if roots is not None else get_object_roots() |
| 245 | override_root = get_override_root() |
| 246 | try: |
| 247 | key = ( |
| 248 | tuple(os.fspath(root) for root in search_roots), |
| 249 | None if override_root is None else os.fspath(override_root), |
| 250 | ) |
| 251 | cached = _SOURCES_CACHE.get(key) |
| 252 | except TypeError: |
| 253 | return _list_object_sources(search_roots, override_root) |
| 254 | if cached is not None and _tree_signature_holds(cached[0]): |
| 255 | return list(cached[1]) |
| 256 | |
| 257 | # Signature first, listing second: a change that lands between the two |
| 258 | # leaves a signature older than the listing, which the next call rejects. |
| 259 | signature = _tree_signature(search_roots, override_root) |
| 260 | listed_at = time.time_ns() |
| 261 | sources = _list_object_sources(search_roots, override_root) |
| 262 | with _SOURCES_CACHE_LOCK: |
| 263 | if signature is not None and _tree_signature_settled(signature, listed_at): |
| 264 | if key not in _SOURCES_CACHE and len(_SOURCES_CACHE) >= _SOURCES_CACHE_MAX_KEYS: |
| 265 | _SOURCES_CACHE.clear() |
| 266 | _SOURCES_CACHE[key] = (signature, tuple(sources)) |
| 267 | else: |
| 268 | _SOURCES_CACHE.pop(key, None) |
| 269 | return sources |
| 270 | |
| 271 | |
| 272 | def _tree_signature(roots: list[Path], override_root: Path | None) -> tuple | None: |
| 273 | """Stat of every directory a listing of `roots` walks, or None when the |
| 274 | tree holds something a stat cannot vouch for. |
| 275 | |
| 276 | One (path, _directory_stat) pair per directory. That is enough to notice |
| 277 | every way the listing can change: |
| 278 | |
| 279 | - a file or directory created, deleted or renamed moves the mtime of the |
| 280 | directory that holds it (a new subdirectory moves its parent's); |
| 281 | - ctime moves with chmod and with utime, so a directory made unreadable, |
| 282 | or one whose mtime a restore (rsync -a, tar) set back, still differs; |
| 283 | - inode and device catch a root replaced, remounted or reached through a |
| 284 | different working directory (roots may be relative paths), and an |
| 285 | override root that starts or stops being one of the roots. |
| 286 | |
| 287 | A symlink is the exception: what it resolves to is decided outside the |
| 288 | directories walked here, so a tree holding any is never cached (None). |
| 289 | The walk follows what the glob follows: real directories, not links. |
| 290 | """ |
| 291 | entries: list[tuple] = [] |
| 292 | if override_root is not None: |
| 293 | text = os.fspath(override_root) |
| 294 | entries.append((text, _directory_stat(text))) |
| 295 | for root in roots: |
| 296 | text = os.fspath(root) |
| 297 | found = _directory_stat(text) |
| 298 | entries.append((text, found)) |
| 299 | if found is None: |
| 300 | continue |
| 301 | pending = [text] |
| 302 | while pending: |
| 303 | directory = pending.pop() |
| 304 | try: |
| 305 | with os.scandir(directory) as scan: |
| 306 | for entry in scan: |
| 307 | if entry.is_symlink(): |
| 308 | return None |
| 309 | if entry.is_dir(follow_symlinks=False): |
| 310 | entries.append((entry.path, _directory_stat(entry.path))) |
| 311 | pending.append(entry.path) |
| 312 | except OSError: |
| 313 | return None |
| 314 | return tuple(entries) |
| 315 | |
| 316 | |
| 317 | def _directory_stat(path: str) -> tuple[int, int, int, int] | None: |
| 318 | """(mtime_ns, ctime_ns, inode, device) of a directory; None when the |
| 319 | path is missing or is not a directory (a listing skips both alike).""" |
| 320 | try: |
| 321 | info = os.stat(path) |
| 322 | except OSError: |
| 323 | return None |
| 324 | if (info.st_mode & 0o170000) != 0o040000: |
| 325 | return None |
| 326 | return (info.st_mtime_ns, info.st_ctime_ns, info.st_ino, info.st_dev) |
| 327 | |
| 328 | |
| 329 | def _tree_signature_holds(signature: tuple) -> bool: |
| 330 | """True when every directory still has exactly the stat recorded.""" |
| 331 | for path, recorded in signature: |
| 332 | if _directory_stat(path) != recorded: |
| 333 | return False |
| 334 | return True |
| 335 | |
| 336 | |
| 337 | def _tree_signature_settled(signature: tuple, listed_at_ns: int) -> bool: |
| 338 | """False when any directory changed too recently for its stat to prove |
| 339 | that nothing changed after it was listed.""" |
| 340 | for _path, recorded in signature: |
| 341 | if recorded is not None and listed_at_ns - max(recorded[0], recorded[1]) < _SOURCES_CACHE_RACY_NS: |
| 342 | return False |
| 343 | return True |
| 344 | |
| 345 | |
| 346 | def _list_object_sources( |
| 347 | search_roots: list[Path], |
| 348 | override_root: Path | None, |
| 349 | ) -> list[ObjectSource]: |
| 350 | sources: list[ObjectSource] = [] |
| 351 | |
| 352 | for root in search_roots: |
| 353 | if not root.exists() or not root.is_dir(): |
| 354 | continue |
| 355 | |
| 356 | is_override_root = override_root is not None and _same_root(root, override_root) |
| 357 | # The root is resolved once for the whole listing; every file is |
| 358 | # still resolved, and checked against it, on its own. This used to |
| 359 | # resolve the root and the file twice each per file (once here, once |
| 360 | # again inside object_id_from_path) for the same answer. |
| 361 | resolved_root = root.resolve(strict=False) |
| 362 | |
| 363 | for path in sorted(root.rglob("*.py"), key=lambda p: p.relative_to(root).as_posix()): |
| 364 | try: |
| 365 | rel = _relative_to_resolved_root(path, resolved_root) |
| 366 | object_id = _object_id_from_relative(rel, path) |
| 367 | except ValueError: |
| 368 | continue |
| 369 | |
| 370 | kind: Literal["system", "user", "override"] |
| 371 | if rel.parts[0] == "users": |
| 372 | kind = "user" |
| 373 | elif is_override_root: |
| 374 | kind = "override" |
| 375 | else: |
| 376 | kind = "system" |
| 377 | sources.append( |
| 378 | ObjectSource( |
| 379 | object_id=object_id, |
| 380 | path=path, |
| 381 | relative_path=rel, |
| 382 | kind=kind, |
| 383 | ) |
| 384 | ) |
| 385 | |
| 386 | return sources |
| 387 | |
| 388 | |
| 389 | def _same_root(a: Path, b: Path) -> bool: |
| 390 | return a.resolve(strict=False) == b.resolve(strict=False) |
| 391 | |
| 392 | |
| 393 | def _candidate_system_paths(object_id: str, roots: Iterable[Path]) -> list[Path]: |
| 394 | candidates: list[Path] = [] |
| 395 | for root in roots: |
| 396 | if "_" in object_id: |
| 397 | category, name = object_id.split("_", 1) |
| 398 | candidates.append(root / category / f"{name}.py") |
| 399 | candidates.append(root / f"{object_id}.py") |
| 400 | return candidates |
| 401 | |
| 402 | |
| 403 | def _candidate_root(candidate: Path, roots: Iterable[Path]) -> Path | None: |
| 404 | for root in roots: |
| 405 | try: |
| 406 | _relative_to_root(candidate, root) |
| 407 | return root |
| 408 | except ValueError: |
| 409 | continue |
| 410 | return None |
| 411 | |
| 412 | |
| 413 | def _relative_to_root(path: Path, root: Path) -> Path: |
| 414 | return _relative_to_resolved_root(path, root.resolve(strict=False)) |
| 415 | |
| 416 | |
| 417 | def _relative_to_resolved_root(path: Path, resolved_root: Path) -> Path: |
| 418 | """`path`, resolved now, relative to an already resolved root; raises |
| 419 | ValueError when it lies outside.""" |
| 420 | resolved_path = path.resolve(strict=False) |
| 421 | |
| 422 | try: |
| 423 | return resolved_path.relative_to(resolved_root) |
| 424 | except ValueError as exc: |
| 425 | raise ValueError(f"Path escapes object root: {path}") from exc |
| 426 | |
| 427 | |
| 428 | def _is_allowed_source_file(path: Path, root: Path) -> bool: |
| 429 | if not path.exists() or not path.is_file(): |
| 430 | return False |
| 431 | try: |
| 432 | rel = _relative_to_root(path, root) |
| 433 | except ValueError: |
| 434 | return False |
| 435 | return _is_public_source_relative_path(rel) |
| 436 | |
| 437 | |
| 438 | def _is_public_source_relative_path(rel: Path) -> bool: |
| 439 | parts = rel.parts |
| 440 | if not parts: |
| 441 | return False |
| 442 | if rel.suffix != ".py": |
| 443 | return False |
| 444 | if rel.name == "__init__.py": |
| 445 | return False |
| 446 | if "__pycache__" in parts: |
| 447 | return False |
| 448 | if any(part.startswith(".") or part.startswith("_") for part in parts): |
| 449 | return False |
| 450 | if any(part in {"", ".", ".."} for part in parts): |
| 451 | return False |
| 452 | |
| 453 | if parts[0] == "users": |
| 454 | if len(parts) != 3: |
| 455 | return False |
| 456 | return parts[1].isdigit() and _is_safe_source_stem(Path(parts[2]).stem) |
| 457 | |
| 458 | return all(_is_safe_source_stem(part if i < len(parts) - 1 else Path(part).stem) |
| 459 | for i, part in enumerate(parts)) |
| 460 | |
| 461 | |
| 462 | def _is_safe_source_stem(stem: str) -> bool: |
| 463 | return bool(re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_]{0,49}", stem)) |