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,133 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://cli-svckit.example/schema/1/envelope.json",
4
+ "title": "svckit envelope",
5
+ "description": "Request (stdin) and response (last JSON line of stdout). Unknown fields are allowed everywhere (must-ignore).",
6
+ "$defs": {
7
+ "request": {
8
+ "type": "object",
9
+ "properties": {
10
+ "svckit": {
11
+ "type": "string",
12
+ "pattern": "^[0-9]+\\.[0-9]+$"
13
+ },
14
+ "id": {
15
+ "type": "string"
16
+ },
17
+ "method": {
18
+ "type": "string",
19
+ "description": "describe|health|doctor|install|uninstall|prepare|complete"
20
+ },
21
+ "caller": {
22
+ "type": [
23
+ "object",
24
+ "null"
25
+ ]
26
+ },
27
+ "deadline_ms": {
28
+ "type": [
29
+ "integer",
30
+ "null"
31
+ ],
32
+ "minimum": 0
33
+ },
34
+ "params": {
35
+ "type": "object"
36
+ }
37
+ },
38
+ "required": [
39
+ "svckit",
40
+ "id",
41
+ "method",
42
+ "params"
43
+ ]
44
+ },
45
+ "error": {
46
+ "type": "object",
47
+ "properties": {
48
+ "code": {
49
+ "enum": [
50
+ "unsupported",
51
+ "invalid",
52
+ "forbidden",
53
+ "requires_root",
54
+ "timeout",
55
+ "internal",
56
+ "incompatible"
57
+ ]
58
+ },
59
+ "message": {
60
+ "type": "string"
61
+ },
62
+ "retry_after_s": {
63
+ "type": [
64
+ "number",
65
+ "null"
66
+ ],
67
+ "minimum": 0
68
+ },
69
+ "data": {
70
+ "type": [
71
+ "object",
72
+ "null"
73
+ ]
74
+ }
75
+ },
76
+ "required": [
77
+ "code",
78
+ "message"
79
+ ]
80
+ },
81
+ "response": {
82
+ "type": "object",
83
+ "properties": {
84
+ "svckit": {
85
+ "type": "string",
86
+ "pattern": "^[0-9]+\\.[0-9]+$"
87
+ },
88
+ "id": {
89
+ "type": "string"
90
+ },
91
+ "ok": {
92
+ "type": "boolean"
93
+ },
94
+ "result": {
95
+ "type": [
96
+ "object",
97
+ "null"
98
+ ]
99
+ },
100
+ "error": {
101
+ "$ref": "#/$defs/error"
102
+ }
103
+ },
104
+ "required": [
105
+ "svckit",
106
+ "id",
107
+ "ok"
108
+ ],
109
+ "if": {
110
+ "properties": {
111
+ "ok": {
112
+ "const": true
113
+ }
114
+ }
115
+ },
116
+ "then": {
117
+ "required": [
118
+ "result"
119
+ ],
120
+ "properties": {
121
+ "result": {
122
+ "type": "object"
123
+ }
124
+ }
125
+ },
126
+ "else": {
127
+ "required": [
128
+ "error"
129
+ ]
130
+ }
131
+ }
132
+ }
133
+ }
@@ -0,0 +1,75 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://cli-svckit.example/schema/1/health.json",
4
+ "title": "health",
5
+ "description": "Result of `svc health` (IETF health-check draft style). Unknown fields are allowed everywhere (must-ignore).",
6
+ "$defs": {
7
+ "params": {
8
+ "type": "object"
9
+ },
10
+ "check": {
11
+ "type": "object",
12
+ "properties": {
13
+ "status": {
14
+ "enum": [
15
+ "pass",
16
+ "warn",
17
+ "fail"
18
+ ]
19
+ },
20
+ "observedValue": {},
21
+ "observedUnit": {
22
+ "type": "string"
23
+ },
24
+ "output": {
25
+ "type": "string"
26
+ }
27
+ },
28
+ "required": [
29
+ "status"
30
+ ]
31
+ },
32
+ "result": {
33
+ "type": "object",
34
+ "properties": {
35
+ "status": {
36
+ "enum": [
37
+ "pass",
38
+ "warn",
39
+ "fail"
40
+ ]
41
+ },
42
+ "live": {
43
+ "type": "boolean"
44
+ },
45
+ "ready": {
46
+ "type": "boolean"
47
+ },
48
+ "version": {
49
+ "type": "string"
50
+ },
51
+ "output": {
52
+ "type": "string"
53
+ },
54
+ "checks": {
55
+ "type": "object",
56
+ "propertyNames": {
57
+ "pattern": "^[^:]+(:[^:]+)?$"
58
+ },
59
+ "additionalProperties": {
60
+ "type": "array",
61
+ "items": {
62
+ "$ref": "#/$defs/check"
63
+ }
64
+ }
65
+ }
66
+ },
67
+ "required": [
68
+ "status",
69
+ "live",
70
+ "ready",
71
+ "checks"
72
+ ]
73
+ }
74
+ }
75
+ }
@@ -0,0 +1,102 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://cli-svckit.example/schema/1/install.json",
4
+ "title": "install / uninstall",
5
+ "description": "Params and result of `svc install` and `svc uninstall`. Unknown fields are allowed everywhere (must-ignore).",
6
+ "$defs": {
7
+ "params": {
8
+ "type": "object",
9
+ "properties": {
10
+ "dry_run": {
11
+ "type": "boolean"
12
+ },
13
+ "confirm": {
14
+ "type": "boolean"
15
+ },
16
+ "scope": {
17
+ "enum": [
18
+ "cli",
19
+ "state",
20
+ "all"
21
+ ]
22
+ },
23
+ "overrides": {
24
+ "type": "object"
25
+ }
26
+ },
27
+ "required": [
28
+ "dry_run",
29
+ "confirm",
30
+ "scope"
31
+ ]
32
+ },
33
+ "action": {
34
+ "type": "object",
35
+ "properties": {
36
+ "op": {
37
+ "enum": [
38
+ "write",
39
+ "remove",
40
+ "link",
41
+ "rc_line",
42
+ "launchctl"
43
+ ]
44
+ },
45
+ "path": {
46
+ "type": "string"
47
+ },
48
+ "sha256": {
49
+ "type": "string",
50
+ "pattern": "^[0-9a-f]{64}$"
51
+ },
52
+ "argv": {
53
+ "type": "array",
54
+ "items": {
55
+ "type": "string"
56
+ }
57
+ },
58
+ "line": {
59
+ "type": "string"
60
+ }
61
+ },
62
+ "required": [
63
+ "op"
64
+ ]
65
+ },
66
+ "result": {
67
+ "type": "object",
68
+ "properties": {
69
+ "changed": {
70
+ "type": "boolean"
71
+ },
72
+ "actions": {
73
+ "type": "array",
74
+ "items": {
75
+ "$ref": "#/$defs/action"
76
+ }
77
+ },
78
+ "requires_root": {
79
+ "type": "object",
80
+ "properties": {
81
+ "argv": {
82
+ "type": "array",
83
+ "items": {
84
+ "type": "string"
85
+ }
86
+ }
87
+ },
88
+ "required": [
89
+ "argv"
90
+ ]
91
+ },
92
+ "receipts": {
93
+ "type": "string"
94
+ }
95
+ },
96
+ "required": [
97
+ "changed",
98
+ "actions"
99
+ ]
100
+ }
101
+ }
102
+ }
@@ -0,0 +1,114 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://cli-svckit.example/schema/1/lease.json",
4
+ "title": "lease file",
5
+ "description": "A lease file in the lease directory (and its `done/` tombstone); `$defs/op` is the operation record used by prepare/complete. Unknown fields are allowed everywhere (must-ignore).",
6
+ "type": "object",
7
+ "properties": {
8
+ "v": {
9
+ "const": 1
10
+ },
11
+ "op": {
12
+ "$ref": "#/$defs/op"
13
+ },
14
+ "phase": {
15
+ "enum": [
16
+ "prepare",
17
+ "running",
18
+ "complete"
19
+ ]
20
+ },
21
+ "phase_at": {
22
+ "type": "number"
23
+ },
24
+ "outcome": {
25
+ "type": [
26
+ "string",
27
+ "null"
28
+ ]
29
+ },
30
+ "facts": {
31
+ "type": [
32
+ "object",
33
+ "null"
34
+ ]
35
+ },
36
+ "owner_uid": {
37
+ "type": "integer",
38
+ "minimum": 0
39
+ }
40
+ },
41
+ "required": [
42
+ "v",
43
+ "op",
44
+ "phase",
45
+ "phase_at",
46
+ "owner_uid"
47
+ ],
48
+ "$defs": {
49
+ "op": {
50
+ "type": "object",
51
+ "properties": {
52
+ "id": {
53
+ "type": "string",
54
+ "pattern": "^op-"
55
+ },
56
+ "kind": {
57
+ "type": "string"
58
+ },
59
+ "targets": {
60
+ "type": "array",
61
+ "items": {
62
+ "type": "string"
63
+ }
64
+ },
65
+ "reason": {
66
+ "type": "string"
67
+ },
68
+ "by": {
69
+ "type": "object"
70
+ },
71
+ "started_at": {
72
+ "type": "number"
73
+ },
74
+ "deadline": {
75
+ "type": "number"
76
+ },
77
+ "expires_at": {
78
+ "type": "number"
79
+ },
80
+ "affected": {
81
+ "type": "object",
82
+ "properties": {
83
+ "pids": {
84
+ "type": [
85
+ "array",
86
+ "null"
87
+ ],
88
+ "items": {
89
+ "type": "integer"
90
+ }
91
+ }
92
+ }
93
+ },
94
+ "wait_for": {
95
+ "type": "string"
96
+ },
97
+ "now": {
98
+ "type": "boolean"
99
+ },
100
+ "lease": {
101
+ "type": [
102
+ "string",
103
+ "null"
104
+ ]
105
+ }
106
+ },
107
+ "required": [
108
+ "id",
109
+ "kind",
110
+ "targets"
111
+ ]
112
+ }
113
+ }
114
+ }
@@ -0,0 +1,89 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://cli-svckit.example/schema/1/prepare.json",
4
+ "title": "prepare",
5
+ "description": "Params and result of `svc prepare`. `busy` is a result, never an error. Unknown fields are allowed everywhere (must-ignore).",
6
+ "$defs": {
7
+ "params": {
8
+ "type": "object",
9
+ "properties": {
10
+ "op": {
11
+ "$ref": "lease.json#/$defs/op"
12
+ },
13
+ "poll": {
14
+ "type": "integer",
15
+ "minimum": 0
16
+ }
17
+ },
18
+ "required": [
19
+ "op",
20
+ "poll"
21
+ ]
22
+ },
23
+ "in_flight": {
24
+ "type": "object",
25
+ "properties": {
26
+ "id": {
27
+ "type": "string"
28
+ },
29
+ "kind": {
30
+ "type": "string"
31
+ },
32
+ "what": {
33
+ "type": "string"
34
+ },
35
+ "pid": {
36
+ "type": "integer"
37
+ },
38
+ "since": {
39
+ "type": "number"
40
+ },
41
+ "interrupted": {
42
+ "type": "boolean"
43
+ }
44
+ },
45
+ "required": [
46
+ "id",
47
+ "kind",
48
+ "what",
49
+ "interrupted"
50
+ ]
51
+ },
52
+ "result": {
53
+ "type": "object",
54
+ "properties": {
55
+ "state": {
56
+ "enum": [
57
+ "ready",
58
+ "busy"
59
+ ]
60
+ },
61
+ "op_id": {
62
+ "type": "string"
63
+ },
64
+ "quiesced": {
65
+ "type": "boolean"
66
+ },
67
+ "eta_s": {
68
+ "type": "number",
69
+ "minimum": 0
70
+ },
71
+ "reason": {
72
+ "type": "string"
73
+ },
74
+ "in_flight": {
75
+ "type": "array",
76
+ "items": {
77
+ "$ref": "#/$defs/in_flight"
78
+ }
79
+ }
80
+ },
81
+ "required": [
82
+ "state",
83
+ "op_id",
84
+ "quiesced",
85
+ "in_flight"
86
+ ]
87
+ }
88
+ }
89
+ }
@@ -0,0 +1,165 @@
1
+ """Participant side of the svckit contract: turn a request into one JSON response line and an exit code.
2
+
3
+ A *provider* is any object with optional methods named after :data:`~cli_svckit.contract.envelope.METHODS`
4
+ (``describe``, ``health``, ...). Each takes ``params: dict`` and returns a result dict, raising
5
+ :class:`~cli_svckit.contract.envelope.SvcError` to report a contract error.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import sys
12
+ import traceback
13
+ from typing import Any, TextIO
14
+
15
+ from cli_svckit.contract.envelope import (
16
+ CONTRACT_VERSION,
17
+ EXIT_BUSY,
18
+ EXIT_FAIL,
19
+ EXIT_OK,
20
+ EXIT_TEMPFAIL,
21
+ EXIT_USAGE,
22
+ EXIT_WARN,
23
+ METHODS,
24
+ Error,
25
+ Request,
26
+ Response,
27
+ SvcError,
28
+ redact,
29
+ )
30
+
31
+
32
+ def implemented_methods(provider: Any) -> list[str]:
33
+ """Return the contract methods the provider implements (callable attributes named as in METHODS)."""
34
+ return [m for m in METHODS if callable(getattr(provider, m, None))]
35
+
36
+
37
+ def _major(version: Any) -> str:
38
+ return str(version).split(".", 1)[0]
39
+
40
+
41
+ def _parse_request(method: str, request_text: str) -> Request:
42
+ text = request_text.strip()
43
+ if not text:
44
+ return Request(method=method, params={}, id="")
45
+ try:
46
+ obj = json.loads(text)
47
+ except ValueError as exc:
48
+ raise SvcError("invalid", f"request is not valid JSON: {exc}") from exc
49
+ if not isinstance(obj, dict):
50
+ raise SvcError("invalid", "request must be a JSON object")
51
+ version = obj.get("svckit")
52
+ if version is not None and _major(version) != _major(CONTRACT_VERSION):
53
+ raise SvcError("incompatible", f"unsupported svckit version {version!r}; this server speaks {CONTRACT_VERSION}")
54
+ obj = dict(obj)
55
+ obj.setdefault("method", method)
56
+ req = Request.from_dict(obj)
57
+ req.method = method # the command line decides which method runs
58
+ return req
59
+
60
+
61
+ def _rc_for_result(method: str, result: dict[str, Any]) -> int:
62
+ if method == "prepare" and result.get("state") == "busy":
63
+ return EXIT_BUSY
64
+ if method in ("health", "doctor"):
65
+ status = result.get("status")
66
+ if status == "warn":
67
+ return EXIT_WARN
68
+ if status == "fail":
69
+ return EXIT_FAIL
70
+ return EXIT_OK
71
+
72
+
73
+ def _rc_for_error(error: Error) -> int:
74
+ return EXIT_TEMPFAIL if error.code == "timeout" else EXIT_FAIL
75
+
76
+
77
+ def _fill_describe(provider: Any, result: dict[str, Any]) -> dict[str, Any]:
78
+ out = dict(result)
79
+ contract = out.get("contract")
80
+ if not isinstance(contract, dict):
81
+ contract = {}
82
+ out["contract"] = {"min": "1.0", "max": "1.0", **contract}
83
+ if "methods" not in out:
84
+ out["methods"] = implemented_methods(provider)
85
+ return out
86
+
87
+
88
+ def dispatch(provider: Any, method: str, request_text: str) -> tuple[str, int]:
89
+ """Run ``method`` on ``provider`` for the request text; return ``(one JSON line, exit code)``.
90
+
91
+ Empty text means a request with empty params. Bad JSON gives ``invalid``, a different svckit major gives
92
+ ``incompatible``, a method the provider lacks gives ``unsupported`` and any other exception gives ``internal``
93
+ (the traceback goes to stderr only). Results are redacted before output.
94
+ """
95
+ rid = ""
96
+ try:
97
+ req = _parse_request(method, request_text)
98
+ rid = req.id
99
+ if method not in METHODS or not callable(getattr(provider, method, None)):
100
+ raise SvcError("unsupported", f"method {method!r} is not supported")
101
+ result = getattr(provider, method)(req.params)
102
+ if not isinstance(result, dict):
103
+ raise SvcError("internal", f"{method} returned {type(result).__name__}, expected an object")
104
+ if method == "describe":
105
+ result = _fill_describe(provider, result)
106
+ result = redact(result)
107
+ return Response(id=rid, ok=True, result=result).to_json(), _rc_for_result(method, result)
108
+ except SvcError as exc:
109
+ err = exc.to_error()
110
+ except Exception as exc: # noqa: BLE001 - any provider failure becomes an `internal` error
111
+ traceback.print_exc(file=sys.stderr)
112
+ err = Error(code="internal", message=f"{type(exc).__name__}: {exc}")
113
+ if err.data is not None:
114
+ err.data = redact(err.data)
115
+ return Response(id=rid, ok=False, error=err).to_json(), _rc_for_error(err)
116
+
117
+
118
+ def run(
119
+ provider: Any,
120
+ argv: list[str] | None = None,
121
+ stdin: TextIO | None = None,
122
+ stdout: TextIO | None = None,
123
+ ) -> int:
124
+ """Handle ``<method> [--json] [--request-file PATH]`` (argv without the ``svc`` word); return the exit code.
125
+
126
+ The request is read from the file, or from stdin when it is not a terminal. Exactly one JSON line is written
127
+ to stdout (pretty-printed when ``--json`` is absent).
128
+ """
129
+ import argparse
130
+
131
+ stdin = stdin if stdin is not None else sys.stdin
132
+ stdout = stdout if stdout is not None else sys.stdout
133
+ parser = argparse.ArgumentParser(prog="svc", description="svckit contract entry point")
134
+ parser.add_argument("method", help="one of: " + ", ".join(METHODS))
135
+ parser.add_argument("--json", action="store_true", dest="as_json", help="print one JSON line")
136
+ parser.add_argument("--request-file", default=None, help="read the request from this file")
137
+ try:
138
+ ns = parser.parse_args(argv)
139
+ except SystemExit as exc:
140
+ return EXIT_USAGE if exc.code not in (0, None) else EXIT_OK
141
+
142
+ text = ""
143
+ if ns.request_file:
144
+ try:
145
+ with open(ns.request_file, encoding="utf-8") as fh:
146
+ text = fh.read()
147
+ except OSError as exc:
148
+ line = Response(id="", ok=False, error=Error("invalid", f"cannot read request file: {exc}")).to_json()
149
+ stdout.write((line if ns.as_json else _pretty(line)) + "\n")
150
+ return EXIT_FAIL
151
+ elif not _is_tty(stdin):
152
+ text = stdin.read()
153
+
154
+ line, rc = dispatch(provider, ns.method, text)
155
+ stdout.write((line if ns.as_json else _pretty(line)) + "\n")
156
+ return rc
157
+
158
+
159
+ def _is_tty(stream: Any) -> bool:
160
+ isatty = getattr(stream, "isatty", None)
161
+ return bool(isatty()) if callable(isatty) else False
162
+
163
+
164
+ def _pretty(line: str) -> str:
165
+ return json.dumps(json.loads(line), indent=2, sort_keys=False)