okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221start and serve never acquire: one guard, a typed error, a test that fails on egress2e3085a55

main
2.8 KiB84 linesraw
1"""The line between serving and acquiring.
2
3Starting a model and serving an API never install, download or compile anything. Everything that
4reaches the network or runs pip, git, cmake or a package manager lives behind an explicit command:
5SETUP, UPDATE or `strata install`. This module is that line, in one place:
6
7* `forbidden()` marks a stretch of code (a start, a serve) in which acquiring is not allowed;
8* `require(what, command)` is called by every acquiring primitive (a download, a pip install, a
9  network probe, a compile) and raises `AcquisitionRefused` inside such a stretch;
10* `AcquisitionRefused` is the typed error: it says what is missing and names the explicit command.
11
12The environment variable `STRATA_NO_ACQUIRE=1` forbids acquiring for a whole process. A process
13that serves (`strata serve`, `strata runtime start`, the API server) never imports the installer, so
14for it this is a second line of defence, not the first.
15
16Nothing here imports anything outside the standard library.
17"""
18
19from __future__ import annotations
20
21import contextlib
22import os
23import sys
24import threading
25
26ENV = "STRATA_NO_ACQUIRE"
27
28_lock = threading.Lock()
29_depth = 0
30
31
32class AcquisitionRefused(RuntimeError):
33    """Something would have been downloaded or installed during a start or a serve."""
34
35    code = "acquisition_refused"
36    exit_code = 5
37
38    def __init__(self, what: str, command: str | None = None):
39        self.what = what
40        self.command = command or explicit_commands()
41        super().__init__(
42            f"{what} is missing or out of date. Starting and serving never install or download "
43            f"anything. Run: {self.command}")
44
45
46def explicit_commands() -> str:
47    """The commands that acquire, named for this platform."""
48    if os.name == "nt":
49        return "SETUP.bat (first-time setup), UPDATE.bat (update) or `strata install`"
50    return "./setup.sh (first-time setup), ./update.sh (update) or `strata install`"
51
52
53def is_forbidden() -> bool:
54    return _depth > 0 or os.environ.get(ENV, "").strip().lower() in ("1", "true", "yes", "on")
55
56
57@contextlib.contextmanager
58def forbidden():
59    """No acquisition inside this block. Nests."""
60    global _depth
61    with _lock:
62        _depth += 1
63    try:
64        yield
65    finally:
66        with _lock:
67            _depth -= 1
68
69
70def require(what: str, command: str | None = None) -> None:
71    """Call before acquiring `what`; raises AcquisitionRefused where acquiring is forbidden."""
72    if is_forbidden():
73        raise AcquisitionRefused(what, command)
74
75
76def main_guard(fn, *, fail=None):
77    """Run `fn()`; a refused acquisition becomes `fail(message, hint)` (or an exit-5 message)."""
78    try:
79        return fn()
80    except AcquisitionRefused as exc:
81        if fail is not None:
82            return fail(str(exc), None)
83        print(f"strata: {exc}", file=sys.stderr)
84        return exc.exit_code