cli-svckit 0.1.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cli_svckit/__init__.py +75 -0
- cli_svckit/contract/__init__.py +47 -0
- cli_svckit/contract/argparse_cli.py +37 -0
- cli_svckit/contract/client.py +290 -0
- cli_svckit/contract/discovery.py +76 -0
- cli_svckit/contract/envelope.py +338 -0
- cli_svckit/contract/schemas/complete.json +126 -0
- cli_svckit/contract/schemas/describe.json +137 -0
- cli_svckit/contract/schemas/doctor.json +87 -0
- cli_svckit/contract/schemas/envelope.json +133 -0
- cli_svckit/contract/schemas/health.json +75 -0
- cli_svckit/contract/schemas/install.json +102 -0
- cli_svckit/contract/schemas/lease.json +114 -0
- cli_svckit/contract/schemas/prepare.json +89 -0
- cli_svckit/contract/server.py +165 -0
- cli_svckit/contract/typer_cli.py +36 -0
- cli_svckit/coord/__init__.py +1 -0
- cli_svckit/coord/controller.py +353 -0
- cli_svckit/coord/lease.py +439 -0
- cli_svckit/coord/participant.py +227 -0
- cli_svckit/coord/watch.py +387 -0
- cli_svckit/doctor.py +125 -0
- cli_svckit/health.py +149 -0
- cli_svckit/procs.py +139 -0
- cli_svckit/py.typed +0 -0
- cli_svckit/rcfile.py +336 -0
- cli_svckit/receipts.py +59 -0
- cli_svckit/testing.py +448 -0
- cli_svckit-0.1.2.dist-info/METADATA +151 -0
- cli_svckit-0.1.2.dist-info/RECORD +32 -0
- cli_svckit-0.1.2.dist-info/WHEEL +4 -0
- cli_svckit-0.1.2.dist-info/licenses/LICENSE +21 -0
cli_svckit/__init__.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""cli-svckit: toolkit for CLIs that ship local services."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from cli_svckit.contract.client import CallResult, Participant, negotiate
|
|
6
|
+
from cli_svckit.contract.discovery import participants_from_registry
|
|
7
|
+
from cli_svckit.contract.envelope import (
|
|
8
|
+
CONTRACT_VERSION,
|
|
9
|
+
ERROR_CODES,
|
|
10
|
+
EXIT_BUSY,
|
|
11
|
+
EXIT_FAIL,
|
|
12
|
+
EXIT_OK,
|
|
13
|
+
EXIT_TEMPFAIL,
|
|
14
|
+
EXIT_USAGE,
|
|
15
|
+
EXIT_WARN,
|
|
16
|
+
METHODS,
|
|
17
|
+
Error,
|
|
18
|
+
Op,
|
|
19
|
+
Request,
|
|
20
|
+
Response,
|
|
21
|
+
SvcError,
|
|
22
|
+
load_schema,
|
|
23
|
+
matches,
|
|
24
|
+
new_op_id,
|
|
25
|
+
parse_stdout,
|
|
26
|
+
redact,
|
|
27
|
+
)
|
|
28
|
+
from cli_svckit.contract.server import dispatch, run
|
|
29
|
+
from cli_svckit.coord.controller import Operation
|
|
30
|
+
from cli_svckit.coord.lease import PHASES, Lease, LeaseDir
|
|
31
|
+
from cli_svckit.coord.participant import Interest, Quiescer, active_ops
|
|
32
|
+
from cli_svckit.coord.watch import LeaseWatcher
|
|
33
|
+
from cli_svckit.doctor import run_checks
|
|
34
|
+
from cli_svckit.health import HealthResult
|
|
35
|
+
|
|
36
|
+
__version__ = "0.1.2"
|
|
37
|
+
|
|
38
|
+
__all__ = [
|
|
39
|
+
"CONTRACT_VERSION",
|
|
40
|
+
"CallResult",
|
|
41
|
+
"ERROR_CODES",
|
|
42
|
+
"EXIT_BUSY",
|
|
43
|
+
"EXIT_FAIL",
|
|
44
|
+
"EXIT_OK",
|
|
45
|
+
"EXIT_TEMPFAIL",
|
|
46
|
+
"EXIT_USAGE",
|
|
47
|
+
"EXIT_WARN",
|
|
48
|
+
"Error",
|
|
49
|
+
"HealthResult",
|
|
50
|
+
"Interest",
|
|
51
|
+
"Lease",
|
|
52
|
+
"LeaseDir",
|
|
53
|
+
"LeaseWatcher",
|
|
54
|
+
"METHODS",
|
|
55
|
+
"Op",
|
|
56
|
+
"Operation",
|
|
57
|
+
"PHASES",
|
|
58
|
+
"Participant",
|
|
59
|
+
"Quiescer",
|
|
60
|
+
"Request",
|
|
61
|
+
"Response",
|
|
62
|
+
"SvcError",
|
|
63
|
+
"__version__",
|
|
64
|
+
"active_ops",
|
|
65
|
+
"dispatch",
|
|
66
|
+
"load_schema",
|
|
67
|
+
"matches",
|
|
68
|
+
"negotiate",
|
|
69
|
+
"new_op_id",
|
|
70
|
+
"parse_stdout",
|
|
71
|
+
"participants_from_registry",
|
|
72
|
+
"redact",
|
|
73
|
+
"run",
|
|
74
|
+
"run_checks",
|
|
75
|
+
]
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""The svckit JSON contract between a controller and participant tools (see ``docs/contract.md``)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from cli_svckit.contract.envelope import (
|
|
6
|
+
CONTRACT_VERSION,
|
|
7
|
+
ERROR_CODES,
|
|
8
|
+
EXIT_BUSY,
|
|
9
|
+
EXIT_FAIL,
|
|
10
|
+
EXIT_OK,
|
|
11
|
+
EXIT_TEMPFAIL,
|
|
12
|
+
EXIT_USAGE,
|
|
13
|
+
EXIT_WARN,
|
|
14
|
+
METHODS,
|
|
15
|
+
Error,
|
|
16
|
+
Op,
|
|
17
|
+
Request,
|
|
18
|
+
Response,
|
|
19
|
+
SvcError,
|
|
20
|
+
load_schema,
|
|
21
|
+
matches,
|
|
22
|
+
new_op_id,
|
|
23
|
+
parse_stdout,
|
|
24
|
+
redact,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
"CONTRACT_VERSION",
|
|
29
|
+
"ERROR_CODES",
|
|
30
|
+
"EXIT_BUSY",
|
|
31
|
+
"EXIT_FAIL",
|
|
32
|
+
"EXIT_OK",
|
|
33
|
+
"EXIT_TEMPFAIL",
|
|
34
|
+
"EXIT_USAGE",
|
|
35
|
+
"EXIT_WARN",
|
|
36
|
+
"METHODS",
|
|
37
|
+
"Error",
|
|
38
|
+
"Op",
|
|
39
|
+
"Request",
|
|
40
|
+
"Response",
|
|
41
|
+
"SvcError",
|
|
42
|
+
"load_schema",
|
|
43
|
+
"matches",
|
|
44
|
+
"new_op_id",
|
|
45
|
+
"parse_stdout",
|
|
46
|
+
"redact",
|
|
47
|
+
]
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""argparse adapter: add ``svc <method>`` to a tool's own argparse CLI."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from cli_svckit.contract.envelope import METHODS
|
|
10
|
+
from cli_svckit.contract.server import run
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def add_svc_subparser(subparsers: Any, provider: Any, name: str = "svc") -> argparse.ArgumentParser:
|
|
14
|
+
"""Add a ``svc <method> [--json] [--request-file PATH]`` command to ``subparsers``.
|
|
15
|
+
|
|
16
|
+
The parsed namespace gets a ``func`` that runs the call and returns the exit code.
|
|
17
|
+
"""
|
|
18
|
+
svc = subparsers.add_parser(name, help="svckit contract commands")
|
|
19
|
+
svc.add_argument("method", choices=METHODS)
|
|
20
|
+
svc.add_argument("--json", action="store_true", dest="as_json", help="print one JSON line")
|
|
21
|
+
svc.add_argument("--request-file", default=None, help="read the request from this file")
|
|
22
|
+
|
|
23
|
+
def func(ns: argparse.Namespace) -> int:
|
|
24
|
+
argv = [ns.method]
|
|
25
|
+
if ns.as_json:
|
|
26
|
+
argv.append("--json")
|
|
27
|
+
if ns.request_file:
|
|
28
|
+
argv += ["--request-file", ns.request_file]
|
|
29
|
+
return run(provider, argv)
|
|
30
|
+
|
|
31
|
+
svc.set_defaults(func=func)
|
|
32
|
+
return svc
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def main(provider: Any, argv: list[str] | None = None) -> int:
|
|
36
|
+
"""Run a standalone ``svc``-style CLI (``<method> [--json] ...``) for ``provider`` and return the exit code."""
|
|
37
|
+
return run(provider, sys.argv[1:] if argv is None else argv)
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
"""Controller side of the svckit contract: call a participant tool and read its answer."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import signal
|
|
10
|
+
import subprocess
|
|
11
|
+
import time
|
|
12
|
+
import uuid
|
|
13
|
+
from collections.abc import Callable, Mapping
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from cli_svckit.contract.envelope import (
|
|
19
|
+
CONTRACT_VERSION,
|
|
20
|
+
Error,
|
|
21
|
+
Request,
|
|
22
|
+
Response,
|
|
23
|
+
SvcError,
|
|
24
|
+
parse_stdout,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
KILL_GRACE_S = 5.0
|
|
28
|
+
_VERSION_RE = re.compile(r"^(\d+)\.(\d+|x)$")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class CallResult:
|
|
33
|
+
"""What one call to a participant produced. Never raised: failures are described here."""
|
|
34
|
+
|
|
35
|
+
participant: str
|
|
36
|
+
method: str
|
|
37
|
+
ok: bool
|
|
38
|
+
response: Response | None
|
|
39
|
+
error: Error | None
|
|
40
|
+
rc: int | None
|
|
41
|
+
duration_s: float
|
|
42
|
+
timed_out: bool
|
|
43
|
+
fail_policy: str = "open"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _caller() -> dict[str, Any]:
|
|
47
|
+
"""Return the ``caller`` object: ``SVCKIT_CALLER`` (JSON object) if valid, else the library default."""
|
|
48
|
+
raw = os.environ.get("SVCKIT_CALLER")
|
|
49
|
+
if raw:
|
|
50
|
+
try:
|
|
51
|
+
value = json.loads(raw)
|
|
52
|
+
except ValueError:
|
|
53
|
+
value = None
|
|
54
|
+
if isinstance(value, dict):
|
|
55
|
+
return value
|
|
56
|
+
return {"tool": "cli-svckit"}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _terminate(proc: subprocess.Popen[str]) -> None:
|
|
60
|
+
"""Stop a child: SIGTERM, then SIGKILL after a short grace period; always reaps it."""
|
|
61
|
+
with contextlib.suppress(OSError):
|
|
62
|
+
os.killpg(proc.pid, signal.SIGTERM)
|
|
63
|
+
try:
|
|
64
|
+
proc.communicate(timeout=KILL_GRACE_S)
|
|
65
|
+
except subprocess.TimeoutExpired:
|
|
66
|
+
with contextlib.suppress(OSError):
|
|
67
|
+
os.killpg(proc.pid, signal.SIGKILL)
|
|
68
|
+
with contextlib.suppress(Exception):
|
|
69
|
+
proc.communicate(timeout=KILL_GRACE_S)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class Participant:
|
|
73
|
+
"""A tool that speaks the contract: ``cmd + ["svc", <method>, "--json"]`` with the request on stdin."""
|
|
74
|
+
|
|
75
|
+
def __init__(
|
|
76
|
+
self,
|
|
77
|
+
name: str,
|
|
78
|
+
cmd: list[str],
|
|
79
|
+
*,
|
|
80
|
+
timeout_s: float = 120.0,
|
|
81
|
+
fail_policy: str = "open",
|
|
82
|
+
wait_for: str = "interrupted",
|
|
83
|
+
env: Mapping[str, str] | None = None,
|
|
84
|
+
drop_env_prefixes: tuple[str, ...] = ("HERMES_KANBAN_",),
|
|
85
|
+
) -> None:
|
|
86
|
+
if fail_policy not in ("open", "closed"):
|
|
87
|
+
raise SvcError("invalid", "fail_policy must be 'open' or 'closed'", data={"participant": name})
|
|
88
|
+
self.name = name
|
|
89
|
+
self.cmd = list(cmd)
|
|
90
|
+
self.timeout_s = timeout_s
|
|
91
|
+
self.fail_policy = fail_policy
|
|
92
|
+
self.wait_for = wait_for
|
|
93
|
+
self.env = None if env is None else dict(env)
|
|
94
|
+
self.drop_env_prefixes = tuple(drop_env_prefixes)
|
|
95
|
+
self.services: list[str] = []
|
|
96
|
+
|
|
97
|
+
def _clean_env(self) -> dict[str, str]:
|
|
98
|
+
"""Return the child environment: ``env`` (or ours) minus keys starting with a dropped prefix."""
|
|
99
|
+
base = dict(os.environ if self.env is None else self.env)
|
|
100
|
+
if not self.drop_env_prefixes:
|
|
101
|
+
return base
|
|
102
|
+
return {k: v for k, v in base.items() if not k.startswith(self.drop_env_prefixes)}
|
|
103
|
+
|
|
104
|
+
def call(self, method: str, params: dict[str, Any] | None = None, *, timeout_s: float | None = None) -> CallResult:
|
|
105
|
+
"""Run one method and return what happened. Timeouts kill the child; participant faults never raise."""
|
|
106
|
+
timeout = self.timeout_s if timeout_s is None else timeout_s
|
|
107
|
+
request = Request(
|
|
108
|
+
method=method,
|
|
109
|
+
params=dict(params or {}),
|
|
110
|
+
id=uuid.uuid4().hex,
|
|
111
|
+
caller=_caller(),
|
|
112
|
+
deadline_ms=int(timeout * 1000),
|
|
113
|
+
)
|
|
114
|
+
argv = [*self.cmd, "svc", method, "--json"]
|
|
115
|
+
start = time.monotonic()
|
|
116
|
+
|
|
117
|
+
def finish(
|
|
118
|
+
ok: bool, response: Response | None, error: Error | None, rc: int | None, timed_out: bool = False
|
|
119
|
+
) -> CallResult:
|
|
120
|
+
return CallResult(
|
|
121
|
+
self.name, method, ok, response, error, rc, time.monotonic() - start, timed_out, self.fail_policy
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
try:
|
|
125
|
+
proc = subprocess.Popen(
|
|
126
|
+
argv,
|
|
127
|
+
stdin=subprocess.PIPE,
|
|
128
|
+
stdout=subprocess.PIPE,
|
|
129
|
+
stderr=subprocess.PIPE,
|
|
130
|
+
text=True,
|
|
131
|
+
env=self._clean_env(),
|
|
132
|
+
start_new_session=True,
|
|
133
|
+
)
|
|
134
|
+
except (OSError, ValueError) as exc:
|
|
135
|
+
return finish(False, None, Error("internal", f"cannot run participant: {type(exc).__name__}"), None)
|
|
136
|
+
try:
|
|
137
|
+
stdout, _stderr = proc.communicate(request.to_json() + "\n", timeout=timeout)
|
|
138
|
+
except subprocess.TimeoutExpired:
|
|
139
|
+
_terminate(proc)
|
|
140
|
+
return finish(False, None, Error("timeout", f"no answer in {timeout:g}s"), proc.returncode, True)
|
|
141
|
+
except BaseException:
|
|
142
|
+
_terminate(proc)
|
|
143
|
+
raise
|
|
144
|
+
rc = proc.returncode
|
|
145
|
+
try:
|
|
146
|
+
response = parse_stdout(stdout or "")
|
|
147
|
+
except SvcError:
|
|
148
|
+
return finish(False, None, Error("invalid", f"unparseable output (rc={rc})"), rc)
|
|
149
|
+
return finish(response.ok, response, response.error, rc)
|
|
150
|
+
|
|
151
|
+
def describe(self, cache: DescribeCache | None = None) -> dict[str, Any] | None:
|
|
152
|
+
"""Return the ``describe`` result (or None on failure), using ``cache`` when it is still valid."""
|
|
153
|
+
if cache is not None:
|
|
154
|
+
return cache.describe(self)
|
|
155
|
+
return self._describe_now()
|
|
156
|
+
|
|
157
|
+
def _describe_now(self) -> dict[str, Any] | None:
|
|
158
|
+
"""Ask the tool for ``describe`` and return its result object, or None."""
|
|
159
|
+
res = self.call("describe", timeout_s=min(self.timeout_s, 30.0))
|
|
160
|
+
if res.ok and res.response is not None and isinstance(res.response.result, dict):
|
|
161
|
+
return res.response.result
|
|
162
|
+
return None
|
|
163
|
+
|
|
164
|
+
def probe_version(self) -> str | None:
|
|
165
|
+
"""Cheap version probe: run ``cmd --version`` and return the last word of its first line, or None."""
|
|
166
|
+
try:
|
|
167
|
+
done = subprocess.run(
|
|
168
|
+
[*self.cmd, "--version"],
|
|
169
|
+
capture_output=True,
|
|
170
|
+
text=True,
|
|
171
|
+
timeout=10.0,
|
|
172
|
+
env=self._clean_env(),
|
|
173
|
+
stdin=subprocess.DEVNULL,
|
|
174
|
+
)
|
|
175
|
+
except (OSError, subprocess.SubprocessError):
|
|
176
|
+
return None
|
|
177
|
+
if done.returncode != 0:
|
|
178
|
+
return None
|
|
179
|
+
lines = done.stdout.strip().splitlines()
|
|
180
|
+
words = lines[0].split() if lines else []
|
|
181
|
+
return words[-1] if words else None
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def effective_ready(result: CallResult, fail_policy: str | None = None) -> bool | None:
|
|
185
|
+
"""Interpret a ``prepare`` result: True ready, False busy, None when the method is not applicable.
|
|
186
|
+
|
|
187
|
+
A participant's own answer decides (``result.ok`` with ``ready``, or exit code 3 meaning busy). Errors and timeouts
|
|
188
|
+
follow ``fail_policy`` (``open``: counts as ready, ``closed``: counts as busy); ``unsupported`` is not applicable.
|
|
189
|
+
"""
|
|
190
|
+
policy = fail_policy or result.fail_policy
|
|
191
|
+
if result.ok and result.response is not None:
|
|
192
|
+
data = result.response.result or {}
|
|
193
|
+
ready = data.get("ready")
|
|
194
|
+
if isinstance(ready, bool):
|
|
195
|
+
return ready
|
|
196
|
+
return result.rc != 3
|
|
197
|
+
error = result.error
|
|
198
|
+
if error is not None and error.code == "unsupported":
|
|
199
|
+
return None
|
|
200
|
+
return policy != "closed"
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
class DescribeCache:
|
|
204
|
+
"""JSON file cache of ``describe`` results keyed by participant name, command and tool version."""
|
|
205
|
+
|
|
206
|
+
def __init__(
|
|
207
|
+
self,
|
|
208
|
+
path: str | os.PathLike[str],
|
|
209
|
+
*,
|
|
210
|
+
max_age_s: float = 3600.0,
|
|
211
|
+
clock: Callable[[], float] = time.time,
|
|
212
|
+
) -> None:
|
|
213
|
+
self.path = Path(path)
|
|
214
|
+
self.max_age_s = max_age_s
|
|
215
|
+
self.clock = clock
|
|
216
|
+
|
|
217
|
+
def _load(self) -> dict[str, Any]:
|
|
218
|
+
try:
|
|
219
|
+
data = json.loads(self.path.read_text())
|
|
220
|
+
except (OSError, ValueError):
|
|
221
|
+
return {}
|
|
222
|
+
return data if isinstance(data, dict) else {}
|
|
223
|
+
|
|
224
|
+
def _save(self, data: dict[str, Any]) -> None:
|
|
225
|
+
try:
|
|
226
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
227
|
+
tmp = self.path.with_name(self.path.name + f".{os.getpid()}.tmp")
|
|
228
|
+
tmp.write_text(json.dumps(data))
|
|
229
|
+
os.replace(tmp, self.path)
|
|
230
|
+
except OSError:
|
|
231
|
+
pass
|
|
232
|
+
|
|
233
|
+
@staticmethod
|
|
234
|
+
def _key(p: Participant) -> str:
|
|
235
|
+
return json.dumps([p.name, p.cmd])
|
|
236
|
+
|
|
237
|
+
def describe(self, p: Participant) -> dict[str, Any] | None:
|
|
238
|
+
"""Return the cached describe result when valid, else fetch, store and return a fresh one."""
|
|
239
|
+
data = self._load()
|
|
240
|
+
key = self._key(p)
|
|
241
|
+
entry = data.get(key)
|
|
242
|
+
now = self.clock()
|
|
243
|
+
if isinstance(entry, dict) and isinstance(entry.get("result"), dict):
|
|
244
|
+
try:
|
|
245
|
+
age = now - float(entry.get("at", 0.0))
|
|
246
|
+
except (TypeError, ValueError):
|
|
247
|
+
age = -1.0
|
|
248
|
+
if 0 <= age <= self.max_age_s:
|
|
249
|
+
return entry["result"]
|
|
250
|
+
# The stored version comes from describe's tool.version; it is compared with the last word of
|
|
251
|
+
# ``cmd --version``, so a tool printing "v1.0.0" never matches and simply refetches.
|
|
252
|
+
version = p.probe_version() if age >= 0 else None
|
|
253
|
+
if version is not None and version == entry.get("version"):
|
|
254
|
+
entry["at"] = now
|
|
255
|
+
data[key] = entry
|
|
256
|
+
self._save(data)
|
|
257
|
+
return entry["result"]
|
|
258
|
+
result = p._describe_now()
|
|
259
|
+
if result is None:
|
|
260
|
+
return None
|
|
261
|
+
tool = result.get("tool")
|
|
262
|
+
version = tool.get("version") if isinstance(tool, dict) else None
|
|
263
|
+
if not isinstance(version, str):
|
|
264
|
+
version = p.probe_version()
|
|
265
|
+
data[key] = {"at": now, "version": version, "result": result}
|
|
266
|
+
self._save(data)
|
|
267
|
+
return result
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def negotiate(contract: dict[str, Any]) -> str:
|
|
271
|
+
"""Check our contract version is within the participant's ``[min, max]`` (max may be ``1.x``); returns it."""
|
|
272
|
+
|
|
273
|
+
def parse(value: Any, allow_x: bool) -> tuple[int, float]:
|
|
274
|
+
m = _VERSION_RE.match(str(value))
|
|
275
|
+
if not m or (m.group(2) == "x" and not allow_x):
|
|
276
|
+
raise SvcError("incompatible", f"bad contract version {value!r}")
|
|
277
|
+
return int(m.group(1)), (float("inf") if m.group(2) == "x" else int(m.group(2)))
|
|
278
|
+
|
|
279
|
+
if not isinstance(contract, dict) or "min" not in contract or "max" not in contract:
|
|
280
|
+
raise SvcError("incompatible", "participant did not report a contract range")
|
|
281
|
+
ours = parse(CONTRACT_VERSION, False)
|
|
282
|
+
lo = parse(contract["min"], False)
|
|
283
|
+
hi = parse(contract["max"], True)
|
|
284
|
+
if not (lo <= ours <= hi):
|
|
285
|
+
raise SvcError(
|
|
286
|
+
"incompatible",
|
|
287
|
+
f"contract {CONTRACT_VERSION} is outside {contract['min']}..{contract['max']}",
|
|
288
|
+
data={"ours": CONTRACT_VERSION, "min": contract["min"], "max": contract["max"]},
|
|
289
|
+
)
|
|
290
|
+
return CONTRACT_VERSION
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Find participants: from a ``[participants.<name>]`` registry table or from Python entry points."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from importlib import metadata
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from cli_svckit.contract.client import Participant
|
|
10
|
+
from cli_svckit.contract.envelope import SvcError
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _bad(name: str, msg: str) -> SvcError:
|
|
14
|
+
return SvcError("invalid", f"participant {name!r}: {msg}", data={"participant": name})
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _from_entry(name: str, entry: Any) -> Participant | None:
|
|
18
|
+
"""Build one participant from a registry entry; None when disabled."""
|
|
19
|
+
if not isinstance(entry, dict):
|
|
20
|
+
raise _bad(name, "entry must be a table")
|
|
21
|
+
enabled = entry.get("enabled", True)
|
|
22
|
+
if not isinstance(enabled, bool):
|
|
23
|
+
raise _bad(name, "enabled must be a boolean")
|
|
24
|
+
if not enabled:
|
|
25
|
+
return None
|
|
26
|
+
cmd = entry.get("cmd")
|
|
27
|
+
if not isinstance(cmd, list) or not cmd or not all(isinstance(c, str) and c for c in cmd):
|
|
28
|
+
raise _bad(name, "cmd must be a non-empty list of strings")
|
|
29
|
+
kwargs: dict[str, Any] = {}
|
|
30
|
+
if "timeout_seconds" in entry:
|
|
31
|
+
t = entry["timeout_seconds"]
|
|
32
|
+
if isinstance(t, bool) or not isinstance(t, int | float) or t <= 0:
|
|
33
|
+
raise _bad(name, "timeout_seconds must be a positive number")
|
|
34
|
+
kwargs["timeout_s"] = float(t)
|
|
35
|
+
if "fail_policy" in entry:
|
|
36
|
+
if entry["fail_policy"] not in ("open", "closed"):
|
|
37
|
+
raise _bad(name, "fail_policy must be 'open' or 'closed'")
|
|
38
|
+
kwargs["fail_policy"] = entry["fail_policy"]
|
|
39
|
+
if "wait_for" in entry:
|
|
40
|
+
if not isinstance(entry["wait_for"], str):
|
|
41
|
+
raise _bad(name, "wait_for must be a string")
|
|
42
|
+
kwargs["wait_for"] = entry["wait_for"]
|
|
43
|
+
services = entry.get("services", [])
|
|
44
|
+
if not isinstance(services, list) or not all(isinstance(s, str) for s in services):
|
|
45
|
+
raise _bad(name, "services must be a list of strings")
|
|
46
|
+
p = Participant(name, [os.path.expanduser(c) for c in cmd], **kwargs)
|
|
47
|
+
p.services = list(services)
|
|
48
|
+
return p
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def participants_from_registry(table: dict[str, Any]) -> list[Participant]:
|
|
52
|
+
"""Build participants from a mapping of name -> entry; disabled entries are skipped, bad ones raise."""
|
|
53
|
+
if not isinstance(table, dict):
|
|
54
|
+
raise SvcError("invalid", "participants table must be a mapping")
|
|
55
|
+
out: list[Participant] = []
|
|
56
|
+
for name, entry in table.items():
|
|
57
|
+
p = _from_entry(str(name), entry)
|
|
58
|
+
if p is not None:
|
|
59
|
+
out.append(p)
|
|
60
|
+
return out
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def participants_from_entry_points(group: str = "cli_svckit.participants") -> list[Participant]:
|
|
64
|
+
"""Load participants from entry points; each yields a registry-style dict (or a callable returning one)."""
|
|
65
|
+
out: list[Participant] = []
|
|
66
|
+
for ep in metadata.entry_points(group=group):
|
|
67
|
+
try:
|
|
68
|
+
value = ep.load()
|
|
69
|
+
if callable(value):
|
|
70
|
+
value = value()
|
|
71
|
+
except Exception as exc:
|
|
72
|
+
raise SvcError("invalid", f"entry point {ep.name!r} failed to load", data={"participant": ep.name}) from exc
|
|
73
|
+
p = _from_entry(ep.name, value)
|
|
74
|
+
if p is not None:
|
|
75
|
+
out.append(p)
|
|
76
|
+
return out
|