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.
@@ -0,0 +1,338 @@
1
+ """The svckit JSON contract: request/response envelopes, errors, exit codes and the operation record.
2
+
3
+ A controller runs ``<cmd> svc <method> --json`` with a :class:`Request` on stdin; the participant prints log lines
4
+ as it likes and finishes with one JSON :class:`Response` line on stdout (the last JSON line wins, see
5
+ :func:`parse_stdout`). Readers ignore fields they do not know (must-ignore), so minor versions only add optional
6
+ fields. ``busy`` is a normal result (``prepare`` returning ``state: "busy"``), never an error.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import copy
12
+ import fnmatch
13
+ import importlib.resources
14
+ import json
15
+ import re
16
+ import secrets
17
+ import time
18
+ from collections.abc import Callable, Iterable
19
+ from dataclasses import dataclass, field
20
+ from typing import Any
21
+
22
+ CONTRACT_VERSION = "1.0"
23
+ METHODS = ("describe", "health", "doctor", "install", "uninstall", "prepare", "complete")
24
+
25
+ EXIT_OK = 0
26
+ EXIT_FAIL = 1
27
+ EXIT_USAGE = 2
28
+ EXIT_BUSY = 3
29
+ EXIT_WARN = 4
30
+ EXIT_TEMPFAIL = 75
31
+
32
+ ERROR_CODES = ("unsupported", "invalid", "forbidden", "requires_root", "timeout", "internal", "incompatible")
33
+
34
+ _SECRET_KEY = re.compile(r"(?i)token|secret|password|passwd|key|auth|cookie")
35
+ _SCHEMA_NAME = re.compile(r"^[a-z][a-z0-9_]*$")
36
+
37
+
38
+ class SvcError(Exception):
39
+ """An error a participant (or the library) reports through the contract.
40
+
41
+ ``code`` is one of :data:`ERROR_CODES`; ``retry_after_s`` tells the caller when a retry may succeed.
42
+ """
43
+
44
+ def __init__(
45
+ self,
46
+ code: str,
47
+ message: str,
48
+ data: dict[str, Any] | None = None,
49
+ retry_after_s: float | None = None,
50
+ ) -> None:
51
+ super().__init__(message)
52
+ self.code = code
53
+ self.message = message
54
+ self.data = data
55
+ self.retry_after_s = retry_after_s
56
+
57
+ def to_error(self) -> Error:
58
+ """Return the wire :class:`Error` for this exception."""
59
+ return Error(code=self.code, message=self.message, retry_after_s=self.retry_after_s, data=self.data)
60
+
61
+ def __repr__(self) -> str:
62
+ return f"SvcError({self.code!r}, {self.message!r})"
63
+
64
+
65
+ def _need_dict(d: Any, what: str) -> dict[str, Any]:
66
+ if not isinstance(d, dict):
67
+ raise SvcError("invalid", f"{what} must be a JSON object")
68
+ return d
69
+
70
+
71
+ def _need_str(d: dict[str, Any], key: str, what: str) -> str:
72
+ value = d.get(key)
73
+ if not isinstance(value, str):
74
+ raise SvcError("invalid", f"{what}.{key} must be a string")
75
+ return value
76
+
77
+
78
+ def _opt_dict(d: dict[str, Any], key: str, what: str) -> dict[str, Any] | None:
79
+ value = d.get(key)
80
+ if value is not None and not isinstance(value, dict):
81
+ raise SvcError("invalid", f"{what}.{key} must be an object or null")
82
+ return value
83
+
84
+
85
+ @dataclass
86
+ class Request:
87
+ """One call from a controller to a participant: ``method`` with ``params``.
88
+
89
+ ``caller`` describes who is calling (free-form object); ``deadline_ms`` is how long the caller will wait.
90
+ """
91
+
92
+ method: str
93
+ params: dict[str, Any]
94
+ id: str
95
+ caller: dict[str, Any] | None = None
96
+ deadline_ms: int | None = None
97
+
98
+ def to_dict(self) -> dict[str, Any]:
99
+ """Return the wire form (keys ``svckit, id, method, caller, deadline_ms, params``)."""
100
+ return {
101
+ "svckit": CONTRACT_VERSION,
102
+ "id": self.id,
103
+ "method": self.method,
104
+ "caller": self.caller,
105
+ "deadline_ms": self.deadline_ms,
106
+ "params": self.params,
107
+ }
108
+
109
+ def to_json(self) -> str:
110
+ """Return the wire form as one line of JSON."""
111
+ return json.dumps(self.to_dict(), separators=(",", ":"))
112
+
113
+ @classmethod
114
+ def from_dict(cls, d: dict[str, Any]) -> Request:
115
+ """Build a request from its wire form; unknown keys are ignored. Raises ``SvcError("invalid")``."""
116
+ d = _need_dict(d, "request")
117
+ params = d.get("params")
118
+ if params is None:
119
+ params = {}
120
+ if not isinstance(params, dict):
121
+ raise SvcError("invalid", "request.params must be an object")
122
+ deadline = d.get("deadline_ms")
123
+ if deadline is not None and (isinstance(deadline, bool) or not isinstance(deadline, int | float)):
124
+ raise SvcError("invalid", "request.deadline_ms must be a number or null")
125
+ rid = d.get("id")
126
+ return cls(
127
+ method=_need_str(d, "method", "request"),
128
+ params=params,
129
+ id="" if rid is None else str(rid),
130
+ caller=_opt_dict(d, "caller", "request"),
131
+ deadline_ms=None if deadline is None else int(deadline),
132
+ )
133
+
134
+
135
+ @dataclass
136
+ class Error:
137
+ """The ``error`` object of a failed response."""
138
+
139
+ code: str
140
+ message: str
141
+ retry_after_s: float | None = None
142
+ data: dict[str, Any] | None = None
143
+
144
+ def to_dict(self) -> dict[str, Any]:
145
+ """Return the wire form; optional fields are left out when unset."""
146
+ out: dict[str, Any] = {"code": self.code, "message": self.message}
147
+ if self.retry_after_s is not None:
148
+ out["retry_after_s"] = self.retry_after_s
149
+ if self.data is not None:
150
+ out["data"] = self.data
151
+ return out
152
+
153
+ @classmethod
154
+ def from_dict(cls, d: dict[str, Any]) -> Error:
155
+ """Build an error from its wire form. Raises ``SvcError("invalid")`` when it is malformed."""
156
+ d = _need_dict(d, "error")
157
+ retry = d.get("retry_after_s")
158
+ if retry is not None and (isinstance(retry, bool) or not isinstance(retry, int | float)):
159
+ raise SvcError("invalid", "error.retry_after_s must be a number or null")
160
+ return cls(
161
+ code=_need_str(d, "code", "error"),
162
+ message=str(d.get("message", "")),
163
+ retry_after_s=None if retry is None else float(retry),
164
+ data=_opt_dict(d, "data", "error"),
165
+ )
166
+
167
+
168
+ @dataclass
169
+ class Response:
170
+ """A participant's answer: ``ok`` with a ``result`` object, or not ok with an :class:`Error`."""
171
+
172
+ id: str
173
+ ok: bool
174
+ result: dict[str, Any] | None = None
175
+ error: Error | None = None
176
+
177
+ def to_dict(self) -> dict[str, Any]:
178
+ """Return the wire form (``svckit, id, ok`` plus ``result`` and/or ``error`` when set)."""
179
+ out: dict[str, Any] = {"svckit": CONTRACT_VERSION, "id": self.id, "ok": self.ok}
180
+ if self.result is not None:
181
+ out["result"] = self.result
182
+ if self.error is not None:
183
+ out["error"] = self.error.to_dict()
184
+ return out
185
+
186
+ def to_json(self) -> str:
187
+ """Return the wire form as one line of JSON (what a participant prints last on stdout)."""
188
+ return json.dumps(self.to_dict(), separators=(",", ":"))
189
+
190
+ @classmethod
191
+ def from_dict(cls, d: dict[str, Any]) -> Response:
192
+ """Build a response from its wire form; unknown keys are ignored. Raises ``SvcError("invalid")``."""
193
+ d = _need_dict(d, "response")
194
+ ok = d.get("ok")
195
+ if not isinstance(ok, bool):
196
+ raise SvcError("invalid", "response.ok must be true or false")
197
+ err = d.get("error")
198
+ rid = d.get("id")
199
+ return cls(
200
+ id="" if rid is None else str(rid),
201
+ ok=ok,
202
+ result=_opt_dict(d, "result", "response"),
203
+ error=None if err is None else Error.from_dict(err),
204
+ )
205
+
206
+
207
+ def parse_stdout(text: str) -> Response:
208
+ """Find the response in a participant's stdout.
209
+
210
+ Participants may print log lines first; the last non-empty line that parses as a JSON object is the
211
+ response. Raises ``SvcError("invalid")`` when there is no such line or it is not a valid response.
212
+ """
213
+ for line in reversed(text.splitlines()):
214
+ line = line.strip()
215
+ if not line:
216
+ continue
217
+ try:
218
+ obj = json.loads(line)
219
+ except ValueError:
220
+ continue
221
+ if isinstance(obj, dict):
222
+ return Response.from_dict(obj)
223
+ raise SvcError("invalid", "no JSON response line on stdout", data={"stdout_tail": text[-500:]})
224
+
225
+
226
+ def redact(obj: Any) -> Any:
227
+ """Return a deep copy of ``obj`` in which values of secret-looking keys are replaced by ``"***"``.
228
+
229
+ A key is secret-looking when it contains token, secret, password, passwd, key, auth or cookie (any case).
230
+ Dicts, lists and tuples are walked recursively; the input is never modified.
231
+ """
232
+ if isinstance(obj, dict):
233
+ return {k: "***" if isinstance(k, str) and _SECRET_KEY.search(k) else redact(v) for k, v in obj.items()}
234
+ if isinstance(obj, list):
235
+ return [redact(v) for v in obj]
236
+ if isinstance(obj, tuple):
237
+ return tuple(redact(v) for v in obj)
238
+ return copy.deepcopy(obj)
239
+
240
+
241
+ @dataclass
242
+ class Op:
243
+ """An operation a controller announces (restart, update, ...) and asks participants to quiesce for.
244
+
245
+ Times are UNIX timestamps: ``deadline`` is when the controller stops waiting for participants,
246
+ ``expires_at`` when a lease for this op counts as stale. ``wait_for`` says what ready means
247
+ (``"interrupted"``: in-flight work may be interrupted safely; other values are tool-defined); ``now``
248
+ asks participants not to wait at all. ``lease`` is the lease file path, when there is one.
249
+ On the wire ``affected_pids`` is nested as ``"affected": {"pids": [...] | null}``.
250
+ """
251
+
252
+ id: str
253
+ kind: str
254
+ targets: list[str]
255
+ reason: str = ""
256
+ by: dict[str, Any] = field(default_factory=dict)
257
+ started_at: float = 0.0
258
+ deadline: float = 0.0
259
+ expires_at: float = 0.0
260
+ affected_pids: list[int] | None = None
261
+ wait_for: str = "interrupted"
262
+ now: bool = False
263
+ lease: str | None = None
264
+
265
+ def to_dict(self) -> dict[str, Any]:
266
+ """Return the wire form."""
267
+ return {
268
+ "id": self.id,
269
+ "kind": self.kind,
270
+ "targets": list(self.targets),
271
+ "reason": self.reason,
272
+ "by": dict(self.by),
273
+ "started_at": self.started_at,
274
+ "deadline": self.deadline,
275
+ "expires_at": self.expires_at,
276
+ "affected": {"pids": None if self.affected_pids is None else list(self.affected_pids)},
277
+ "wait_for": self.wait_for,
278
+ "now": self.now,
279
+ "lease": self.lease,
280
+ }
281
+
282
+ @classmethod
283
+ def from_dict(cls, d: dict[str, Any]) -> Op:
284
+ """Build an op from its wire form; missing optional fields get defaults. Raises ``SvcError("invalid")``."""
285
+ d = _need_dict(d, "op")
286
+ targets = d.get("targets", [])
287
+ if not isinstance(targets, list) or not all(isinstance(t, str) for t in targets):
288
+ raise SvcError("invalid", "op.targets must be a list of strings")
289
+ affected = d.get("affected") or {}
290
+ if not isinstance(affected, dict):
291
+ raise SvcError("invalid", "op.affected must be an object")
292
+ pids = affected.get("pids")
293
+ if pids is not None:
294
+ if not isinstance(pids, list) or not all(isinstance(p, int) and not isinstance(p, bool) for p in pids):
295
+ raise SvcError("invalid", "op.affected.pids must be a list of integers or null")
296
+ pids = list(pids)
297
+ lease = d.get("lease")
298
+ try:
299
+ return cls(
300
+ id=_need_str(d, "id", "op"),
301
+ kind=_need_str(d, "kind", "op"),
302
+ targets=list(targets),
303
+ reason=str(d.get("reason") or ""),
304
+ by=_opt_dict(d, "by", "op") or {},
305
+ started_at=float(d.get("started_at") or 0.0),
306
+ deadline=float(d.get("deadline") or 0.0),
307
+ expires_at=float(d.get("expires_at") or 0.0),
308
+ affected_pids=pids,
309
+ wait_for=str(d.get("wait_for") or "interrupted"),
310
+ now=bool(d.get("now", False)),
311
+ lease=None if lease is None else str(lease),
312
+ )
313
+ except (TypeError, ValueError) as exc:
314
+ raise SvcError("invalid", f"op has a malformed field: {exc}") from exc
315
+
316
+
317
+ def new_op_id(clock: Callable[[], float] = time.time) -> str:
318
+ """Return a fresh op id ``op-YYYYMMDDTHHMMSS-<4 hex>`` (UTC time from ``clock``, random suffix)."""
319
+ stamp = time.strftime("%Y%m%dT%H%M%S", time.gmtime(clock()))
320
+ return f"op-{stamp}-{secrets.token_hex(2)}"
321
+
322
+
323
+ def matches(value: str, globs: Iterable[str]) -> bool:
324
+ """Return True when ``value`` matches any of the shell-style ``globs`` (case-sensitive fnmatch)."""
325
+ return any(fnmatch.fnmatchcase(value, g) for g in globs)
326
+
327
+
328
+ def load_schema(name: str) -> dict[str, Any]:
329
+ """Load the JSON Schema ``contract/schemas/<name>.json`` shipped with the package (``.json`` optional)."""
330
+ if name.endswith(".json"):
331
+ name = name[: -len(".json")]
332
+ if not _SCHEMA_NAME.match(name):
333
+ raise ValueError(f"bad schema name: {name!r}")
334
+ res = importlib.resources.files("cli_svckit.contract").joinpath("schemas").joinpath(f"{name}.json")
335
+ if not res.is_file():
336
+ raise FileNotFoundError(f"no svckit schema named {name!r}")
337
+ data: dict[str, Any] = json.loads(res.read_text(encoding="utf-8"))
338
+ return data
@@ -0,0 +1,126 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://cli-svckit.example/schema/1/complete.json",
4
+ "title": "complete",
5
+ "description": "Params and result of `svc complete`. Unknown fields are allowed everywhere (must-ignore).",
6
+ "$defs": {
7
+ "target": {
8
+ "type": "object",
9
+ "properties": {
10
+ "old_pid": {
11
+ "type": [
12
+ "integer",
13
+ "null"
14
+ ]
15
+ },
16
+ "new_pid": {
17
+ "type": [
18
+ "integer",
19
+ "null"
20
+ ]
21
+ },
22
+ "old_version": {
23
+ "type": [
24
+ "string",
25
+ "null"
26
+ ]
27
+ },
28
+ "new_version": {
29
+ "type": [
30
+ "string",
31
+ "null"
32
+ ]
33
+ },
34
+ "healthy": {
35
+ "type": [
36
+ "boolean",
37
+ "null"
38
+ ]
39
+ },
40
+ "restarted": {
41
+ "type": "boolean"
42
+ }
43
+ },
44
+ "required": [
45
+ "restarted"
46
+ ]
47
+ },
48
+ "facts": {
49
+ "type": "object",
50
+ "properties": {
51
+ "targets": {
52
+ "type": "object",
53
+ "additionalProperties": {
54
+ "$ref": "#/$defs/target"
55
+ }
56
+ },
57
+ "duration_s": {
58
+ "type": "number"
59
+ },
60
+ "waited_s": {
61
+ "type": "number"
62
+ },
63
+ "capped": {
64
+ "type": "boolean"
65
+ },
66
+ "forced_now": {
67
+ "type": "boolean"
68
+ }
69
+ },
70
+ "required": [
71
+ "targets",
72
+ "duration_s",
73
+ "waited_s",
74
+ "capped",
75
+ "forced_now"
76
+ ]
77
+ },
78
+ "params": {
79
+ "type": "object",
80
+ "properties": {
81
+ "op": {
82
+ "$ref": "lease.json#/$defs/op"
83
+ },
84
+ "outcome": {
85
+ "enum": [
86
+ "ok",
87
+ "failed",
88
+ "partial",
89
+ "aborted"
90
+ ]
91
+ },
92
+ "error": {
93
+ "type": "string"
94
+ },
95
+ "facts": {
96
+ "$ref": "#/$defs/facts"
97
+ }
98
+ },
99
+ "required": [
100
+ "op",
101
+ "outcome",
102
+ "facts"
103
+ ]
104
+ },
105
+ "result": {
106
+ "type": "object",
107
+ "properties": {
108
+ "state": {
109
+ "enum": [
110
+ "resumed",
111
+ "recovering"
112
+ ]
113
+ },
114
+ "actions": {
115
+ "type": "array",
116
+ "items": {
117
+ "type": "string"
118
+ }
119
+ }
120
+ },
121
+ "required": [
122
+ "state"
123
+ ]
124
+ }
125
+ }
126
+ }
@@ -0,0 +1,137 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://cli-svckit.example/schema/1/describe.json",
4
+ "title": "describe",
5
+ "description": "Result of `svc describe`: who the tool is and what it supports. Unknown fields are allowed everywhere (must-ignore).",
6
+ "$defs": {
7
+ "params": {
8
+ "type": "object"
9
+ },
10
+ "result": {
11
+ "type": "object",
12
+ "properties": {
13
+ "tool": {
14
+ "type": "object",
15
+ "properties": {
16
+ "name": {
17
+ "type": "string"
18
+ },
19
+ "version": {
20
+ "type": "string"
21
+ }
22
+ },
23
+ "required": [
24
+ "name",
25
+ "version"
26
+ ]
27
+ },
28
+ "contract": {
29
+ "type": "object",
30
+ "properties": {
31
+ "min": {
32
+ "type": "string",
33
+ "pattern": "^[0-9]+\\.[0-9]+$"
34
+ },
35
+ "max": {
36
+ "type": "string",
37
+ "pattern": "^[0-9]+\\.[0-9]+$"
38
+ }
39
+ },
40
+ "required": [
41
+ "min",
42
+ "max"
43
+ ]
44
+ },
45
+ "methods": {
46
+ "type": "array",
47
+ "items": {
48
+ "type": "string"
49
+ }
50
+ },
51
+ "services": {
52
+ "type": "array",
53
+ "items": {
54
+ "type": "object"
55
+ }
56
+ },
57
+ "coordination": {
58
+ "type": "object",
59
+ "properties": {
60
+ "kinds": {
61
+ "type": "array",
62
+ "items": {
63
+ "type": "string"
64
+ }
65
+ },
66
+ "services": {
67
+ "type": "array",
68
+ "items": {
69
+ "type": "string"
70
+ }
71
+ },
72
+ "phases": {
73
+ "type": "array",
74
+ "items": {
75
+ "enum": [
76
+ "prepare",
77
+ "complete"
78
+ ]
79
+ }
80
+ },
81
+ "prepare_timeout_s": {
82
+ "type": "integer",
83
+ "minimum": 0
84
+ },
85
+ "complete_timeout_s": {
86
+ "type": "integer",
87
+ "minimum": 0
88
+ },
89
+ "watches_lease": {
90
+ "type": "boolean"
91
+ }
92
+ },
93
+ "required": [
94
+ "kinds",
95
+ "services",
96
+ "phases",
97
+ "prepare_timeout_s",
98
+ "complete_timeout_s",
99
+ "watches_lease"
100
+ ]
101
+ },
102
+ "doctor": {
103
+ "type": "object",
104
+ "properties": {
105
+ "checks": {
106
+ "type": "array",
107
+ "items": {
108
+ "type": "object",
109
+ "properties": {
110
+ "id": {
111
+ "type": "string"
112
+ },
113
+ "title": {
114
+ "type": "string"
115
+ }
116
+ },
117
+ "required": [
118
+ "id",
119
+ "title"
120
+ ]
121
+ }
122
+ }
123
+ },
124
+ "required": [
125
+ "checks"
126
+ ]
127
+ }
128
+ },
129
+ "required": [
130
+ "tool",
131
+ "contract",
132
+ "methods",
133
+ "services"
134
+ ]
135
+ }
136
+ }
137
+ }
@@ -0,0 +1,87 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://cli-svckit.example/schema/1/doctor.json",
4
+ "title": "doctor",
5
+ "description": "Params and result of `svc doctor`. Unknown fields are allowed everywhere (must-ignore).",
6
+ "$defs": {
7
+ "params": {
8
+ "type": "object",
9
+ "properties": {
10
+ "fix": {
11
+ "type": "boolean"
12
+ },
13
+ "deep": {
14
+ "type": "boolean"
15
+ }
16
+ },
17
+ "required": [
18
+ "fix",
19
+ "deep"
20
+ ]
21
+ },
22
+ "check": {
23
+ "type": "object",
24
+ "properties": {
25
+ "id": {
26
+ "type": "string"
27
+ },
28
+ "area": {
29
+ "type": "string"
30
+ },
31
+ "status": {
32
+ "enum": [
33
+ "ok",
34
+ "warn",
35
+ "fail",
36
+ "skip"
37
+ ]
38
+ },
39
+ "detail": {
40
+ "type": "string"
41
+ },
42
+ "fix": {
43
+ "type": "object",
44
+ "properties": {
45
+ "argv": {
46
+ "type": "array",
47
+ "items": {
48
+ "type": "string"
49
+ }
50
+ },
51
+ "hint": {
52
+ "type": "string"
53
+ }
54
+ }
55
+ }
56
+ },
57
+ "required": [
58
+ "id",
59
+ "area",
60
+ "status",
61
+ "detail"
62
+ ]
63
+ },
64
+ "result": {
65
+ "type": "object",
66
+ "properties": {
67
+ "status": {
68
+ "enum": [
69
+ "ok",
70
+ "warn",
71
+ "fail"
72
+ ]
73
+ },
74
+ "checks": {
75
+ "type": "array",
76
+ "items": {
77
+ "$ref": "#/$defs/check"
78
+ }
79
+ }
80
+ },
81
+ "required": [
82
+ "status",
83
+ "checks"
84
+ ]
85
+ }
86
+ }
87
+ }