okami.mom/strata

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

Niko1221rc1 merge cfg-paths (d0d31a419)71e26e68f

main
16.4 KiB391 linesraw
1"""Versioned, owner-editable serving profiles separate from setup's run config.
2
3The source JSON belongs to setup.py; this small layer keeps operator overrides in
4the user's configuration directory so an installer update cannot silently erase
5them. It deliberately does not start processes or contact a network service.
6"""
7
8from __future__ import annotations
9
10from strata_control.private_files import private_mkdir as _private_mkdir
11import hashlib
12import json
13import math
14import os
15import re
16import shlex
17import stat
18import subprocess
19import tempfile
20from strata_control import atomic as _atomic_mod
21from contextlib import contextmanager
22from pathlib import Path
23
24
25PROFILE_ID = re.compile(r"[a-z][a-z0-9_-]{0,63}\Z")
26OVERRIDE_KEYS = frozenset({"host", "port", "parallel", "batch_groups", "max_queue", "queue_timeout", "offline",
27                           "batch_telemetry"})
28
29
30class ProfileError(ValueError):
31    """A profile is missing, invalid or changed while it was being edited."""
32
33    def __init__(self, message: str, exit_code: int = 2):
34        super().__init__(message)
35        self.exit_code = exit_code
36
37
38def profile_dir() -> Path:
39    explicit = os.environ.get("STRATA_PROFILE_DIR")
40    if explicit:
41        return Path(explicit).expanduser()
42    if os.name == "nt":
43        base = os.environ.get("APPDATA")
44        return (Path(base) if base else Path.home() / "AppData" / "Roaming") / "Strata" / "profiles"
45    return Path(os.environ.get("XDG_CONFIG_HOME", str(Path.home() / ".config"))) / "strata" / "profiles"
46
47
48def _name(name: str) -> str:
49    if not PROFILE_ID.fullmatch(name):
50        raise ProfileError("profile name must start with a lowercase letter and use only a-z, 0-9, _ or -")
51    return name
52
53
54def _path(name: str) -> Path:
55    return profile_dir() / f"{_name(name)}.json"
56
57
58def _bytes(profile: dict) -> bytes:
59    return (json.dumps(profile, indent=2, ensure_ascii=False, sort_keys=True) + "\n").encode("utf-8")
60
61
62def _revision(data: bytes) -> str:
63    return hashlib.sha256(data).hexdigest()[:16]
64
65
66def parse_assignment(text: str) -> tuple[str, object]:
67    key, sep, raw = text.partition("=")
68    if not sep or key not in OVERRIDE_KEYS:
69        raise ProfileError(f"expected one of {', '.join(sorted(OVERRIDE_KEYS))} as KEY=VALUE")
70    if key in ("port", "parallel", "max_queue"):
71        try:
72            value: object = int(raw)
73        except ValueError:
74            raise ProfileError(f"{key} must be a whole number") from None
75    elif key == "queue_timeout":
76        try:
77            value = float(raw)
78        except ValueError:
79            raise ProfileError("queue_timeout must be a number of seconds") from None
80    elif key == "batch_groups":
81        if raw == "auto":
82            value = raw
83        else:
84            try:
85                value = int(raw)
86            except ValueError:
87                raise ProfileError("batch_groups must be auto or a positive whole number") from None
88    elif key in ("offline", "batch_telemetry"):
89        if raw not in ("true", "false"):
90            raise ProfileError(f"{key} must be true or false")
91        value = raw == "true"
92    else:
93        value = raw
94    validate_overrides({key: value})
95    return key, value
96
97
98def validate_overrides(overrides: object) -> dict:
99    if not isinstance(overrides, dict) or set(overrides) - OVERRIDE_KEYS:
100        raise ProfileError("overrides must contain only supported serving settings")
101    for key, value in overrides.items():
102        if key == "host" and (not isinstance(value, str) or not value or any(c.isspace() for c in value)):
103            raise ProfileError("host must be a nonempty address without whitespace")
104        if key == "port" and (type(value) is not int or not 0 <= value <= 65535):
105            raise ProfileError("port must be in 0..65535")
106        if key == "parallel" and (type(value) is not int or not 1 <= value <= 1024):
107            raise ProfileError("parallel must be in 1..1024")
108        if key == "max_queue" and (type(value) is not int or not 0 <= value <= 4096):
109            raise ProfileError("max_queue must be in 0..4096")
110        if key == "queue_timeout" and (type(value) not in (int, float) or not math.isfinite(value)
111                                        or not 0.1 <= value <= 600):
112            raise ProfileError("queue_timeout must be finite seconds in 0.1..600")
113        if key == "batch_groups" and value != "auto" and (type(value) is not int or not 1 <= value <= 1024):
114            raise ProfileError("batch_groups must be auto or in 1..1024")
115        if key in ("offline", "batch_telemetry") and type(value) is not bool:
116            raise ProfileError(f"{key} must be true or false")
117    return overrides
118
119
120def validate_profile(value: object, *, expected_name: str | None = None) -> dict:
121    if not isinstance(value, dict) or set(value) != {"schema_version", "id", "source_config", "overrides"}:
122        raise ProfileError("profile needs schema_version, id, source_config and overrides")
123    if type(value["schema_version"]) is not int or value["schema_version"] != 1:
124        raise ProfileError("unsupported profile schema version")
125    name = _name(value["id"] if isinstance(value["id"], str) else "")
126    if expected_name is not None and name != expected_name:
127        raise ProfileError("profile ID does not match its filename")
128    source = value["source_config"]
129    if not isinstance(source, str) or not Path(source).is_absolute():
130        raise ProfileError("source_config must be an absolute path")
131    validate_overrides(value["overrides"])
132    return value
133
134
135def read_run_config(path: Path) -> dict:
136    try:
137        cfg = json.loads(path.read_text(encoding="utf-8-sig"))
138    except (OSError, ValueError) as exc:
139        raise ProfileError(f"cannot read run config ({type(exc).__name__})", 5) from None
140    if isinstance(cfg, dict):                                # paths into a version folder of Strata's own that an update removed: the current one
141        from strata_control import cfg_paths
142        cfg = cfg_paths.resolve_config(cfg)[0]
143    if not isinstance(cfg, dict) or not isinstance(cfg.get("args"), list) or not all(
144        isinstance(arg, str) for arg in cfg["args"]
145    ):
146        raise ProfileError("run config needs an args array of strings")
147    for key in ("exe", "tokenizer"):
148        if not isinstance(cfg.get(key), str) or not cfg[key]:
149            raise ProfileError(f"run config needs a nonempty {key} path")
150    return cfg
151
152
153def load(name: str) -> tuple[dict, str]:
154    path = _path(name)
155    try:
156        if not stat.S_ISREG(path.lstat().st_mode):
157            raise ProfileError("profile must be a regular file", 5)
158        from strata_control import private_files
159        data = private_files.read_bytes_repairing(path)      # a profile an elevated run locked is repaired once, in place
160        if len(data) > 1024 * 1024:
161            raise ProfileError("profile is larger than 1 MiB", 5)
162        value = json.loads(data.decode("utf-8-sig"))
163    except FileNotFoundError:
164        raise ProfileError(f"profile {name!r} is not saved; use strata profile create", 5) from None
165    except (OSError, ValueError, UnicodeError) as exc:
166        if isinstance(exc, ProfileError):
167            raise
168        raise ProfileError(f"cannot read profile ({type(exc).__name__})", 5) from None
169    return validate_profile(value, expected_name=name), _revision(data)
170
171
172def list_profiles() -> list[dict]:
173    directory = profile_dir()
174    if not directory.exists():
175        return []
176    result = []
177    for path in sorted(directory.glob("*.json")):
178        if not PROFILE_ID.fullmatch(path.stem):
179            continue
180        try:
181            profile, revision = load(path.stem)
182            result.append({"id": path.stem, "revision": revision, "source_config": profile["source_config"]})
183        except ProfileError as exc:
184            result.append({"id": path.stem, "error": str(exc)})
185    return result
186
187
188@contextmanager
189def _lock(name: str):
190    directory = profile_dir()
191    _private_mkdir(directory, parents=True, exist_ok=True)
192    lock = directory / f".{_name(name)}.lock"
193    with open(lock, "a+b") as stream:
194        if os.name == "nt":
195            import msvcrt
196            stream.seek(0)
197            if not stream.read(1):
198                stream.write(b"0")
199                stream.flush()
200            stream.seek(0)
201            msvcrt.locking(stream.fileno(), msvcrt.LK_LOCK, 1)
202            try:
203                yield
204            finally:
205                stream.seek(0)
206                msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1)
207        else:
208            import fcntl
209            fcntl.flock(stream.fileno(), fcntl.LOCK_EX)
210            try:
211                yield
212            finally:
213                fcntl.flock(stream.fileno(), fcntl.LOCK_UN)
214
215
216def _atomic(path: Path, data: bytes) -> None:
217    fd, temp_name = tempfile.mkstemp(prefix=f".{path.stem}-", suffix=".tmp", dir=path.parent)
218    try:
219        with os.fdopen(fd, "wb") as stream:
220            stream.write(data)
221            stream.flush()
222            os.fsync(stream.fileno())
223        _atomic_mod.replace(temp_name, path)
224        if os.name != "nt":
225            try:
226                parent_fd = os.open(path.parent, os.O_RDONLY)
227                try:
228                    os.fsync(parent_fd)
229                finally:
230                    os.close(parent_fd)
231            except OSError:
232                # Replacement already succeeded; do not report a failed save after it changed the profile.
233                pass
234    finally:
235        if os.path.exists(temp_name):
236            os.unlink(temp_name)
237
238
239def create(name: str, source_config: str) -> tuple[dict, str]:
240    name = _name(name)
241    try:
242        source = Path(source_config).expanduser().resolve(strict=True)
243    except OSError as exc:
244        raise ProfileError(f"run config is unavailable ({type(exc).__name__})", 5) from None
245    read_run_config(source)
246    profile = {"schema_version": 1, "id": name, "source_config": str(source), "overrides": {}}
247    with _lock(name):
248        path = _path(name)
249        if path.exists() or path.is_symlink():
250            raise ProfileError(f"profile {name!r} already exists")
251        _atomic(path, _bytes(profile))
252    return load(name)
253
254
255def propose_source(name: str, source_config: str) -> tuple[dict, str]:
256    """Select another installed run config without changing its contents."""
257    current, revision = load(name)
258    try:
259        source = Path(source_config).expanduser().resolve(strict=True)
260    except OSError as exc:
261        raise ProfileError(f"run config is unavailable ({type(exc).__name__})", 5) from None
262    if not stat.S_ISREG(source.lstat().st_mode):
263        raise ProfileError("run config must be a regular file", 5)
264    read_run_config(source)
265    proposed = {**current, "source_config": str(source)}
266    return validate_profile(proposed, expected_name=name), revision
267
268
269def save(name: str, proposed: dict, *, expected_revision: str,
270         expected_source_sha256: str | None = None) -> tuple[dict, str]:
271    name = _name(name)
272    validate_profile(proposed, expected_name=name)
273    read_run_config(Path(proposed["source_config"]))
274    with _lock(name):
275        current, revision = load(name)
276        if revision != expected_revision:
277            raise ProfileError("profile changed during edit; reload it before saving", 6)
278        if expected_source_sha256 is not None:
279            if not re.fullmatch(r"[0-9a-f]{64}", expected_source_sha256):
280                raise ProfileError("source digest must be a lowercase SHA-256")
281            try:
282                source = Path(proposed["source_config"]).read_bytes()
283            except OSError:
284                raise ProfileError("run config changed after review; retry", 6) from None
285            if len(source) > 1024 * 1024 or hashlib.sha256(source).hexdigest() != expected_source_sha256:
286                raise ProfileError("run config changed after review; retry", 6)
287        if current == proposed:
288            return current, revision
289        history = profile_dir() / ".history" / name
290        _private_mkdir(history, parents=True, exist_ok=True)
291        old = _path(name).read_bytes()
292        if _revision(old) != revision:
293            raise ProfileError("profile changed during edit; reload it before saving", 6)
294        old_path = history / f"{revision}.json"
295        if not old_path.exists():
296            _atomic(old_path, old)
297        _atomic(_path(name), _bytes(proposed))
298    return load(name)
299
300
301def set_values(name: str, assignments: list[str]) -> tuple[dict, str, str]:
302    proposed, revision = propose_values(name, assignments)
303    saved, new_revision = save(name, proposed, expected_revision=revision)
304    return saved, revision, new_revision
305
306
307def propose_values(name: str, assignments: list[str]) -> tuple[dict, str]:
308    current, revision = load(name)
309    changed = {key: value for key, value in (parse_assignment(item) for item in assignments)}
310    proposed = {**current, "overrides": {**current["overrides"], **changed}}
311    validate_profile(proposed, expected_name=name)
312    return proposed, revision
313
314
315def history(name: str) -> list[dict]:
316    _name(name)
317    directory = profile_dir() / ".history" / name
318    entries = []
319    if directory.exists():
320        for path in directory.glob("*.json"):
321            if re.fullmatch(r"[0-9a-f]{16}", path.stem) and path.is_file() and not path.is_symlink():
322                entries.append({"revision": path.stem, "saved_at": path.stat().st_mtime})
323    _, current = load(name)
324    return [{"revision": current, "current": True},
325            *sorted((item for item in entries if item["revision"] != current),
326                    key=lambda item: item["saved_at"], reverse=True)]
327
328
329def rollback(name: str, target_revision: str) -> tuple[dict, str, str]:
330    _name(name)
331    if not re.fullmatch(r"[0-9a-f]{16}", target_revision):
332        raise ProfileError("rollback target must be a full 16-character revision")
333    _, current_revision = load(name)
334    path = profile_dir() / ".history" / name / f"{target_revision}.json"
335    try:
336        if not stat.S_ISREG(path.lstat().st_mode):
337            raise ProfileError("profile history must be a regular file", 5)
338        data = path.read_bytes()
339        if _revision(data) != target_revision:
340            raise ProfileError("profile history content does not match its revision", 5)
341        target = validate_profile(json.loads(data.decode("utf-8")), expected_name=name)
342    except FileNotFoundError:
343        raise ProfileError(f"profile revision {target_revision} was not found", 5) from None
344    except (OSError, UnicodeError, ValueError) as exc:
345        if isinstance(exc, ProfileError):
346            raise
347        raise ProfileError(f"cannot read profile history ({type(exc).__name__})", 5) from None
348    saved, new_revision = save(name, target, expected_revision=current_revision)
349    return saved, current_revision, new_revision
350
351
352def edit(name: str) -> tuple[dict, str, str]:
353    current, revision = load(name)
354    editor = os.environ.get("VISUAL") or os.environ.get("EDITOR")
355    if not editor:
356        raise ProfileError("set VISUAL or EDITOR, or use strata profile set")
357    command = shlex.split(editor, posix=os.name != "nt")
358    if not command:
359        raise ProfileError("VISUAL or EDITOR is empty")
360    fd, temp_name = tempfile.mkstemp(prefix=f".{name}-edit-", suffix=".json", dir=profile_dir())
361    keep_draft = False
362    try:
363        with os.fdopen(fd, "wb") as stream:
364            stream.write(_bytes(current))
365        result = subprocess.run([*command, temp_name], check=False)
366        if result.returncode:
367            keep_draft = True
368            raise ProfileError(f"editor exited with status {result.returncode}; draft kept at {temp_name}", 6)
369        try:
370            proposed = json.loads(Path(temp_name).read_text(encoding="utf-8-sig"))
371        except (OSError, ValueError) as exc:
372            keep_draft = True
373            raise ProfileError(f"edited profile is not valid JSON ({type(exc).__name__}); draft kept at {temp_name}") from None
374        try:
375            saved, new_revision = save(name, proposed, expected_revision=revision)
376        except ProfileError as exc:
377            keep_draft = True
378            raise ProfileError(f"{exc}; draft kept at {temp_name}", exc.exit_code) from None
379        return saved, revision, new_revision
380    finally:
381        if not keep_draft:
382            Path(temp_name).unlink(missing_ok=True)
383
384
385def resolve(ref: str) -> tuple[Path, dict | None, str | None]:
386    """A saved name or an explicit JSON path; path-like values never fall back to names."""
387    path = Path(ref).expanduser()
388    if path.suffix.lower() == ".json" or path.is_absolute() or "/" in ref or "\\" in ref:
389        return path.resolve(), None, None
390    profile, revision = load(ref)
391    return Path(profile["source_config"]), profile, revision