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,411 @@
1
+ """``fm space-plan`` - read and set a space's usage plan (``space_plan``).
2
+
3
+ ``space_plan`` lives in a region database, keyed by the space's project id,
4
+ and the only database it may go in is the one that owns that space's
5
+ project row. There is deliberately no ``--region`` and no database flag
6
+ here: the server resolves the database from the Global space registry and
7
+ reports what it resolved to, and refuses if that database turns out not to
8
+ hold the project.
9
+
10
+ ``--env`` therefore does not name the database. It names which deployment's
11
+ admin API to ask, and for the default product ``/admin`` is served from
12
+ Global only in production, so the real choice is `local` or `global` even
13
+ for an AE space.
14
+
15
+ The `formist` host is a different deployment, not a third region: for a
16
+ `formist` space ``--host formist`` is the only correct choice. It has no
17
+ Global/AE split of its own, so its one deployment serves ``/admin``
18
+ locally.
19
+
20
+ Dry run first, always, same contract as `fm update`: the request body
21
+ carries ``apply``, which defaults to false on the server model, so a body
22
+ that merely forgets it cannot write. ``fm space-plan set`` runs the dry
23
+ run, prints exactly what would change, and prints the revision of the row
24
+ it was looking at. ``--apply <revision>`` re-runs the dry run, refuses if
25
+ the revision has moved, and only then sends ``apply: true``, carrying the
26
+ revision so the server re-checks it too. Both checks matter: the client's
27
+ copy gives the operator a readable refusal without a write ever being
28
+ attempted, while the server's copy is what actually holds for a caller
29
+ that skips this CLI.
30
+
31
+ A space with no plan row is ungated: nothing settles any model call.
32
+ Creating the first row flips that space from fail-open to fail-closed. The
33
+ server measures the consequences on the deployment that will enforce them
34
+ (whether the gate is switched on, whether there is a catch-all multiplier)
35
+ and this command prints them.
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ import argparse
41
+ import json
42
+
43
+ from formist_cli import api, context
44
+ from formist_cli.cli_support import PLATFORM_ADMIN_GATE_NOTE, add_admin_flag, as_dict
45
+ from formist_cli.cli_support import build_standalone_parser as _build_standalone_parser
46
+ from formist_cli.targets import require_space_id
47
+
48
+ SUBJECTS = ("show", "set")
49
+ DEFAULT_SUBJECT = "show"
50
+
51
+ #: The plan columns this command can set, and the flag each is spelled with.
52
+ #: One table, so ``--help``, the request body and the "nothing to set" refusal
53
+ #: cannot disagree about what is settable.
54
+ SETTABLE = (
55
+ ("name", "--name", str, "plan label (NULL -> the config default, '<product> Max')"),
56
+ ("rolling_window_hours", "--rolling-window-hours", int, "length of the ROLLING window, in hours"),
57
+ (
58
+ "rolling_limit_standard_tokens",
59
+ "--rolling-limit",
60
+ int,
61
+ "standard tokens allowed inside the rolling window",
62
+ ),
63
+ (
64
+ "weekly_limit_standard_tokens",
65
+ "--weekly-limit",
66
+ int,
67
+ "standard tokens allowed inside the ANCHORED weekly window",
68
+ ),
69
+ ("tier", "--tier", str, "plan tier of this product, e.g. plus, pro, max"),
70
+ ("extra_seats", "--extra-seats", int, "members allowed beyond the tier's included members"),
71
+ )
72
+
73
+ #: The columns ``--use-tier-limits`` clears to NULL, so name and limits follow the
74
+ #: tier's own config instead of the row.
75
+ TIER_FOLLOWING = (
76
+ "name",
77
+ "rolling_window_hours",
78
+ "rolling_limit_standard_tokens",
79
+ "weekly_limit_standard_tokens",
80
+ )
81
+
82
+
83
+ class SpacePlanError(Exception):
84
+ """A refusal about the plan surface, written for an operator."""
85
+
86
+
87
+ def canonical_subject(subject: str | None) -> str:
88
+ if subject is None:
89
+ return DEFAULT_SUBJECT
90
+ value = subject.strip().lower()
91
+ if value not in SUBJECTS:
92
+ raise SpacePlanError(
93
+ f"unknown subcommand {subject!r}. Valid: {', '.join(SUBJECTS)}.\n"
94
+ " show this space's plan row, and the database it lives in\n"
95
+ " set create or change it, a DRY RUN unless --apply is given"
96
+ )
97
+ return value
98
+
99
+
100
+ # ===========================================================================
101
+ # Rendering
102
+ # ===========================================================================
103
+ def render_target(target: dict, *, container_app: str | None) -> str:
104
+ """WHERE this resolved to. A write whose target is not in its own output is
105
+ not auditable, so this is printed on every call, read or write."""
106
+ database = target.get("database") or {}
107
+ lines = [
108
+ f"space {target.get('space_name') or '?'} ({target.get('space_id')})",
109
+ f"region {target.get('region')} (resolved by the server from the "
110
+ "Global space registry, not from --env)",
111
+ f"database {database.get('database') or '?'} on "
112
+ f"{database.get('host') or '?'}:{database.get('port') or '?'}",
113
+ ]
114
+ if container_app:
115
+ lines.append(f"container {container_app}")
116
+ if database.get("shared_with_global"):
117
+ lines.append(
118
+ " this region shares ONE database with global on this deployment, "
119
+ "so 'region' here is a label and not evidence about where a row landed"
120
+ )
121
+ return "\n".join(lines)
122
+
123
+
124
+ def render_plan(plan: dict | None) -> str:
125
+ if plan is None:
126
+ return (
127
+ "plan (none): this space is UNGATED, every model call is allowed "
128
+ "and nothing is settled"
129
+ )
130
+ fields = (
131
+ ("name", plan.get("name")),
132
+ ("rolling_window_hours", plan.get("rolling_window_hours")),
133
+ ("rolling_limit_standard_tokens", plan.get("rolling_limit_standard_tokens")),
134
+ ("weekly_limit_standard_tokens", plan.get("weekly_limit_standard_tokens")),
135
+ ("week_reset_at", plan.get("week_reset_at")),
136
+ ("additional_usage_enabled", plan.get("additional_usage_enabled")),
137
+ ("additional_usage_disabled_reason", plan.get("additional_usage_disabled_reason")),
138
+ ("tier", plan.get("tier")),
139
+ ("extra_seats", plan.get("extra_seats")),
140
+ )
141
+ lines = ["plan"]
142
+ for key, value in fields:
143
+ shown = "NULL (-> the configured default)" if value is None else value
144
+ lines.append(f" {key:<34} {shown}")
145
+ return "\n".join(lines)
146
+
147
+
148
+ def render_effects(effects: dict) -> str:
149
+ """What the write DOES. Never omitted, including on a read."""
150
+ lines = ["what a plan row does here", f" {effects.get('billing_gate')}"]
151
+ if effects.get("usage_gate_enabled_on_this_deployment") is False:
152
+ lines.append(
153
+ " EVANE_USAGE_GATE_ENABLED is OFF on this deployment, so the row "
154
+ "changes nothing until it is switched on. A quiet graph afterwards "
155
+ "will not mean the plan is working"
156
+ )
157
+ else:
158
+ lines.append(" the usage gate is switched ON on this deployment")
159
+ lines.append(f" {effects.get('catch_all_note')}")
160
+ limits = effects.get("effective_limits") or {}
161
+ lines.append(" effective limits (NULL columns resolved against the config):")
162
+ for key, value in limits.items():
163
+ lines.append(f" {key:<32} {value}")
164
+ return "\n".join(lines)
165
+
166
+
167
+ def render_change(payload: dict) -> str:
168
+ """The dry-run / apply report."""
169
+ outcome = payload.get("outcome")
170
+ applied = bool(payload.get("applied"))
171
+ changes = payload.get("changes") or {}
172
+ lines = [f"outcome {outcome} (applied: {'yes' if applied else 'NO, dry run'})"]
173
+ if changes:
174
+ lines.append("changes")
175
+ for key, pair in changes.items():
176
+ before, after = pair if isinstance(pair, list) and len(pair) == 2 else (None, None)
177
+ lines.append(f" {key:<34} {before!r} -> {after!r}")
178
+ elif outcome == "unchanged":
179
+ lines.append(" (every requested value already matches this row)")
180
+ return "\n".join(lines)
181
+
182
+
183
+ def next_command(args, revision: str) -> str:
184
+ """The exact command that applies what was just shown."""
185
+ parts = ["fm space-plan set", f"--host {getattr(args, 'host', None) or 'formist'}", f"--space {args.space}"]
186
+ for field, flag, _type, _help in SETTABLE:
187
+ value = getattr(args, field, None)
188
+ if value is not None:
189
+ parts.append(f"{flag} {value!r}" if isinstance(value, str) else f"{flag} {value}")
190
+ if getattr(args, "additional_usage", None) is not None:
191
+ parts.append(f"--additional-usage {args.additional_usage}")
192
+ if getattr(args, "use_tier_limits", False):
193
+ parts.append("--use-tier-limits")
194
+ parts.append(f"--apply {revision}")
195
+ return " ".join(parts)
196
+
197
+
198
+ # ===========================================================================
199
+ # CLI
200
+ # ===========================================================================
201
+ _HELP = "read or set a space's usage plan (dry run unless --apply)"
202
+
203
+ _DESCRIPTION = """A space's USAGE PLAN (space_plan): the two window limits and whether
204
+ overage is allowed.
205
+
206
+ fm space-plan show --host evane --space <uuid>
207
+ fm space-plan set --host evane --space <uuid> --name '<product> Max' \\
208
+ --rolling-window-hours 5 --rolling-limit 20000000 \\
209
+ --weekly-limit 120000000 --additional-usage off
210
+
211
+ A SPACE WITH NO PLAN ROW IS UNGATED. Every model call is allowed and
212
+ nothing is settled. Creating the first row flips that space from FAIL-OPEN
213
+ to FAIL-CLOSED: the limits start being enforced, and a model with no
214
+ configured multiplier becomes a 503 model-not-priced for that space. The
215
+ command prints the live state of both of those before you apply anything.
216
+
217
+ `set` IS A DRY RUN unless you pass --apply <revision>. The dry run prints the
218
+ revision of the row it read; --apply re-runs it, refuses if the row moved, and the
219
+ server re-checks the revision before writing.
220
+
221
+ --env DOES NOT CHOOSE THE DATABASE. `space_plan` lives in whichever region
222
+ database owns the space's `project` row, and the server derives that from
223
+ the Global registry; there is no --region flag and there must never be
224
+ one. /admin is served from the Global region only, so use `--host evane`
225
+ for a default-product prod space in either region.
226
+
227
+ `--host formist` is different, not an exception to the rule above:
228
+ `formist` is a whole separate deployment (its own subscription, database,
229
+ container apps), not a second region of the default product. It has no
230
+ Global/AE split, so its own single deployment serves /admin locally.
231
+ `--env formist` is the only correct target for a space on that
232
+ deployment, never `--host evane`.
233
+ """
234
+
235
+
236
+ def _add_arguments(parser: argparse.ArgumentParser) -> None:
237
+ parser.add_argument(
238
+ "subject",
239
+ nargs="?",
240
+ help=f"one of: {', '.join(SUBJECTS)} (default: {DEFAULT_SUBJECT})",
241
+ )
242
+ # No default, deliberately: a write must never inherit its environment from
243
+ # `fm use`.
244
+ parser.add_argument(
245
+ "--host",
246
+ default=argparse.SUPPRESS,
247
+ metavar="HOST",
248
+ help="deployment name or API origin (default: formist, or `fm use` for reads); "
249
+ "a write never inherits it",
250
+ )
251
+ parser.add_argument("--space", help="space UUID (never a name)")
252
+ for field, flag, type_, help_text in SETTABLE:
253
+ parser.add_argument(flag, dest=field, type=type_, default=None, help=help_text)
254
+ parser.add_argument(
255
+ "--additional-usage",
256
+ dest="additional_usage",
257
+ choices=("on", "off"),
258
+ default=None,
259
+ help="allow usage to continue past a limit and be settled hourly",
260
+ )
261
+ parser.add_argument(
262
+ "--use-tier-limits",
263
+ dest="use_tier_limits",
264
+ action="store_true",
265
+ help="clear name and the three limits to NULL so they follow --tier's config",
266
+ )
267
+ parser.add_argument(
268
+ "--apply",
269
+ metavar="REVISION",
270
+ default=None,
271
+ help="commit, if the row still matches the revision this dry run printed",
272
+ )
273
+ parser.add_argument("--json", action="store_true", help="raw JSON instead of a report")
274
+
275
+
276
+ def add_parser(subparsers) -> argparse.ArgumentParser:
277
+ parser = subparsers.add_parser(
278
+ "space-plan",
279
+ help=_HELP,
280
+ description=_DESCRIPTION,
281
+ epilog=PLATFORM_ADMIN_GATE_NOTE,
282
+ formatter_class=argparse.RawDescriptionHelpFormatter,
283
+ )
284
+ _add_arguments(parser)
285
+ add_admin_flag(parser)
286
+ return parser
287
+
288
+
289
+ def build_standalone_parser() -> argparse.ArgumentParser:
290
+ """The same parser, detached, so ``--help`` can be asserted in a test."""
291
+ return _build_standalone_parser(add_parser)
292
+
293
+
294
+ def requested_fields(args) -> dict:
295
+ """The plan fields the operator actually named. Absent flag = leave alone.
296
+
297
+ Only keys present here are sent, and the server applies only keys present in
298
+ the body (``model_fields_set``), so omitting a flag never silently NULLs a
299
+ column that somebody else set.
300
+ """
301
+ body = {
302
+ field: getattr(args, field)
303
+ for field, _flag, _type, _help in SETTABLE
304
+ if getattr(args, field, None) is not None
305
+ }
306
+ if getattr(args, "additional_usage", None) is not None:
307
+ body["additional_usage_enabled"] = args.additional_usage == "on"
308
+ if getattr(args, "use_tier_limits", False):
309
+ clashing = [field for field in TIER_FOLLOWING if field in body]
310
+ if clashing:
311
+ raise SpacePlanError(
312
+ "--use-tier-limits clears name and the limits; do not also set " + ", ".join(clashing)
313
+ )
314
+ body.update({field: None for field in TIER_FOLLOWING})
315
+ return body
316
+
317
+
318
+ def _payload(response: object) -> dict:
319
+ """This command's binding of :func:`formist_cli.cli_support.as_dict`.
320
+
321
+ Deliberately not named ``_as_dict``: another module binds the same
322
+ shared body under that name, and two same-named one-line bindings would
323
+ read as one implementation copied into two modules. One shared body,
324
+ one name per module for the binding.
325
+ """
326
+ return as_dict(response, what="/admin/spaces/.../plan", error=SpacePlanError)
327
+
328
+
329
+ def run(args) -> int:
330
+ subject = canonical_subject(getattr(args, "subject", None))
331
+ # for_write on both subjects: `show` is a read, but this command's whole
332
+ # subject matter is a billing write, and a remembered environment is the one
333
+ # an operator forgets they set. Resolving them differently would mean the
334
+ # banner an operator reads on `show` describes a different resolution from the
335
+ # one `set` will use, which is worse than requiring the flag twice.
336
+ ctx = context.resolve(args, for_write=True, need_space=True, need_token=True)
337
+ space = require_space_id(str(ctx.space))
338
+ path = f"/admin/spaces/{space}/plan"
339
+
340
+ if subject == "show":
341
+ payload = _payload(api.admin_get(ctx.target, path, token=ctx.token))
342
+ if args.json:
343
+ print(json.dumps(payload, indent=2, ensure_ascii=False))
344
+ return 0
345
+ target = payload.get("target") or {}
346
+ print(render_target(target, container_app=None))
347
+ print()
348
+ print(render_plan(payload.get("plan")))
349
+ print()
350
+ print(render_effects(payload.get("effects") or {}))
351
+ print(f"\nrevision {payload.get('revision')}")
352
+ return 0
353
+
354
+ fields = requested_fields(args)
355
+ if not fields:
356
+ raise SpacePlanError(
357
+ "nothing to set. Name at least one of:\n "
358
+ + "\n ".join(f"{flag} {help_}" for _f, flag, _t, help_ in SETTABLE)
359
+ + "\n --additional-usage on|off"
360
+ )
361
+
362
+ # The dry run always runs, including on the apply path: a revision proves the
363
+ # operator saw a plan, not that the plan is still true. Re-running is what makes
364
+ # it a check instead of a receipt.
365
+ dry = _payload(api.admin_put(ctx.target, path, fields, token=ctx.token))
366
+ target = dry.get("target") or {}
367
+ revision = str(dry.get("revision"))
368
+
369
+ if not args.apply:
370
+ if args.json:
371
+ print(json.dumps(dry, indent=2, ensure_ascii=False))
372
+ return 0
373
+ print(render_target(target, container_app=None))
374
+ print()
375
+ print(render_change(dry))
376
+ print()
377
+ print(render_effects(dry.get("effects") or {}))
378
+ print(f"\nrevision {revision}")
379
+ print("\nNOTHING WAS WRITTEN. To apply exactly this:\n " + next_command(args, revision))
380
+ return 0
381
+
382
+ if args.apply != revision:
383
+ raise SpacePlanError(
384
+ "REFUSING TO APPLY: this plan row is not the one you were shown.\n"
385
+ f" you supplied: {args.apply}\n"
386
+ f" current row: {revision}\n"
387
+ "\n"
388
+ "Nothing was written. The revision covers the row's identity and every "
389
+ "column this command writes, so the row changed underneath your dry "
390
+ "run: somebody else set a plan, or this revision came from another "
391
+ "space.\n"
392
+ "\n"
393
+ "-> Re-run without --apply, read it, and apply with the revision it prints."
394
+ )
395
+
396
+ applied = _payload(
397
+ api.admin_put(
398
+ ctx.target,
399
+ path,
400
+ fields | {"apply": True, "expect_revision": revision},
401
+ token=ctx.token,
402
+ )
403
+ )
404
+ if args.json:
405
+ print(json.dumps(applied, indent=2, ensure_ascii=False))
406
+ return 0
407
+ print(render_target(target, container_app=None))
408
+ print()
409
+ print(render_change(applied))
410
+ print(f"\nrevision {applied.get('revision')}")
411
+ return 0