config_backend.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. """Where the user config layer lives: the ``ConfigBackend`` seam (config-config design §4.1, D10/D11).
  2. Every read and write of a profile's user ``config.yaml`` goes through the backend returned by
  3. :func:`get_config_backend` (``scripts/check_config_yaml_readers.py`` and
  4. ``scripts/check_config_yaml_writers.py`` reject direct file access elsewhere). The key per call is
  5. the hermes home (profile): one multiplexed process serves N profiles, and every config cache
  6. already keys on the config path, so a backend keeps per-home state.
  7. :class:`FileBackend` (the default) is today's behaviour byte for byte:
  8. the version is the ``file_signature`` stat tuple, reads are ``open`` + ``fast_safe_load`` and raise
  9. exactly what those raise (``FileNotFoundError`` for an absent file, ``OSError``, YAML errors), and
  10. writes are the ruamel round-trip writers in ``utils``. Callers keep their own error handling, so a
  11. backend whose layer always exists simply never takes the "no file" branches. Every other kind
  12. (``HERMES_CONFIG_BACKEND=<kind>``, e.g. ``remote``) is the package ``plugins/config_backends/<kind>/``,
  13. whose ``get_backend()`` returns the instance; this module names no backend beyond that.
  14. The managed scope (``/etc/hermes``) is NOT a backend concern: it stays an overlay applied on top of
  15. whatever user layer the backend returns.
  16. """
  17. from __future__ import annotations
  18. import contextlib
  19. import contextvars
  20. import importlib
  21. import os
  22. import re
  23. import sys
  24. import threading
  25. from dataclasses import dataclass, field
  26. from pathlib import Path
  27. from typing import Any, Mapping, Optional, Protocol, Union, runtime_checkable
  28. CONFIG_FILENAME = "config.yaml"
  29. BACKEND_ENV = "HERMES_CONFIG_BACKEND"
  30. PathLike = Union[str, "os.PathLike[str]"]
  31. @dataclass(frozen=True)
  32. class UserLayer:
  33. """One read of a profile's user layer."""
  34. doc: Any # the parsed root as written (None for an empty document)
  35. version: tuple[Any, ...] # the cache signature this doc was read at (etag for a remote backend)
  36. locks: Mapping[str, str] = field(default_factory=dict) # dotted prefix -> level that locks it
  37. provenance: str = "" # where the doc came from, for diagnostics
  38. @dataclass(frozen=True)
  39. class Changes:
  40. """A write to one profile's user layer.
  41. ``document`` replaces the whole user-layer document (``atomic_config_write``: the file backend
  42. merges it onto the on-disk document, comment-preserving); ``set`` / ``unset`` are single dotted
  43. keys (``atomic_roundtrip_yaml_update`` semantics). A backend applies ``document`` first.
  44. """
  45. document: Optional[dict] = None
  46. set: Mapping[str, Any] = field(default_factory=dict)
  47. unset: tuple[str, ...] = ()
  48. extra_content_on_create: Optional[str] = None
  49. @runtime_checkable
  50. class ConfigBackend(Protocol):
  51. name: str
  52. def read_user_doc(self, home: Path) -> Any:
  53. """The parsed user layer as written (None for an empty document); version checks are separate."""
  54. ...
  55. def read_user_doc_readonly(self, home: Path) -> Any:
  56. """``read_user_doc(home)`` re-read only when ``version`` changes; never mutate it."""
  57. ...
  58. def version(self, home: Path) -> tuple[Any, ...]:
  59. """Cheap change signature; changes whenever the user layer does."""
  60. ...
  61. def cache_version(self, home: Path, version: tuple[Any, ...]) -> tuple[Any, ...]:
  62. """``version`` (just taken) plus whatever a cache needs to tell apart writes it cannot see."""
  63. ...
  64. def exists(self, home: Path) -> bool: ...
  65. def probe_readable(self, home: Path) -> None:
  66. """Raise ``OSError`` while the user layer cannot be read; no parse."""
  67. ...
  68. def write_changes(self, home: Path, changes: Changes) -> None: ...
  69. def locked(self, home: Path, dotted: str) -> Optional[str]:
  70. """The level that locks ``dotted`` (prefix-aware), or None."""
  71. ...
  72. def supports_file_tooling(self) -> bool:
  73. """Whether tools that copy/edit/back up the config FILE (profile clone, backup/restore,
  74. ``config edit``, last-known-good backups, ``migrate_config`` write-back) may run."""
  75. ...
  76. def honors_managed_config(self) -> bool:
  77. """Whether the managed ``/etc/hermes/config.yaml`` overlay applies (D18: not in remote mode)."""
  78. ...
  79. def boot(self, home: Path) -> None:
  80. """Called once per ``load_hermes_dotenv`` after the ``.env`` loads and before the first
  81. config read (design §4.4): a backend that fetches config does it here, failing closed."""
  82. ...
  83. def protected_env_names(self) -> frozenset:
  84. """Env names no external secret source may supply (the plane credential, D32)."""
  85. ...
  86. def deployment_env_names(self) -> frozenset:
  87. """Non-secret env names that select and address this backend (see :func:`deployment_env_names`)."""
  88. ...
  89. def bootstrap_env_names(self) -> frozenset:
  90. """Env names published from the launch home's and the managed ``.env`` before the first
  91. config read (design §4.4 steps 1-2): what this backend needs to select, address and
  92. authenticate itself before any config exists."""
  93. ...
  94. def preserve_read_base(self) -> contextlib.AbstractContextManager:
  95. """A context in which a read does not become the base a later document save is diffed
  96. against (see :func:`keeping_read_base`)."""
  97. ...
  98. def doctor_warnings(self, home: Path) -> tuple:
  99. """``(warning, hint, issue)`` triples ``hermes doctor`` reports after a successful read."""
  100. ...
  101. def apply_in_memory(self, home: Path, doc: dict) -> None:
  102. """Replace the user layer in memory only (in-memory migration, D12). Only called for a
  103. backend without file tooling; nothing is sent or written."""
  104. ...
  105. def describe(self, home: Path) -> str:
  106. """One line naming where the user layer comes from and its state (status line, doctor)."""
  107. ...
  108. def destination(self, home: Path) -> str:
  109. """Where a write lands, for a user-facing "saved in ..." line (no state, no network)."""
  110. ...
  111. class ConfigBackendUnavailable(SystemExit):
  112. """The selected backend cannot serve config. A ``SystemExit`` on purpose: many config readers
  113. fail open with ``except Exception`` → defaults, and serving defaults instead of the selected
  114. backend's config is exactly the silent failure this must not become."""
  115. class ConfigWriteError(RuntimeError):
  116. """A config write the backend refused or could not complete; nothing was changed. ``code`` is
  117. a machine code (the plane's ``error`` for a remote refusal)."""
  118. def __init__(self, message: str, *, code: str = "config_write_failed") -> None:
  119. super().__init__(message)
  120. self.code = code
  121. class ConfigLockedError(ConfigWriteError):
  122. """The write touches a path locked by an upper level (D7, D10)."""
  123. def __init__(self, path: str, locked_by: str, message: Optional[str] = None) -> None:
  124. super().__init__(message or f"{path} is locked by the {locked_by} level", code="config_key_locked")
  125. self.path = path
  126. self.locked_by = locked_by
  127. class ConfigValueError(ConfigWriteError):
  128. """A value the backend cannot store (a YAML-only type, a secret literal); nothing was sent."""
  129. def __init__(self, message: str, *, code: str = "config_value_invalid") -> None:
  130. super().__init__(message, code=code)
  131. class FileBackend:
  132. """The user layer is ``<home>/config.yaml`` on local disk."""
  133. name = "file"
  134. # Path-level primitives: the file backend's whole behaviour, also used for explicit files
  135. # that are not a home's config.yaml (see ``_route``).
  136. @staticmethod
  137. def version_path(path: Path) -> tuple[int, int, int, int]:
  138. st = path.stat() # before the import: a missing file must not need the utils stack (PM runtime)
  139. from utils import file_signature
  140. return file_signature(st)
  141. @staticmethod
  142. def read_path(path: Path) -> Any:
  143. from utils import fast_safe_load
  144. with open(path, encoding="utf-8-sig") as f:
  145. return fast_safe_load(f)
  146. @staticmethod
  147. def read_path_readonly(path: Path) -> Any:
  148. from utils import load_yaml_file_readonly
  149. return load_yaml_file_readonly(path)
  150. @staticmethod
  151. def write_path(path: Path, changes: Changes) -> None:
  152. from utils import atomic_roundtrip_yaml_save, atomic_roundtrip_yaml_update
  153. if changes.document is not None:
  154. atomic_roundtrip_yaml_save(path, changes.document, extra_content_on_create=changes.extra_content_on_create)
  155. for key, value in changes.set.items():
  156. atomic_roundtrip_yaml_update(path, key, value)
  157. for key in changes.unset:
  158. atomic_roundtrip_yaml_update(path, key, None)
  159. def config_path(self, home: Path) -> Path:
  160. return Path(home) / CONFIG_FILENAME
  161. def read_user_doc(self, home: Path) -> Any:
  162. return self.read_path(self.config_path(home))
  163. def read_user_doc_readonly(self, home: Path) -> Any:
  164. return self.read_path_readonly(self.config_path(home))
  165. def version(self, home: Path) -> tuple[int, int, int, int]:
  166. return self.version_path(self.config_path(home))
  167. def cache_version(self, home: Path, version: tuple[Any, ...]) -> tuple[Any, ...]:
  168. # utils.file_cache_version's rule. ``version`` is config_version's opaque token, so the
  169. # racy test takes the file's own signature.
  170. from utils import racy_content_digest
  171. return (*version, racy_content_digest(self.config_path(home), self.version(home)))
  172. def exists(self, home: Path) -> bool:
  173. return self.config_path(home).exists()
  174. def probe_readable(self, home: Path) -> None:
  175. path = self.config_path(home)
  176. with open(path, "rb") as f:
  177. f.read(1)
  178. def write_changes(self, home: Path, changes: Changes) -> None:
  179. self.write_path(self.config_path(home), changes)
  180. def locked(self, home: Path, dotted: str) -> Optional[str]:
  181. return None # a local file has no levels; the managed scope is a separate overlay
  182. def supports_file_tooling(self) -> bool:
  183. return True
  184. def honors_managed_config(self) -> bool:
  185. return True
  186. def boot(self, home: Path) -> None:
  187. return None
  188. def protected_env_names(self) -> frozenset:
  189. return frozenset()
  190. def deployment_env_names(self) -> frozenset:
  191. return frozenset()
  192. def bootstrap_env_names(self) -> frozenset:
  193. return frozenset()
  194. def preserve_read_base(self) -> contextlib.AbstractContextManager:
  195. return contextlib.nullcontext()
  196. def doctor_warnings(self, home: Path) -> tuple:
  197. return ()
  198. def apply_in_memory(self, home: Path, doc: dict) -> None:
  199. raise NotImplementedError("the file backend persists migrations to config.yaml")
  200. def describe(self, home: Path) -> str:
  201. return str(self.config_path(home))
  202. def destination(self, home: Path) -> str:
  203. return str(self.config_path(home))
  204. _FILE_BACKEND = FileBackend()
  205. # Reentrant: publishing the deployment can import modules whose import-time config read selects
  206. # the backend again on the SAME thread (``_BOOTSTRAP_OWNER``); every other thread waits for it.
  207. _BOOTSTRAP_LOCK = threading.RLock()
  208. _BOOTSTRAPPED = False
  209. _BOOTSTRAP_OWNER: Optional[int] = None
  210. def _bootstrap_names(kind: str) -> frozenset:
  211. """The env names backend *kind* (as the ``.env`` layers select it) needs before the first read;
  212. none for a kind this build lacks (selection refuses it afterwards)."""
  213. try:
  214. return _backend_for(kind).bootstrap_env_names()
  215. except ConfigBackendUnavailable:
  216. return frozenset()
  217. def _ensure_bootstrap_env() -> None:
  218. """Once per process, before the first selection: the deployment that selects, addresses and
  219. authenticates the backend comes from the process env, the launch home's ``.env`` and the
  220. managed ``.env`` (design §4.4 steps 1-2, D26/D32) — also when the first config read comes before
  221. ``load_hermes_dotenv`` (``hermes_cli.config`` reads config at import time)."""
  222. if not _BOOTSTRAPPED:
  223. _bootstrap(None, None, once=True)
  224. def bootstrap_deployment(home: Optional[PathLike] = None, project_env: Optional[PathLike] = None) -> None:
  225. """Publish the deployment from an explicit dotenv load's layers (``load_hermes_dotenv``: its
  226. home and project ``.env``) before that load's first config read. Runs even when the
  227. once-per-process bootstrap already ran: an earlier one did not know this load's project file."""
  228. _bootstrap(Path(home) if home is not None else None,
  229. Path(project_env) if project_env is not None else None, once=False)
  230. def _bootstrap(home: Optional[Path], project_env: Optional[Path], *, once: bool) -> None:
  231. global _BOOTSTRAPPED, _BOOTSTRAP_OWNER
  232. with _BOOTSTRAP_LOCK: # another thread's bootstrap in progress: wait for it to publish
  233. if (once and _BOOTSTRAPPED) or _BOOTSTRAP_OWNER == threading.get_ident():
  234. return # done, or this thread's own bootstrap re-entering (import-time config read)
  235. _BOOTSTRAP_OWNER = threading.get_ident()
  236. try:
  237. from hermes_cli.env_loader import apply_config_bootstrap_env
  238. # names resolved only for the kind the .env layers select
  239. apply_config_bootstrap_env(_bootstrap_names, home, project_env)
  240. except ImportError: # no usable python-dotenv (a bare installer interpreter): no .env loads either
  241. pass
  242. finally:
  243. # Complete only once the deployment is published: a concurrent first reader that saw
  244. # the flag earlier would select (and read) the file backend of a remote deployment.
  245. _BOOTSTRAP_OWNER = None
  246. _BOOTSTRAPPED = True
  247. def get_config_backend() -> ConfigBackend:
  248. """The backend selected by ``HERMES_CONFIG_BACKEND`` (default ``file``).
  249. Read from the environment on every call, before any config read, so no config value can
  250. select it (D11). Raises :class:`ConfigBackendUnavailable` for a backend this build lacks.
  251. """
  252. _ensure_bootstrap_env()
  253. return _backend_for(os.environ.get(BACKEND_ENV, "").strip().lower() or "file")
  254. # A kind is one package name under plugins/config_backends/: never a dotted or relative path.
  255. _KIND_RE = re.compile(r"[a-z][a-z0-9_]{0,63}")
  256. _BACKENDS_PACKAGE = "plugins.config_backends"
  257. def _backend_for(kind: str) -> ConfigBackend:
  258. """``file``, or the instance ``plugins.config_backends.<kind>.get_backend()`` returns. The
  259. package is imported directly, never through the general plugin loader (which reads config, D11)."""
  260. if kind == "file":
  261. return _FILE_BACKEND
  262. unknown = f"{BACKEND_ENV}={kind!r} is not a config backend this build provides (expected 'file' or 'remote')."
  263. if not _KIND_RE.fullmatch(kind):
  264. raise ConfigBackendUnavailable(unknown)
  265. name = f"{_BACKENDS_PACKAGE}.{kind}"
  266. module = sys.modules.get(name)
  267. if module is None:
  268. try:
  269. module = importlib.import_module(name)
  270. except ImportError as exc:
  271. if exc.name not in (name, _BACKENDS_PACKAGE, "plugins"):
  272. raise # the backend exists but is broken: show that, not "unknown"
  273. raise ConfigBackendUnavailable(unknown) from exc
  274. get_backend = getattr(module, "get_backend", None)
  275. if not callable(get_backend):
  276. raise ConfigBackendUnavailable(unknown)
  277. return get_backend()
  278. class _ExplicitFile(FileBackend):
  279. """A config file that is not a home's user layer (a test fixture, an import source): the file
  280. backend's behaviour on that exact path, whichever backend is selected."""
  281. def __init__(self, path: Path):
  282. self._path = path
  283. def config_path(self, home: Path) -> Path:
  284. return self._path
  285. def _route(config_path: PathLike) -> tuple[ConfigBackend, Path]:
  286. """``(backend, home)`` serving a config path through the one ``ConfigBackend`` surface.
  287. ``<home>/config.yaml`` is that home's user layer and goes to the selected backend. Any other
  288. file name is an explicit file, served by the file backend on that path.
  289. """
  290. path = Path(config_path)
  291. if path.name == CONFIG_FILENAME:
  292. return get_config_backend(), path.parent
  293. return _ExplicitFile(path), path.parent
  294. def local_file_layer(config_path: PathLike) -> tuple[ConfigBackend, Path]:
  295. """``(backend, home)`` for the LOCAL file at *config_path*, whichever backend is selected.
  296. Only for PM's dependency runtime: it publishes plugin selections to the local file and
  297. compare-and-swaps those bytes, and it carries neither the remote backend's client nor the
  298. plane credential. Everything else goes through :func:`_route`."""
  299. path = Path(config_path)
  300. return _ExplicitFile(path), path.parent
  301. def read_config_doc(config_path: PathLike) -> Any:
  302. """Parsed root of a config file (None when empty); raises like ``open`` + ``fast_safe_load``."""
  303. backend, home = _route(config_path)
  304. return backend.read_user_doc(home)
  305. def read_config_doc_readonly(config_path: PathLike) -> Any:
  306. """Signature-cached :func:`read_config_doc`; the result is shared — never mutate it."""
  307. backend, home = _route(config_path)
  308. return backend.read_user_doc_readonly(home)
  309. def config_version(config_path: PathLike) -> tuple[Any, ...]:
  310. """Cache signature of a config file; raises ``FileNotFoundError`` / ``OSError`` like ``stat``."""
  311. backend, home = _route(config_path)
  312. return backend.version(home)
  313. def config_cache_version(config_path: PathLike) -> tuple[Any, ...]:
  314. """Signature for a cache of a config file's parse: :func:`config_version` can stay equal across a
  315. same-tick same-size rewrite, which would pin the older parse for the process lifetime."""
  316. version = config_version(config_path) # the one stat; its errors (and test seams) stay config_version's
  317. backend, home = _route(config_path)
  318. return backend.cache_version(home, version)
  319. def config_cache_version_or_none(config_path: PathLike) -> Optional[tuple[Any, ...]]:
  320. """:func:`config_cache_version`, or None when the config is absent or cannot be read."""
  321. try:
  322. return config_cache_version(config_path)
  323. except OSError:
  324. return None
  325. def config_version_or_none(config_path: PathLike) -> Optional[tuple[Any, ...]]:
  326. """:func:`config_version`, or None when the config is absent or cannot be stat'ed."""
  327. try:
  328. return config_version(config_path)
  329. except OSError:
  330. return None
  331. def version_token(version: Optional[tuple[Any, ...]]) -> float:
  332. """A number that changes with a backend ``version`` (0 = no config), for clients that only
  333. compare successive values: the file backend's version leads with ``st_mtime_ns``, kept as seconds.
  334. Any other int-led version is scaled the same way, which is fine: only changes are compared."""
  335. if not version:
  336. return 0
  337. if isinstance(version[0], int):
  338. return version[0] / 1_000_000_000
  339. import zlib
  340. return float(zlib.crc32(repr(version).encode("utf-8")) or 1)
  341. def probe_config_readable(config_path: PathLike) -> None:
  342. """Raise ``OSError`` while a config file cannot be read; no parse."""
  343. backend, home = _route(config_path)
  344. backend.probe_readable(home)
  345. def config_exists(config_path: PathLike) -> bool:
  346. backend, home = _route(config_path)
  347. return backend.exists(home)
  348. def write_config_document(config_path: PathLike, document: dict, *, extra_content_on_create: Optional[str] = None) -> None:
  349. """Replace a config file's document (comment-preserving merge for the file backend)."""
  350. backend, home = _route(config_path)
  351. backend.write_changes(home, Changes(document=document, extra_content_on_create=extra_content_on_create))
  352. def config_destination(config_path: PathLike) -> str:
  353. """Where a write to *config_path* lands, for "✓ Set ... in <here>" lines: the file path for
  354. the file backend and explicit files, the backend's own name for the user layer otherwise."""
  355. backend, home = _route(config_path)
  356. return backend.destination(home)
  357. def write_config_key(config_path: PathLike, key_path: str, value: Any) -> None:
  358. """Set one dotted key (``None`` removes it) — ``atomic_roundtrip_yaml_update`` semantics."""
  359. write_config_keys(config_path, {key_path: value})
  360. def write_config_keys(config_path: PathLike, updates: Mapping[str, Any]) -> None:
  361. """Set several related dotted keys (``None`` removes one) as ONE write.
  362. A remote backend sends them as one CAS PATCH, so a refusal of any of them (a lock, a value
  363. check) changes none of them: a grouped edit such as a model switch (default + provider + ...)
  364. never lands half-applied. The file backend applies them key by key, as before."""
  365. backend, home = _route(config_path)
  366. backend.write_changes(home, Changes(set={k: v for k, v in updates.items() if v is not None},
  367. unset=tuple(k for k, v in updates.items() if v is None)))
  368. def keeping_read_base(read):
  369. """Run ``read()`` (a pre-write guard read) without making it the read a later document save
  370. is diffed against: the caller's document came from ITS earlier read (Remote Config). A
  371. context that never read keeps the guard read. No-op for the file backend."""
  372. with get_config_backend().preserve_read_base():
  373. return read()
  374. # Dotted prefixes a document save in this context must write whole: a lock on a changed key under
  375. # one refuses the save (ConfigLockedError) instead of being silently omitted from it.
  376. _REFUSE_LOCKED_OMISSIONS: contextvars.ContextVar[tuple[str, ...]] = contextvars.ContextVar(
  377. "config_refuse_locked_omissions", default=())
  378. @contextlib.contextmanager
  379. def refusing_locked_omissions(*prefixes: str):
  380. """Within the block, a document save that changes a key under one of *prefixes* (dotted, e.g.
  381. ``"model"``) and finds it locked raises :class:`ConfigLockedError` and sends nothing, instead
  382. of dropping the locked key and landing the rest (Remote Config bulk-save rule). Checked against
  383. the locks the save itself sees, so a lock published after an earlier preflight still refuses;
  384. a CAS retry re-checks every key it sends. No-op for the file backend (no locks)."""
  385. token = _REFUSE_LOCKED_OMISSIONS.set(_REFUSE_LOCKED_OMISSIONS.get() + tuple(prefixes))
  386. try:
  387. yield
  388. finally:
  389. _REFUSE_LOCKED_OMISSIONS.reset(token)
  390. def refused_locked_omission_prefixes() -> tuple[str, ...]:
  391. return _REFUSE_LOCKED_OMISSIONS.get()
  392. # Dotted keys a document save in this context stores at the user layer even when the value equals
  393. # what an upper level already supplies (an explicit `config set`): the file backend always writes
  394. # them, and a backend with levels must not drop them as "no change".
  395. _PINNED_KEYS: contextvars.ContextVar[tuple[str, ...]] = contextvars.ContextVar("config_pinned_keys", default=())
  396. @contextlib.contextmanager
  397. def pinning_keys(*keys: str):
  398. """Within the block, a document save stores *keys* (dotted) at the user layer even when
  399. unchanged from the inherited value. No-op for the file backend (it writes the whole file)."""
  400. token = _PINNED_KEYS.set(_PINNED_KEYS.get() + tuple(keys))
  401. try:
  402. yield
  403. finally:
  404. _PINNED_KEYS.reset(token)
  405. def pinned_keys() -> tuple[str, ...]:
  406. return _PINNED_KEYS.get()
  407. def write_changes(config_path: PathLike, changes: Changes) -> None:
  408. """One :class:`Changes` write. Unlike :func:`write_config_keys`, a ``None`` in ``set`` stores
  409. an explicit null (Remote Config: "no value", masking an inherited scalar); the file backend
  410. writes it as YAML null."""
  411. backend, home = _route(config_path)
  412. backend.write_changes(home, changes)
  413. def deployment_env_names() -> frozenset:
  414. """The selected backend's deployment env names (which backend, which plane, which instance).
  415. The deployment is a property of the instance, not of a profile, but it usually arrives in the
  416. launch profile's ``.env``, which a child acting for ANOTHER profile drops as launch residue
  417. (``strip_launch_profile_env``). Such a child re-reads only its own profile's ``.env`` and would
  418. silently select the file backend, so these names are never residue. Credentials are not part
  419. of it: the child resolves its own, and fails closed without them."""
  420. return get_config_backend().deployment_env_names()
  421. def supports_file_tooling() -> bool:
  422. """Gate for tools that copy, edit or back up the config FILE itself (§4.3, §4.7)."""
  423. return get_config_backend().supports_file_tooling()
  424. def require_file_tooling(what: str) -> None:
  425. """Refuse *what* (a file-copy tool) with a clear message when the backend has no config file."""
  426. if not supports_file_tooling():
  427. raise ConfigBackendUnavailable(
  428. f"{what} copies the local config.yaml, and the {get_config_backend().name!r} config "
  429. "backend has none. It is not available with this backend.")