variantgate 0.9.0__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.
variantgate/cli.py ADDED
@@ -0,0 +1,242 @@
1
+ """The ``variantgate`` command: ask a person from a shell script or a CI job,
2
+ and let the exit code say whether to go on.
3
+
4
+ Exit codes: 0 approved, 1 not approved, 2 a mistake or an unreachable API,
5
+ 3 approved only with changes: do only the approved version it prints.
6
+ """
7
+
8
+ import argparse
9
+ import contextlib
10
+ import functools
11
+ import json
12
+ import os
13
+ import subprocess
14
+ import sys
15
+ from collections.abc import Mapping
16
+ from dataclasses import dataclass
17
+ from typing import Any, Callable, NoReturn, Optional, cast
18
+
19
+ from .cancel_window import in_cancel_window
20
+ from .client import ApprovalClient
21
+ from .errors import RunStoppedError, VariantGateError, approved_version, describe
22
+ from .types import Decision, Outcome, is_allowed, is_changed
23
+
24
+ APPROVED_EXIT = 0
25
+ NOT_APPROVED_EXIT = 1
26
+ MISTAKE_EXIT = 2
27
+ CHANGED_EXIT = 3
28
+ INTERRUPTED_EXIT = 130
29
+ NOT_FOUND_EXIT = 127
30
+ DEFAULT_TIMEOUT_SECONDS = 15 * 60
31
+
32
+ USAGE = """Usage:
33
+ variantgate ask --action ACTION --summary TEXT [options]
34
+ variantgate run --action ACTION --summary TEXT [options] -- COMMAND [ARGS...]
35
+ variantgate withdraw REQUEST_ID
36
+ variantgate outcome REQUEST_ID succeeded|failed [--note TEXT]
37
+
38
+ Options for ask and run:
39
+ --amount N --currency EUR the money the action would move
40
+ --details JSON facts for the person deciding, as a JSON object
41
+ --agent NAME defaults to $VARIANTGATE_AGENT or "cli"
42
+ --run ID the run (one job or session) it belongs to;
43
+ defaults to $VARIANTGATE_RUN. A person can stop
44
+ a run: then nothing in it is approved
45
+ --timeout SECONDS stop waiting after this long (default: 15 minutes)
46
+ --json print the request as JSON on stdout
47
+
48
+ Reads VARIANTGATE_KEY, and VARIANTGATE_API_URL (default https://api.variantgate.com).
49
+ Exit codes: 0 approved, 1 not approved, 2 mistake or unreachable API,
50
+ 3 approved only with changes: do only the approved version it prints.
51
+ run never runs COMMAND on a changed approval."""
52
+
53
+
54
+ class UsageError(Exception):
55
+ """A mistake in how the command was called."""
56
+
57
+
58
+ @dataclass
59
+ class Io:
60
+ """Everything the command touches outside itself, so tests can stand in."""
61
+
62
+ env: Mapping[str, str]
63
+ stdout: Callable[[str], None]
64
+ stderr: Callable[[str], None]
65
+ run: Callable[[list[str]], int]
66
+ client: Optional[Callable[[str], ApprovalClient]] = None
67
+
68
+
69
+ class _Parser(argparse.ArgumentParser):
70
+ def error(self, message: str) -> NoReturn:
71
+ raise UsageError(message[:1].upper() + message[1:] + ".")
72
+
73
+
74
+ def _parser() -> argparse.ArgumentParser:
75
+ parser = _Parser(prog="variantgate", add_help=False)
76
+ parser.add_argument("verb", nargs="?")
77
+ parser.add_argument("rest", nargs="*")
78
+ for name in ("action", "summary", "amount", "currency", "details", "agent", "note", "run"):
79
+ parser.add_argument(f"--{name}")
80
+ parser.add_argument("--timeout")
81
+ parser.add_argument("--json", action="store_true")
82
+ return parser
83
+
84
+
85
+ def main(argv: list[str], io: Io) -> int:
86
+ """Runs the command and returns the exit code."""
87
+ try:
88
+ return _dispatch(argv, io)
89
+ except UsageError as error:
90
+ io.stderr(f"{error}\n\n{USAGE}")
91
+ except RunStoppedError as error:
92
+ io.stderr(f"Not approved: {error}. Do not retry in this run.")
93
+ return NOT_APPROVED_EXIT
94
+ except VariantGateError as error:
95
+ io.stderr(f"variantgate: {error}")
96
+ except KeyboardInterrupt:
97
+ return INTERRUPTED_EXIT
98
+ return MISTAKE_EXIT
99
+
100
+
101
+ def _dispatch(argv: list[str], io: Io) -> int:
102
+ split = argv.index("--") if "--" in argv else len(argv)
103
+ options = _parser().parse_intermixed_args(argv[:split])
104
+ command = argv[split + 1 :]
105
+ verb = options.verb
106
+ if verb == "ask":
107
+ return _ask(io, options, None)
108
+ if verb == "run":
109
+ return _ask(io, options, command)
110
+ if verb == "withdraw":
111
+ return _withdraw(io, options.rest)
112
+ if verb == "outcome":
113
+ return _outcome(io, options.rest, options.note)
114
+ raise UsageError(f'Unknown command "{verb}".' if verb else "No command given.")
115
+
116
+
117
+ def _ask(io: Io, options: argparse.Namespace, command: Optional[list[str]]) -> int:
118
+ if command is not None and not command:
119
+ raise UsageError("Give the command to run after --.")
120
+ if not (options.action and options.summary):
121
+ raise UsageError("Give both --action and --summary.")
122
+ timeout = _seconds(options.timeout)
123
+ client = _client(io, options.agent)
124
+ asked = client.ask(
125
+ options.action,
126
+ options.summary,
127
+ amount=options.amount,
128
+ currency=options.currency,
129
+ details=_details(options.details),
130
+ run=options.run,
131
+ )
132
+ io.stderr(f"Asked for approval (request {asked['id']}). Waiting for a person…")
133
+ try:
134
+ decision = client.wait(asked, timeout)
135
+ except KeyboardInterrupt:
136
+ # Nobody should approve a request the command has stopped waiting for.
137
+ _quietly(lambda: client.withdraw(asked["id"]))
138
+ return INTERRUPTED_EXIT
139
+ if options.json:
140
+ io.stdout(json.dumps(decision))
141
+ if not is_allowed(decision):
142
+ lead = "Not allowed yet" if in_cancel_window(decision) else "Not approved"
143
+ io.stderr(f"{lead}: {describe(decision)}.")
144
+ return NOT_APPROVED_EXIT
145
+ by = decision.get("decided_by") or "a person"
146
+ if is_changed(decision):
147
+ return _approved_with_changes(io, client, decision, by, command)
148
+ io.stderr(f"Approved by {by}.")
149
+ return _run_approved(io, client, decision, command) if command else APPROVED_EXIT
150
+
151
+
152
+ def _approved_with_changes(
153
+ io: Io, client: ApprovalClient, decision: Decision, by: str, command: Optional[list[str]]
154
+ ) -> int:
155
+ """Says what was approved instead of what was asked.
156
+
157
+ A command stands for what was asked, so it is never run; the record shows
158
+ it was not done.
159
+ """
160
+ io.stderr(
161
+ f"Approved with changes by {by}. Do only this, not what was asked: "
162
+ f"{approved_version(decision)}."
163
+ )
164
+ if command:
165
+ io.stderr("The command was not run, because it is what was asked.")
166
+ client.report_outcome(decision["id"], "failed", "not run: the approval changed the request")
167
+ return CHANGED_EXIT
168
+
169
+
170
+ def _run_approved(io: Io, client: ApprovalClient, decision: Decision, command: list[str]) -> int:
171
+ code = io.run(command)
172
+ result: Outcome = "succeeded" if code == 0 else "failed"
173
+ client.report_outcome(decision["id"], result, f"exit code {code}")
174
+ return code
175
+
176
+
177
+ def _withdraw(io: Io, rest: list[str]) -> int:
178
+ if not rest:
179
+ raise UsageError("Give the id of the request to withdraw.")
180
+ decision = _client(io).withdraw(rest[0])
181
+ io.stderr(f"Request {decision['id']} is {decision['status']}.")
182
+ return APPROVED_EXIT
183
+
184
+
185
+ def _outcome(io: Io, rest: list[str], note: Optional[str]) -> int:
186
+ if len(rest) < 2 or rest[1] not in ("succeeded", "failed"):
187
+ raise UsageError("Give the request id and succeeded or failed.")
188
+ request_id, result = rest[0], cast(Outcome, rest[1])
189
+ _client(io).report_outcome(request_id, result, note)
190
+ io.stderr(f"Reported that request {request_id} {result}.")
191
+ return APPROVED_EXIT
192
+
193
+
194
+ def _client(io: Io, agent: Optional[str] = None) -> ApprovalClient:
195
+ name = agent or io.env.get("VARIANTGATE_AGENT") or "cli"
196
+ if io.client is not None:
197
+ return io.client(name)
198
+ return ApprovalClient(name, environ=io.env)
199
+
200
+
201
+ def _details(text: Optional[str]) -> Optional[dict[str, Any]]:
202
+ if text is None:
203
+ return None
204
+ try:
205
+ parsed = json.loads(text)
206
+ except ValueError:
207
+ parsed = None
208
+ if not isinstance(parsed, dict):
209
+ raise UsageError("--details must be a JSON object.")
210
+ return parsed
211
+
212
+
213
+ def _seconds(text: Optional[str]) -> int:
214
+ if text is None:
215
+ return DEFAULT_TIMEOUT_SECONDS
216
+ if not text.isdigit() or int(text) <= 0:
217
+ raise UsageError("--timeout must be a whole number of seconds.")
218
+ return int(text)
219
+
220
+
221
+ def _quietly(action: Callable[[], Any]) -> None:
222
+ with contextlib.suppress(VariantGateError):
223
+ action()
224
+
225
+
226
+ def run_command(command: list[str]) -> int:
227
+ """Runs a command with the terminal attached and returns its exit code."""
228
+ try:
229
+ return subprocess.call(command)
230
+ except OSError:
231
+ return NOT_FOUND_EXIT
232
+
233
+
234
+ def entry() -> None:
235
+ """The console script."""
236
+ io = Io(
237
+ env=os.environ,
238
+ stdout=print,
239
+ stderr=functools.partial(print, file=sys.stderr),
240
+ run=run_command,
241
+ )
242
+ sys.exit(main(sys.argv[1:], io))
variantgate/client.py ADDED
@@ -0,0 +1,298 @@
1
+ """A client for one agent key."""
2
+
3
+ import contextlib
4
+ import math
5
+ import os
6
+ import time
7
+ from collections.abc import Mapping, Sequence
8
+ from typing import Any, Callable, Optional, TypeVar
9
+ from urllib.parse import quote
10
+
11
+ from . import _http
12
+ from .cancel_window import in_cancel_window, kept_window, parse_time, window_ends
13
+ from .errors import (
14
+ ApprovalApiError,
15
+ ChangedApprovalError,
16
+ ConfigurationError,
17
+ NotApprovedError,
18
+ )
19
+ from .guard import RequireApproval
20
+ from .mandate import MandateAnswer, request_mandate
21
+ from .on_behalf import declare_on_behalf, get_on_behalf
22
+ from .plans import Step, declare_plan, get_plan
23
+ from .preview import Preview, preview_problem
24
+ from .run_links import link_run
25
+ from .runs import run_id
26
+ from .types import Amount, Decision, Outcome, Source, is_allowed, is_changed
27
+
28
+ DEFAULT_API_URL = "https://api.variantgate.com"
29
+ """Where the hosted service lives. ``VARIANTGATE_API_URL`` overrides it."""
30
+
31
+ MAX_WAIT_SECONDS = 30
32
+ """The longest the API holds one call open while waiting for a decision."""
33
+
34
+ DEFAULT_TTL_SECONDS = 15 * 60
35
+ NOT_DONE_AS_CHANGED = (
36
+ "not done: the approval changed the request, and this agent can only do what it asked"
37
+ )
38
+ """How long a request stays open unless it says otherwise."""
39
+
40
+ MAX_NOTE = 2000
41
+ """The longest outcome note the API takes, in characters."""
42
+
43
+ CONFLICT = 409
44
+
45
+ T = TypeVar("T")
46
+
47
+
48
+ class ApprovalClient:
49
+ """Asks a person through the approvals API before an agent acts.
50
+
51
+ Every argument may be left out: ``api_url`` defaults to
52
+ ``$VARIANTGATE_API_URL`` (or the hosted service), ``key`` to
53
+ ``$VARIANTGATE_KEY`` and ``agent`` to ``$VARIANTGATE_AGENT`` (or
54
+ ``"agent"``), and ``run`` to ``$VARIANTGATE_RUN``: the run (one agent
55
+ session, such as a CI job) every request belongs to unless it names
56
+ another. A person can stop a run; asking in it then raises
57
+ ``RunStoppedError``. ``timeout`` is how long, in seconds, to wait for the API to
58
+ answer on top of any time it is asked to wait for a person.
59
+ """
60
+
61
+ def __init__(
62
+ self,
63
+ agent: Optional[str] = None,
64
+ *,
65
+ api_url: Optional[str] = None,
66
+ key: Optional[str] = None,
67
+ run: Optional[str] = None,
68
+ timeout: float = 15.0,
69
+ environ: Optional[Mapping[str, str]] = None,
70
+ now: Callable[[], float] = time.time,
71
+ ) -> None:
72
+ env = os.environ if environ is None else environ
73
+ found_key = key or env.get("VARIANTGATE_KEY")
74
+ if not found_key:
75
+ raise ConfigurationError("Set VARIANTGATE_KEY, or pass key= to the client.")
76
+ url = api_url or env.get("VARIANTGATE_API_URL") or DEFAULT_API_URL
77
+ self.api_url = url.rstrip("/")
78
+ self.agent = agent or env.get("VARIANTGATE_AGENT") or "agent"
79
+ self.run = run_id(run) or run_id(env.get("VARIANTGATE_RUN"))
80
+ self.timeout = timeout
81
+ self._key = found_key
82
+ self._now = now
83
+
84
+ def __repr__(self) -> str:
85
+ return f"ApprovalClient(agent={self.agent!r}, api_url={self.api_url!r})"
86
+
87
+ def ask(
88
+ self,
89
+ action: str,
90
+ summary: str,
91
+ *,
92
+ agent: Optional[str] = None,
93
+ amount: Optional[Amount] = None,
94
+ currency: Optional[str] = None,
95
+ details: Optional[dict[str, Any]] = None,
96
+ mandate: Optional[dict[str, Any]] = None,
97
+ preview: Optional[Preview] = None,
98
+ run: Optional[str] = None,
99
+ sources: Optional[Sequence[Source]] = None,
100
+ ttl_seconds: Optional[int] = None,
101
+ wait_seconds: int = 0,
102
+ ) -> Decision:
103
+ """Asks for approval. With ``wait_seconds``, waits up to 30 s for a decision.
104
+
105
+ ``sources`` lists what the agent read before asking, at most 10;
106
+ ``Sources`` builds it. ``run`` defaults to the client's; characters
107
+ other than letters, digits, ``.``, ``_``, ``:`` and ``-`` become
108
+ ``_``, and it is cut to 200. Raises ``RunStoppedError`` when a person
109
+ stopped the run. ``preview`` shows what the action will do (the
110
+ rendered email, the diff, the SQL and its dry-run row count, the
111
+ records it touches); one over the API's limits raises
112
+ ``ApprovalApiError`` (``invalid_request``) before anything is sent.
113
+ """
114
+ problem = None if preview is None else preview_problem(preview)
115
+ if problem:
116
+ raise ApprovalApiError(problem, "invalid_request", 422)
117
+ body = {
118
+ "action": action,
119
+ "agent": agent or self.agent,
120
+ "amount": amount,
121
+ "currency": currency,
122
+ "details": details,
123
+ "mandate": mandate,
124
+ "preview": None if preview is None else dict(preview),
125
+ # Left out when there is none: the API refuses fields it does not know.
126
+ "run": run_id(run) or self.run,
127
+ "sources": None if sources is None else list(sources),
128
+ "summary": summary,
129
+ "ttl_seconds": ttl_seconds,
130
+ "wait_seconds": wait_seconds,
131
+ }
132
+ return self._call("POST", "/v1/requests", body, wait_seconds)
133
+
134
+ def request_mandate(self, action: str, summary: str, **terms: Any) -> MandateAnswer:
135
+ """Asks up front for a bounded run of one action; see ``mandate.request_mandate``."""
136
+ return request_mandate(self, action, summary, **terms)
137
+
138
+ def declare_plan(
139
+ self, goal: str, steps: Sequence[Step], run: Optional[str] = None
140
+ ) -> Optional[dict[str, Any]]:
141
+ """Declares what the run will do, before it reads anything from outside; see ``plans``."""
142
+ return declare_plan(self, goal, steps, run)
143
+
144
+ def get_plan(self, run: Optional[str] = None) -> Optional[dict[str, Any]]:
145
+ """The run's plan with how much of each step is used, or None."""
146
+ return get_plan(self, run)
147
+
148
+ def declare_on_behalf(
149
+ self, parties: Sequence[str], label: str = "", run: Optional[str] = None
150
+ ) -> Optional[dict[str, Any]]:
151
+ """Declares whom the run works for, before it reads anything outside; see ``on_behalf``."""
152
+ return declare_on_behalf(self, parties, label, run)
153
+
154
+ def get_on_behalf(self, run: Optional[str] = None) -> Optional[dict[str, Any]]:
155
+ """Whom the run works for, or None."""
156
+ return get_on_behalf(self, run)
157
+
158
+ def link_run(self, run: str, parent: str) -> Optional[dict[str, Any]]:
159
+ """Links sub-agent run ``run`` below ``parent``; see ``run_links``."""
160
+ return link_run(self, run, parent)
161
+
162
+ def check(self, request_id: str, wait_seconds: int = 0) -> Decision:
163
+ """Reads a request, waiting up to ``wait_seconds`` for a decision."""
164
+ query = f"?wait_seconds={wait_seconds}" if wait_seconds > 0 else ""
165
+ return self._call("GET", f"{_path(request_id)}{query}", None, wait_seconds)
166
+
167
+ def withdraw(self, request_id: str) -> Decision:
168
+ """Takes back a request nobody has decided yet, or an approval still in
169
+ its cancel window."""
170
+ return self._call("POST", f"{_path(request_id)}/withdraw", None, 0)
171
+
172
+ def report_outcome(
173
+ self, request_id: str, outcome: Outcome, note: Optional[str] = None
174
+ ) -> Decision:
175
+ """Says how an approved action went. Once per request.
176
+
177
+ A note longer than the API takes is cut short rather than refused.
178
+ """
179
+ body = {"note": None if note is None else note[:MAX_NOTE], "outcome": outcome}
180
+ return self._call("POST", f"{_path(request_id)}/outcome", body, 0)
181
+
182
+ def wait(self, decision: Decision, timeout: Optional[float] = None) -> Decision:
183
+ """Waits until the request is decided, or the time is up.
184
+
185
+ ``timeout`` is in seconds and defaults to the request's expiry. A
186
+ request still pending at the end is withdrawn, so nobody approves it
187
+ after the agent has stopped listening. An approval in a cancel window
188
+ is waited out too, until ``allowed`` turns true or it is cancelled;
189
+ one still in its window when ``timeout`` is up is withdrawn the same
190
+ way, so it does not go ahead after the agent stopped waiting for it.
191
+ """
192
+ deadline = math.inf if timeout is None else self._now() + timeout
193
+ # Read once: a time that cannot be read must not move the end along.
194
+ expires = _expiry(decision.get("expires_at"), self._now())
195
+ latest = decision
196
+ while True:
197
+ pending = latest.get("status") == "pending"
198
+ if not (pending or in_cancel_window(latest)):
199
+ return latest
200
+ until = expires if pending else window_ends(latest)
201
+ left = min(until, deadline) - self._now()
202
+ if left <= 0:
203
+ return self._withdraw_if_open(latest)
204
+ # Infinite while only the API can say a window is over.
205
+ wait = MAX_WAIT_SECONDS if math.isinf(left) else math.ceil(left)
206
+ latest = self.check(latest["id"], min(wait, MAX_WAIT_SECONDS))
207
+
208
+ def wait_for_approval(
209
+ self,
210
+ action: str,
211
+ summary: str,
212
+ *,
213
+ timeout: Optional[float] = None,
214
+ accept_changes: bool = False,
215
+ **request: Any,
216
+ ) -> Decision:
217
+ """Asks, waits, and returns the decision only if it allows acting.
218
+
219
+ Raises ``NotApprovedError`` for anything but an approval,
220
+ ``RunStoppedError`` when a person stopped the run, and
221
+ ``ApprovalApiError`` when the API cannot be asked. An approval of a
222
+ changed version raises ``ChangedApprovalError`` and is recorded as not
223
+ done, unless ``accept_changes`` says the code acts on
224
+ ``approved_summary`` and ``approved_amount``. Takes the same keyword
225
+ arguments as ``ask``.
226
+ """
227
+ asked = self.ask(action, summary, wait_seconds=MAX_WAIT_SECONDS, **request)
228
+ decision = self.wait(asked, timeout)
229
+ if not is_allowed(decision):
230
+ raise NotApprovedError(decision)
231
+ if is_changed(decision) and not accept_changes:
232
+ with contextlib.suppress(ApprovalApiError):
233
+ self.report_outcome(decision["id"], "failed", NOT_DONE_AS_CHANGED)
234
+ raise ChangedApprovalError(decision)
235
+ return decision
236
+
237
+ def guard(
238
+ self,
239
+ act: Callable[[], T],
240
+ action: str,
241
+ summary: str,
242
+ *,
243
+ timeout: Optional[float] = None,
244
+ accept_changes: bool = False,
245
+ **request: Any,
246
+ ) -> T:
247
+ """Runs ``act`` only on an approval, then reports how it went.
248
+
249
+ The outcome is ``succeeded``, with what ``act`` returned when that is
250
+ a string, or ``failed`` with the error. When ``act`` raises, its error
251
+ is raised even if reporting the failure did not work.
252
+ """
253
+ decision = self.wait_for_approval(
254
+ action, summary, timeout=timeout, accept_changes=accept_changes, **request
255
+ )
256
+ try:
257
+ result = act()
258
+ except BaseException as error:
259
+ self.report_failure(decision["id"], error)
260
+ raise
261
+ note = result if isinstance(result, str) else None
262
+ self.report_outcome(decision["id"], "succeeded", note)
263
+ return result
264
+
265
+ def report_failure(self, request_id: str, error: BaseException) -> None:
266
+ """Records that an approved action failed, ignoring any error doing so."""
267
+ with contextlib.suppress(ApprovalApiError):
268
+ self.report_outcome(request_id, "failed", str(error) or type(error).__name__)
269
+
270
+ def require_approval(self, action: Any, summary: Any, **request: Any) -> RequireApproval:
271
+ """A decorator or ``with`` block that runs only on an approval.
272
+
273
+ See ``variantgate.require_approval``.
274
+ """
275
+ return RequireApproval(lambda: self, action, summary, **request)
276
+
277
+ def _withdraw_if_open(self, decision: Decision) -> Decision:
278
+ try:
279
+ return kept_window(self.withdraw(decision["id"]), decision)
280
+ except ApprovalApiError as error:
281
+ if error.status == CONFLICT:
282
+ return self.check(decision["id"])
283
+ raise
284
+
285
+ def _call(self, method: str, path: str, body: Optional[dict[str, Any]], wait: int) -> Decision:
286
+ sent = None if body is None else {k: v for k, v in body.items() if v is not None}
287
+ url = f"{self.api_url}{path}"
288
+ return _http.call(url, self._key, method, sent, self.timeout + wait)
289
+
290
+
291
+ def _path(request_id: str) -> str:
292
+ return f"/v1/requests/{quote(request_id, safe='')}"
293
+
294
+
295
+ def _expiry(text: Any, now: float) -> float:
296
+ """When a request expires, as a timestamp. Unreadable means the default TTL."""
297
+ at = parse_time(text)
298
+ return now + DEFAULT_TTL_SECONDS if at is None else at