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,36 @@
1
+ """Typer adapter: a ready-made ``svc`` command group (needs the optional ``typer`` extra)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from cli_svckit.contract.server import implemented_methods, run
8
+
9
+
10
+ def make_svc_app(provider: Any) -> Any:
11
+ """Return a ``typer.Typer`` with one command per method the provider implements.
12
+
13
+ Each command takes ``--json`` and ``--request-file`` and exits with the contract exit code.
14
+ """
15
+ import typer
16
+
17
+ app = typer.Typer(help="svckit contract commands", add_completion=False, no_args_is_help=True)
18
+
19
+ def make(method: str) -> None:
20
+ def command(
21
+ json_out: bool = typer.Option(False, "--json", help="print one JSON line"),
22
+ request_file: str | None = typer.Option(None, "--request-file", help="read the request from this file"),
23
+ ) -> None:
24
+ argv = [method]
25
+ if json_out:
26
+ argv.append("--json")
27
+ if request_file:
28
+ argv += ["--request-file", request_file]
29
+ rc = run(provider, argv)
30
+ raise typer.Exit(rc)
31
+
32
+ app.command(name=method, help=f"svc {method}")(command)
33
+
34
+ for method in implemented_methods(provider):
35
+ make(method)
36
+ return app
@@ -0,0 +1 @@
1
+ """Coordination primitives: lease directory, participant helpers, watcher and controller (one module each)."""
@@ -0,0 +1,353 @@
1
+ """Controller side of lease coordination: announce an operation, wait for participants to quiesce, then resume them.
2
+
3
+ An :class:`Operation` is a context manager. Entering it writes a lease (so participant daemons see it), asks every
4
+ relevant participant to ``prepare`` until all are ready (or a cap is hit), and moves the lease to ``running``.
5
+ Leaving it tells the participants ``complete`` and tombstones the lease.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import time
11
+ from collections.abc import Callable
12
+ from dataclasses import dataclass, field
13
+ from typing import Any
14
+
15
+ from cli_svckit.contract.client import CallResult
16
+ from cli_svckit.contract.envelope import Error, Op, SvcError, matches, new_op_id
17
+ from cli_svckit.coord.lease import LeaseDir
18
+
19
+ __all__ = ["Operation", "OperationAborted", "PrepareReport"]
20
+
21
+
22
+ class OperationAborted(Exception):
23
+ """Raised when participants did not become ready in time and the operation was told to abort at the cap."""
24
+
25
+ def __init__(self, message: str, report: PrepareReport | None = None) -> None:
26
+ super().__init__(message)
27
+ self.report = report
28
+
29
+
30
+ @dataclass
31
+ class PrepareReport:
32
+ """Outcome of the prepare phase: ``ready`` to go on, ``capped`` (cap reached), ``forced_now``, and who was busy."""
33
+
34
+ ready: bool
35
+ capped: bool = False
36
+ forced_now: bool = False
37
+ waited_s: float = 0.0
38
+ busy: dict[str, dict[str, Any]] = field(default_factory=dict)
39
+ errors: dict[str, Error] = field(default_factory=dict)
40
+
41
+
42
+ class Operation:
43
+ """One controller operation (restart, update, ...) coordinated with participants through a lease directory.
44
+
45
+ ``max_wait_s`` is how long to wait for participants, ``margin_s`` extra time before the lease counts as stale,
46
+ ``poll_s`` the pause between prepare polls. ``on_cap`` is ``"proceed"`` (go on anyway) or ``"abort"``. ``now``
47
+ asks for one prepare call and no waiting. ``mirror(event, op)`` is called with ``"start"``/``"end"`` (for legacy
48
+ drain files). ``say`` receives progress lines. ``facts`` is a dict the caller fills; it is stored on the lease.
49
+ """
50
+
51
+ def __init__(
52
+ self,
53
+ kind: str,
54
+ targets: list[str],
55
+ *,
56
+ lease_dir: LeaseDir,
57
+ participants: list[Any],
58
+ max_wait_s: float = 900.0,
59
+ margin_s: float = 1200.0,
60
+ poll_s: float = 15.0,
61
+ now: bool = False,
62
+ reason: str = "",
63
+ by: dict[str, Any] | None = None,
64
+ affected_pids: list[int] | None = None,
65
+ wait_for: str = "interrupted",
66
+ on_cap: str = "proceed",
67
+ op_id: str | None = None,
68
+ describe_cache: Any = None,
69
+ mirror: Callable[[str, Op], None] | None = None,
70
+ say: Callable[[str], None] = print,
71
+ clock: Callable[[], float] = time.time,
72
+ sleep: Callable[[float], None] = time.sleep,
73
+ ) -> None:
74
+ if on_cap not in ("proceed", "abort"):
75
+ raise SvcError("invalid", "on_cap must be 'proceed' or 'abort'")
76
+ self.kind = kind
77
+ self.targets = list(targets)
78
+ self.lease_dir = lease_dir
79
+ self.participants = list(participants)
80
+ self.max_wait_s = max_wait_s
81
+ self.margin_s = margin_s
82
+ self.poll_s = poll_s
83
+ self.now = now
84
+ self.reason = reason
85
+ self.by = dict(by or {})
86
+ self.affected_pids = None if affected_pids is None else list(affected_pids)
87
+ self.wait_for = wait_for
88
+ self.on_cap = on_cap
89
+ self.op_id = op_id
90
+ self.describe_cache = describe_cache
91
+ self.mirror = mirror
92
+ self.say = say
93
+ self.clock = clock
94
+ self.sleep = sleep
95
+ self.facts: dict[str, Any] = {}
96
+ self.op: Op | None = None
97
+ self.report: PrepareReport | None = None
98
+ self._relevant: list[Any] | None = None
99
+ self._polls = 0
100
+ self._started = False
101
+ self._finished = False
102
+ self._said: set[str] = set()
103
+
104
+ # -- relevance ---------------------------------------------------------------------------------------
105
+
106
+ def _say_once(self, line: str) -> None:
107
+ if line not in self._said:
108
+ self._said.add(line)
109
+ self.say(line)
110
+
111
+ def relevant(self) -> list[Any]:
112
+ """Return the participants whose ``coordination`` covers this kind and any target (computed once).
113
+
114
+ No coordination means not relevant. A participant whose describe fails is relevant only with
115
+ ``fail_policy == "closed"`` (a note is printed once).
116
+ """
117
+ if self._relevant is not None:
118
+ return self._relevant
119
+ found: list[Any] = []
120
+ for p in self.participants:
121
+ desc = p.describe(self.describe_cache)
122
+ if desc is None:
123
+ if p.fail_policy == "closed":
124
+ self._say_once(f"{p.name}: describe failed; treating as relevant (fail closed)")
125
+ found.append(p)
126
+ else:
127
+ self._say_once(f"{p.name}: describe failed; skipping (fail open)")
128
+ continue
129
+ coord = desc.get("coordination") if isinstance(desc, dict) else None
130
+ if not isinstance(coord, dict):
131
+ continue
132
+ kinds = [str(k) for k in coord.get("kinds") or []]
133
+ services = [str(s) for s in coord.get("services") or []]
134
+ if not matches(self.kind, kinds):
135
+ continue
136
+ if services and not any(matches(t, services) for t in self.targets):
137
+ continue
138
+ found.append(p)
139
+ self._relevant = found
140
+ return found
141
+
142
+ # -- lifecycle ---------------------------------------------------------------------------------------
143
+
144
+ def start(self) -> Op:
145
+ """Build the op and write its lease (phase prepare) before any prepare call; then call ``mirror("start")``.
146
+
147
+ When ``op_id`` names an existing active lease, that lease's op is reused instead.
148
+ """
149
+ if self.op is not None:
150
+ return self.op
151
+ existing = self.lease_dir.get(self.op_id) if self.op_id else None
152
+ if existing is not None and existing.phase != "complete" and existing.is_active(self.clock()):
153
+ self.op = existing.op
154
+ self._started = True
155
+ return self.op
156
+ started = self.clock()
157
+ op = Op(
158
+ id=self.op_id or new_op_id(self.clock),
159
+ kind=self.kind,
160
+ targets=list(self.targets),
161
+ reason=self.reason,
162
+ by=dict(self.by),
163
+ started_at=started,
164
+ deadline=started + self.max_wait_s,
165
+ expires_at=started + self.max_wait_s + self.margin_s,
166
+ affected_pids=self.affected_pids,
167
+ wait_for=self.wait_for,
168
+ now=self.now,
169
+ )
170
+ self.lease_dir.ensure()
171
+ self.lease_dir.create(op, "prepare")
172
+ self.op = op
173
+ self.op_id = op.id
174
+ self._started = True
175
+ if self.mirror is not None:
176
+ self.mirror("start", op)
177
+ return op
178
+
179
+ def _poll(self, op: Op, poll: int) -> PrepareReport:
180
+ """Call ``prepare`` once on every relevant participant and sum up who is still blocking."""
181
+ report = PrepareReport(ready=True)
182
+ for p in self.relevant():
183
+ result: CallResult = p.call("prepare", {"op": op.to_dict(), "poll": poll})
184
+ if not result.ok and result.error is not None:
185
+ report.errors[p.name] = result.error
186
+ if not self._participant_ready(p, op, result, report):
187
+ report.ready = False
188
+ return report
189
+
190
+ def _participant_ready(self, p: Any, op: Op, result: CallResult, report: PrepareReport) -> bool:
191
+ """Decide whether one participant's answer lets the operation go on (recording busy details)."""
192
+ policy = getattr(p, "fail_policy", "open")
193
+ data: dict[str, Any] | None = None
194
+ if result.ok and result.response is not None:
195
+ data = result.response.result or {}
196
+ if data is None:
197
+ error = result.error
198
+ if error is not None and error.code == "unsupported":
199
+ return True
200
+ return policy != "closed"
201
+ if "state" in data:
202
+ ready = data.get("state") == "ready"
203
+ elif isinstance(data.get("ready"), bool):
204
+ ready = bool(data["ready"])
205
+ else:
206
+ ready = result.rc != 3
207
+ if ready:
208
+ return True
209
+ report.busy[p.name] = data
210
+ wait_all = (getattr(p, "wait_for", "interrupted") == "all") or op.wait_for == "all"
211
+ in_flight = [i for i in data.get("in_flight") or [] if isinstance(i, dict)]
212
+ if wait_all:
213
+ return False
214
+ # Busy only blocks when something in flight would be interrupted by the operation.
215
+ return not any(i.get("interrupted") is True for i in in_flight)
216
+
217
+ def _progress(self, report: PrepareReport) -> None:
218
+ parts: list[str] = []
219
+ count = 0
220
+ for name, data in report.busy.items():
221
+ for item in data.get("in_flight") or []:
222
+ if isinstance(item, dict) and item.get("interrupted") is False and self.wait_for != "all":
223
+ continue
224
+ count += 1
225
+ if isinstance(item, dict):
226
+ parts.append(f"{name}:{item.get('what') or item.get('id') or '?'}")
227
+ detail = ", ".join(parts)
228
+ if report.busy:
229
+ self.say(f"waiting for {count} in flight: {detail}" if count else f"waiting for {', '.join(report.busy)}")
230
+ else:
231
+ self.say("waiting for participants")
232
+
233
+ def prepare(self) -> PrepareReport:
234
+ """Poll relevant participants until all are ready, the cap is hit, or ``now`` forces one call.
235
+
236
+ At the cap, ``on_cap="proceed"`` returns ready with ``capped=True``; ``"abort"`` returns ``ready=False``.
237
+ """
238
+ op = self.start()
239
+ t0 = op.started_at or self.clock()
240
+ if self.now or op.now:
241
+ report = self._poll(op, 0)
242
+ report.ready = True
243
+ report.forced_now = True
244
+ report.waited_s = self.clock() - t0
245
+ self.report = report
246
+ return report
247
+ poll = 0
248
+ while True:
249
+ report = self._poll(op, poll)
250
+ poll += 1
251
+ report.waited_s = self.clock() - t0
252
+ if report.ready:
253
+ break
254
+ if self.clock() >= op.deadline:
255
+ report.capped = True
256
+ report.ready = self.on_cap == "proceed"
257
+ break
258
+ self._progress(report)
259
+ self.sleep(max(0.0, min(self.poll_s, op.deadline - self.clock())))
260
+ self.report = report
261
+ return report
262
+
263
+ def tick(self) -> str:
264
+ """One step for periodic jobs: ``"waiting"``, ``"ready"`` or ``"capped"``.
265
+
266
+ The first tick creates the lease; later ticks (also from another process, via ``op_id``) reuse it. Each tick
267
+ does one prepare poll. On ``ready`` the lease moves to ``running``. ``capped`` means the cap was hit: with
268
+ ``on_cap="proceed"`` the lease moves to ``running`` (``report.ready`` True); with ``"abort"`` it stays in
269
+ ``prepare`` and ``report.ready`` is False.
270
+ """
271
+ op = self.start()
272
+ report = self._poll(op, self._polls)
273
+ self._polls += 1
274
+ report.waited_s = self.clock() - op.started_at
275
+ if report.ready or op.now or self.now:
276
+ report.forced_now = bool(self.now or op.now)
277
+ report.ready = True
278
+ state = "ready"
279
+ elif self.clock() >= op.deadline:
280
+ report.capped = True
281
+ report.ready = self.on_cap == "proceed"
282
+ state = "capped"
283
+ else:
284
+ self.report = report
285
+ return "waiting"
286
+ self.report = report
287
+ if report.ready:
288
+ self.lease_dir.set_phase(op.id, "running")
289
+ return state
290
+
291
+ def __enter__(self) -> Operation:
292
+ try:
293
+ report = self.prepare()
294
+ if not report.ready:
295
+ self._finish("aborted", f"participants not ready after {report.waited_s:.0f}s")
296
+ raise OperationAborted("participants did not become ready before the cap", report)
297
+ assert self.op is not None
298
+ self.lease_dir.set_phase(self.op.id, "running")
299
+ except OperationAborted:
300
+ raise
301
+ except BaseException as e:
302
+ # Python never calls __exit__ when __enter__ fails, so release the lease here.
303
+ if self._started and not self._finished:
304
+ self._finish("aborted", f"{type(e).__name__}: {e}" if str(e) else type(e).__name__)
305
+ raise
306
+ return self
307
+
308
+ def __exit__(self, exc_type: Any, exc: BaseException | None, tb: Any) -> None:
309
+ if exc is not None:
310
+ self._finish("failed", f"{exc_type.__name__}: {exc}" if str(exc) else exc_type.__name__)
311
+ else:
312
+ self._finish("ok", None)
313
+ return None
314
+
315
+ def finish(self, outcome: str = "ok", error: str | None = None) -> None:
316
+ """End the operation (for ``tick`` users): complete participants, tombstone the lease, call mirror."""
317
+ self._finish(outcome, error)
318
+
319
+ def _finish(self, outcome: str, error: str | None) -> None:
320
+ if self._finished or self.op is None:
321
+ return
322
+ self._finished = True
323
+ op = self.op
324
+ report = self.report
325
+ facts = dict(self.facts)
326
+ facts["duration_s"] = self.clock() - op.started_at
327
+ facts["waited_s"] = report.waited_s if report else 0.0
328
+ facts["capped"] = bool(report and report.capped)
329
+ facts["forced_now"] = bool(report and report.forced_now)
330
+ if error:
331
+ facts["error"] = error
332
+ for p in self.relevant():
333
+ try:
334
+ res = p.call("complete", {"op": op.to_dict(), "outcome": outcome, "facts": facts})
335
+ if not res.ok:
336
+ detail = res.error.message if res.error else "failed"
337
+ self.say(f"{p.name}: complete failed: {detail}")
338
+ except Exception as exc: # reported, never raised
339
+ self.say(f"{p.name}: complete raised: {exc}")
340
+ try:
341
+ self.lease_dir.complete(op.id, outcome, facts)
342
+ except SvcError as exc:
343
+ self.say(f"lease complete failed: {exc}")
344
+ if self.mirror is not None:
345
+ try:
346
+ self.mirror("end", op)
347
+ except Exception as exc:
348
+ self.say(f"mirror end failed: {exc}")
349
+
350
+ def run(self, action: Callable[[], dict[str, Any] | None]) -> None:
351
+ """Run ``action`` inside the operation; its returned dict (if any) is merged into ``facts``."""
352
+ with self:
353
+ self.facts.update(action() or {})