formist-cli 0.1.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.
@@ -0,0 +1 @@
1
+ """Formist command-line client (``fm``)."""
@@ -0,0 +1,3 @@
1
+ from formist_cli.cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,238 @@
1
+ """``fm airtable direction`` - what an Airtable grant can actually do, and repair.
2
+
3
+ The decision this drives lives on the server, and this module is a
4
+ client that holds no copy of it. That split is the entire point: a
5
+ client that reached the database directly would be a second
6
+ implementation of "may this connection write back to Airtable", and two
7
+ answers to that question is how a connection ends up 403-ing every
8
+ outbound write on every tick while a script insists it is fine.
9
+
10
+ What stays on this side is only presentation and the safety choreography:
11
+
12
+ A dry run always runs, including under ``--apply``. ``--apply`` does not
13
+ skip the GET; it performs it, prints it, and then submits exactly the
14
+ lines it printed. The server re-probes and refuses anything that no
15
+ longer matches, so the operator authorizes a plan they have read, not a
16
+ verb they typed.
17
+
18
+ ``--apply`` will not inherit an environment. A read may resolve ``--env``
19
+ from ``fm use``; this write may not. A remembered environment is one
20
+ somebody forgets they set, and the cost of forgetting is a write against
21
+ production.
22
+
23
+ Inconclusive is printed, never folded into "fine". Four things (no
24
+ credential, a failed probe, no bases, no ``permissionLevel``) mean
25
+ nothing was learned. They are the reason an operator is running this at
26
+ all, and a summary that reported them as "0 changes" would be a check
27
+ that cannot fail.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import json
33
+ import sys
34
+ from typing import Any
35
+
36
+ ENDPOINT = "/projects/{space}/admin/airtable/direction"
37
+
38
+ #: How a plan line's reason code reads at a terminal. Unknown codes fall through
39
+ #: verbatim rather than being dropped: a reason this client has never heard of is
40
+ #: still the server's answer, and hiding it would be worse than printing it raw.
41
+ _REASONS = {
42
+ "ok": "",
43
+ "no-credential": "NO CREDENTIAL",
44
+ "probe-failed": "PROBE FAILED",
45
+ "no-bases": "NO BASES",
46
+ "no-permission-level": "NO PERMISSION LEVEL",
47
+ }
48
+
49
+
50
+ class AirtableError(Exception):
51
+ """A refusal or a malformed answer, phrased for whoever has to fix it."""
52
+
53
+
54
+ def add_parser(sub) -> None:
55
+ import argparse
56
+
57
+ from formist_cli.cli import _add_env, _add_space
58
+ from formist_cli.cli_support import add_admin_flag
59
+
60
+ p = sub.add_parser(
61
+ "airtable",
62
+ help="inspect and repair an Airtable connection's sync direction",
63
+ description=(
64
+ "Asks AIRTABLE what each connection's token can actually do, and "
65
+ "reports whether the stored sync direction agrees.\n\n"
66
+ "The stored OAuth scope cannot answer this. A real connection carries "
67
+ "data.records:write in payload.oauth.scope while the base's actual "
68
+ "permissionLevel is 'read': the scope was granted, the permission was "
69
+ "never there. So this makes a live call, per connection.\n\n"
70
+ "DRY RUN BY DEFAULT. --apply re-runs the dry run, prints it, and "
71
+ "submits exactly those lines; the server re-probes and applies only "
72
+ "what still matches. --apply never inherits an environment from "
73
+ "`fm use`: with one remembered the write is REFUSED until you pass "
74
+ "--env, and with nothing remembered it targets local.\n\n"
75
+ "This only ever DEMOTES a connection to 'inbound'. A writable base is "
76
+ "not a request to write, so nothing is ever promoted to "
77
+ "'outbound'/'both' here."
78
+ ),
79
+ formatter_class=argparse.RawDescriptionHelpFormatter,
80
+ )
81
+ _add_env(p)
82
+ _add_space(p)
83
+ p.add_argument(
84
+ "subject",
85
+ choices=("direction",),
86
+ help="what to operate on (today: direction)",
87
+ )
88
+ p.add_argument(
89
+ "--apply",
90
+ action="store_true",
91
+ help=(
92
+ "persist the changes this run reports. Refuses a remembered `fm use` "
93
+ "environment: pass --env to write anywhere but local"
94
+ ),
95
+ )
96
+ p.add_argument("--json", action="store_true", help="machine-readable output")
97
+ add_admin_flag(p)
98
+
99
+
100
+ def fetch_plan(target, space: str, *, token: str | None, get=None) -> dict:
101
+ """The dry run: every Airtable connection in the space, probed live."""
102
+ from formist_cli import api
103
+
104
+ get = get or api.get
105
+ body = get(target, ENDPOINT.format(space=space), token=token)
106
+ return _envelope(body)
107
+
108
+
109
+ def submit(target, space: str, changes: list[dict], *, token: str | None, post=None) -> dict:
110
+ """Authorize exactly the plan lines in ``changes``."""
111
+ from formist_cli import api
112
+
113
+ post = post or api.post
114
+ body = post(target, ENDPOINT.format(space=space), {"changes": changes}, token=token)
115
+ return _envelope(body)
116
+
117
+
118
+ def _envelope(body: Any) -> dict:
119
+ if not isinstance(body, dict):
120
+ raise AirtableError(
121
+ f"expected a JSON object from the direction endpoint, got "
122
+ f"{type(body).__name__}. This is not a plan and must not be acted on."
123
+ )
124
+ return body
125
+
126
+
127
+ def changes_from(plan: dict) -> list[dict]:
128
+ """The lines to authorize: the ones the SERVER marked ``would_change``.
129
+
130
+ Read off the server's own flag rather than recomputed here as
131
+ ``current != wanted``. The two agree today and would diverge the moment an
132
+ inconclusive probe grew a ``wanted`` that differs (a reasonable future change),
133
+ at which point a client re-derivation would start authorizing writes on
134
+ connections the server had explicitly declined to decide about.
135
+ """
136
+ return [
137
+ {
138
+ "connection_id": item.get("connection_id"),
139
+ "current": item.get("current"),
140
+ "wanted": item.get("wanted"),
141
+ }
142
+ for item in plan.get("items") or []
143
+ if item.get("would_change")
144
+ ]
145
+
146
+
147
+ def render_plan(plan: dict, *, applying: bool, out=None) -> None:
148
+ out = out or sys.stdout
149
+ items = plan.get("items") or []
150
+ counts = plan.get("counts") or {}
151
+ print(f"{len(items)} AIRTABLE connection(s)", file=out)
152
+ for item in items:
153
+ flag = _REASONS.get(item.get("reason"), str(item.get("reason")))
154
+ head = f" {item.get('connection_id')}"
155
+ detail = item.get("detail") or ""
156
+ if item.get("would_change"):
157
+ suffix = "" if applying else " (dry run)"
158
+ print(
159
+ f"{head}: {detail} -> direction {item.get('current')!r} => {item.get('wanted')!r}{suffix}",
160
+ file=out,
161
+ )
162
+ elif item.get("conclusive"):
163
+ print(
164
+ f"{head}: {detail} -> direction {item.get('current')!r} is correct",
165
+ file=out,
166
+ )
167
+ else:
168
+ print(
169
+ f"{head}: {flag}: {detail}; left at {item.get('current')!r}",
170
+ file=out,
171
+ )
172
+ print(
173
+ f"\n{counts.get('would_change', 0)} "
174
+ + ("to change" if applying else "would change")
175
+ + f" | {counts.get('inconclusive', 0)} inconclusive",
176
+ file=out,
177
+ )
178
+
179
+
180
+ def render_outcomes(report: dict, *, out=None) -> None:
181
+ out = out or sys.stdout
182
+ outcomes = report.get("outcomes") or []
183
+ print("\napplied:", file=out)
184
+ for o in outcomes:
185
+ mark = "OK" if o.get("applied") else "SKIP"
186
+ print(f" {mark} {o.get('connection_id')}: {o.get('detail')}", file=out)
187
+ counts = report.get("counts") or {}
188
+ print(f"\n{counts.get('applied', 0)} changed", file=out)
189
+
190
+
191
+ def cmd_airtable(args) -> int:
192
+ from formist_cli.cli import _effective, _token_for
193
+
194
+ # for_write is the --apply flag itself: the dry run may inherit an environment
195
+ # from `fm use`, the write may not. Same rule as `fm update`, applied to the
196
+ # half of this command that actually writes.
197
+ eff = _effective(args, for_write=bool(args.apply))
198
+ target, space = eff.target, eff.space
199
+ token = _token_for(eff)
200
+
201
+ # The dry run happens either way. Under --apply it is printed FIRST and then
202
+ # submitted verbatim, so the terminal shows what is about to be authorized.
203
+ plan = fetch_plan(target, space, token=token)
204
+ if not args.json:
205
+ render_plan(plan, applying=bool(args.apply))
206
+ if not args.apply:
207
+ if args.json:
208
+ print(json.dumps(plan, indent=2))
209
+ elif plan.get("counts", {}).get("would_change"):
210
+ print("\n-> re-run with --apply --host <host> to persist this.")
211
+ return 0
212
+
213
+ changes = changes_from(plan)
214
+ if not changes:
215
+ # Nothing to authorize. Deliberately NOT posted: the endpoint refuses an
216
+ # empty change list, and turning "already correct" into a 400 would train
217
+ # an operator to read a refusal as routine.
218
+ if args.json:
219
+ counts = {**(plan.get("counts") or {}), "applied": 0}
220
+ print(json.dumps({**plan, "outcomes": [], "counts": counts}, indent=2))
221
+ else:
222
+ print("\nnothing to change, no request was sent.")
223
+ return 0
224
+
225
+ report = submit(target, space, changes, token=token)
226
+ if args.json:
227
+ print(json.dumps(report, indent=2))
228
+ return 0
229
+ render_outcomes(report)
230
+ stalled = [o for o in report.get("outcomes") or [] if o.get("reason") == "plan-moved"]
231
+ if stalled:
232
+ print(
233
+ f"\n{len(stalled)} connection(s) were NOT applied because the live "
234
+ "probe disagreed with the plan you were shown. Re-run the dry run.",
235
+ file=sys.stderr,
236
+ )
237
+ return 1
238
+ return 0
formist_cli/alerts.py ADDED
@@ -0,0 +1,207 @@
1
+ """``fm alerts`` - platform risk alerts, over ``GET /admin/alerts*``.
2
+
3
+ Read-only; the email is the push channel, this is the pull one: filterable,
4
+ reviewable a week later, and shows an alert the hourly ceiling suppressed
5
+ from becoming an email at all.
6
+
7
+ These are platform alerts, not project notifications. ``project_id`` on a
8
+ row is attribution, never scope: most alerts have no project at all.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import json
15
+
16
+ from formist_cli import api, context
17
+ from formist_cli.cli_support import PLATFORM_ADMIN_GATE_NOTE, add_admin_flag
18
+ from formist_cli.cli_support import as_dict as _shared_alerts_payload
19
+ from formist_cli.cli_support import build_standalone_parser as _build_standalone_parser
20
+
21
+ SUBJECTS = ("list", "conditions", "ack-parked")
22
+ DEFAULT_SUBJECT = "list"
23
+
24
+
25
+ class AlertsError(Exception):
26
+ """A refusal about the alerts surface, written for an operator."""
27
+
28
+
29
+ def canonical_subject(subject: str | None) -> str:
30
+ if subject is None:
31
+ return DEFAULT_SUBJECT
32
+ value = subject.strip().lower()
33
+ if value not in SUBJECTS:
34
+ raise AlertsError(
35
+ f"unknown subcommand {subject!r}. Valid: {', '.join(SUBJECTS)}.\n"
36
+ " list open (default) / resolved / all alerts\n"
37
+ " conditions every condition this deployment CAN alert on\n"
38
+ " ack-parked stop listing a connector's parked sync rows"
39
+ )
40
+ return value
41
+
42
+
43
+ def render_alerts(payload: dict) -> str:
44
+ counts = payload.get("counts") or {}
45
+ header = (
46
+ f"open={counts.get('open', 0)} critical={counts.get('critical', 0)} "
47
+ f"warning={counts.get('warning', 0)} info={counts.get('info', 0)}"
48
+ )
49
+ alerts = payload.get("alerts") or []
50
+ if not alerts:
51
+ return f"{header}\n\n(no alerts match this filter)"
52
+ lines = [
53
+ header, "",
54
+ f"{'severity':<9} {'condition':<38} {'occ':<4} {'last_seen':<20} id",
55
+ f"{'-' * 9} {'-' * 38} {'-' * 4} {'-' * 20} {'-' * 8}",
56
+ ]
57
+ for row in alerts:
58
+ resolved = " (resolved)" if row.get("resolved") else ""
59
+ lines.append(
60
+ f"{str(row.get('severity') or '-'):<9} "
61
+ f"{str(row.get('condition') or '-'):<38.38} "
62
+ f"{row.get('occurrences', '?'):<4} "
63
+ f"{str(row.get('last_seen_at') or '-'):<20} "
64
+ f"{row.get('id')}{resolved}"
65
+ )
66
+ if row.get("title"):
67
+ lines.append(f" {row['title']}")
68
+ total = payload.get("total")
69
+ shown = len(alerts)
70
+ if total is not None and shown < int(total):
71
+ lines.append(
72
+ f"\n{shown} shown of {total}, MORE EXIST. Raise --limit or page with --offset."
73
+ )
74
+ return "\n".join(lines)
75
+
76
+
77
+ def render_conditions(payload: dict) -> str:
78
+ origin = payload.get("deployment") or {}
79
+ lines = [
80
+ f"deployment {origin.get('region', '?')}/{origin.get('env_name', '?')}",
81
+ f"alerts_enabled={payload.get('alerts_enabled')} "
82
+ f"email_enabled={payload.get('email_enabled')} "
83
+ f"admin_email_configured={payload.get('admin_email_configured')}",
84
+ f"evaluation_interval_seconds={payload.get('evaluation_interval_seconds')} "
85
+ f"max_emails_per_hour={payload.get('max_emails_per_hour')}",
86
+ "",
87
+ f"{'key':<40} {'category':<10} {'severity':<9} available",
88
+ f"{'-' * 40} {'-' * 10} {'-' * 9} {'-' * 9}",
89
+ ]
90
+ for c in payload.get("conditions") or []:
91
+ available = "yes" if c.get("available") else f"NO (needs {c.get('requires')})"
92
+ lines.append(
93
+ f"{str(c.get('key') or '-'):<40.40} "
94
+ f"{str(c.get('category') or '-'):<10} "
95
+ f"{str(c.get('severity') or '-'):<9} "
96
+ f"{available}"
97
+ )
98
+ return "\n".join(lines)
99
+
100
+
101
+ _HELP = "platform risk alerts and the conditions that can fire (admin)"
102
+
103
+ _DESCRIPTION = """Platform-wide risk alerts, the PULL channel alongside the admin
104
+ email (the PUSH channel). Filterable and reviewable after the fact, unlike email.
105
+
106
+ fm alerts --host evane open alerts (default)
107
+ fm alerts --host evane --status all --severity critical
108
+ fm alerts conditions --host evane what CAN alert, and why not
109
+ fm alerts ack-parked <connection-id> --env ae stop listing its parked sync rows
110
+ fm alerts ack-parked <connection-id> --record recX just one row (repeatable)
111
+
112
+ project_id on a row is ATTRIBUTION, not scope: most alerts have no project.
113
+ """
114
+
115
+
116
+ def _add_arguments(parser: argparse.ArgumentParser) -> None:
117
+ parser.add_argument(
118
+ "subject", nargs="?",
119
+ help=f"one of: {', '.join(SUBJECTS)} (default: {DEFAULT_SUBJECT})",
120
+ )
121
+ parser.add_argument(
122
+ "connection", nargs="?", help="ack-parked: the connection id",
123
+ )
124
+ parser.add_argument(
125
+ "--record", action="append", default=None, metavar="RECORD_ID",
126
+ help="ack-parked: one source record id (repeatable; default: every parked row)",
127
+ )
128
+ parser.add_argument(
129
+ "--host",
130
+ default=argparse.SUPPRESS,
131
+ metavar="HOST",
132
+ help="deployment name or API origin (default: formist, or `fm use` for reads); "
133
+ "a write never inherits it",
134
+ )
135
+ parser.add_argument("--status", choices=("open", "resolved", "all"), default=None)
136
+ parser.add_argument("--severity", choices=("critical", "warning", "info"), default=None)
137
+ parser.add_argument("--condition", default=None, help="filter to one condition key")
138
+ parser.add_argument("--region", default=None)
139
+ parser.add_argument("--limit", type=int, default=None)
140
+ parser.add_argument("--offset", type=int, default=None)
141
+ parser.add_argument("--json", action="store_true", help="raw JSON instead of a report")
142
+
143
+
144
+ def add_parser(subparsers) -> argparse.ArgumentParser:
145
+ parser = subparsers.add_parser(
146
+ "alerts", help=_HELP, description=_DESCRIPTION, epilog=PLATFORM_ADMIN_GATE_NOTE,
147
+ formatter_class=argparse.RawDescriptionHelpFormatter,
148
+ )
149
+ _add_arguments(parser)
150
+ add_admin_flag(parser)
151
+ return parser
152
+
153
+
154
+ def build_standalone_parser() -> argparse.ArgumentParser:
155
+ return _build_standalone_parser(add_parser)
156
+
157
+
158
+ def run(args) -> int:
159
+ subject = canonical_subject(getattr(args, "subject", None))
160
+ ctx = context.resolve(args, need_token=True)
161
+
162
+ if subject == "conditions":
163
+ payload = api.admin_get(ctx.target, "/admin/alerts/conditions", token=ctx.token)
164
+ payload = _alerts_payload(payload)
165
+ print(json.dumps(payload, indent=2, ensure_ascii=False) if args.json
166
+ else render_conditions(payload))
167
+ return 0
168
+
169
+ if subject == "ack-parked":
170
+ connection = getattr(args, "connection", None)
171
+ if not connection:
172
+ raise AlertsError("ack-parked needs the connection id: fm alerts ack-parked <id>")
173
+ body = {"connection_id": connection, "record_ids": getattr(args, "record", None)}
174
+ payload = _alerts_payload(
175
+ api.admin_post(
176
+ ctx.target, "/admin/alerts/parked-rows/acknowledge", body, token=ctx.token
177
+ )
178
+ )
179
+ if args.json:
180
+ print(json.dumps(payload, indent=2, ensure_ascii=False))
181
+ else:
182
+ print(
183
+ f"acknowledged {len(payload.get('acknowledged') or [])} row(s); "
184
+ f"{payload.get('still_listed', '?')} still listed"
185
+ + (f"; not parked: {', '.join(payload['unknown'])}" if payload.get("unknown") else "")
186
+ )
187
+ return 0
188
+
189
+ params: dict[str, str] = {}
190
+ for flag in ("status", "severity", "condition", "region"):
191
+ value = getattr(args, flag, None)
192
+ if value is not None:
193
+ params[flag] = str(value)
194
+ if getattr(args, "limit", None) is not None:
195
+ params["limit"] = str(args.limit)
196
+ if getattr(args, "offset", None) is not None:
197
+ params["offset"] = str(args.offset)
198
+
199
+ payload = api.admin_get(ctx.target, "/admin/alerts", token=ctx.token, params=params)
200
+ payload = _alerts_payload(payload)
201
+ print(json.dumps(payload, indent=2, ensure_ascii=False) if args.json
202
+ else render_alerts(payload))
203
+ return 0
204
+
205
+
206
+ def _alerts_payload(payload: object) -> dict:
207
+ return _shared_alerts_payload(payload, what="/admin/alerts", error=AlertsError)