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.
formist_cli/prefs.py ADDED
@@ -0,0 +1,328 @@
1
+ """Remembered defaults for ``fm``, and the rule that stops one writing production.
2
+
3
+ A remembered target is a target someone forgets they set, which argues
4
+ for having no memory at all. This module takes a narrower position: a
5
+ remembered value is dangerous when it silently supplies the dangerous
6
+ half of a decision, and the two halves are not equally dangerous.
7
+
8
+ A space is a *what*: 36 characters nobody verifies by eye, and the half a
9
+ transcribed-id mistake lives in. Worth remembering.
10
+
11
+ An env is a *where*: one word, and the half that decides whether this is
12
+ production. Not worth remembering.
13
+
14
+ So: remember the what, require the where. A write resolves its
15
+ environment from the command line only. A read may inherit it, because a
16
+ read against the wrong environment is a wrong answer, while a write
17
+ against the wrong environment is a wrong database.
18
+
19
+ Three properties follow, and they are why this is a flag rather than a prompt:
20
+
21
+ - ``yes |`` cannot defeat it. There is nothing to answer.
22
+ - It survives scripting. A script that writes production contains the string
23
+ ``ae`` in its source, where a reviewer sees it.
24
+ - It cannot be satisfied by habit, because the operator types the environment in
25
+ the same breath as the thing that makes it dangerous.
26
+
27
+ The remaining hazard is a stale default, which is handled by making
28
+ staleness visible rather than by expiring it: :meth:`Effective.banner`
29
+ prints where each half came from and how old it is, on every command
30
+ including reads. Printing the target alone is close to useless, since the
31
+ operator already believes they know it. Printing why it is what it is is
32
+ what breaks a wrong belief.
33
+
34
+ Stdlib only.
35
+ """
36
+
37
+ from __future__ import annotations
38
+
39
+ import json
40
+ import os
41
+ import stat
42
+ from dataclasses import dataclass
43
+ from datetime import datetime, timezone
44
+ from pathlib import Path
45
+
46
+ from formist_cli import tokens
47
+ from formist_cli.targets import (
48
+ DEFAULT_HOST,
49
+ REGION_AE,
50
+ REGION_GLOBAL,
51
+ Target,
52
+ TargetError,
53
+ require_space_id,
54
+ resolve,
55
+ )
56
+
57
+ #: Both ``dev`` and ``local`` are accepted and ``local`` is canonical: it is
58
+ #: what the host allow-list key, the token filename (``token-local.json``) and
59
+ #: every existing string already say, and "dev" is genuinely ambiguous in
60
+ #: this project in a way that would bite (a dev email provider setting, a
61
+ #: dev Attendee instance, a local env file, and "the dev environment" which
62
+ #: is a different thing from this laptop).
63
+ class PrefsError(Exception):
64
+ """A refusal about remembered state."""
65
+
66
+
67
+ _REGION_HOSTS = {REGION_GLOBAL: "evane", REGION_AE: "evane-ae"}
68
+
69
+
70
+ def canonical_env(env: str | None) -> str | None:
71
+ """Normalise a ``--host`` value to the name credentials are stored under.
72
+
73
+ None stays None. Raises :class:`PrefsError` for a value that names no host.
74
+ """
75
+ if env is None:
76
+ return None
77
+ try:
78
+ return resolve(env).name
79
+ except TargetError as exc:
80
+ raise PrefsError(str(exc)) from None
81
+
82
+
83
+ def prefs_path() -> Path:
84
+ return tokens.config_dir() / "prefs.json"
85
+
86
+
87
+ @dataclass(frozen=True)
88
+ class Prefs:
89
+ """What ``fm use`` remembered, and when."""
90
+
91
+ space: str | None = None
92
+ env: str | None = None
93
+ #: The region ``/admin/spaces`` reported for :attr:`space` when it was set.
94
+ #: Used to refuse a contradicting write BEFORE a socket is opened.
95
+ space_region: str | None = None
96
+ set_at: datetime | None = None
97
+
98
+ @property
99
+ def age(self) -> str:
100
+ if self.set_at is None:
101
+ return "unknown age"
102
+ delta = _utcnow() - self.set_at
103
+ seconds = int(delta.total_seconds())
104
+ if seconds < 90:
105
+ return "just now"
106
+ if seconds < 5400:
107
+ return f"{seconds // 60}m ago"
108
+ if seconds < 172800:
109
+ return f"{seconds // 3600}h ago"
110
+ return f"{seconds // 86400}d ago"
111
+
112
+
113
+ def load() -> Prefs:
114
+ path = prefs_path()
115
+ if not path.exists():
116
+ return Prefs()
117
+ try:
118
+ raw = json.loads(path.read_text())
119
+ except (json.JSONDecodeError, OSError) as exc:
120
+ raise PrefsError(
121
+ f"could not read {path}: {exc}\n-> `fm use --clear` to start over."
122
+ ) from exc
123
+ if not isinstance(raw, dict):
124
+ raise PrefsError(f"could not read {path}: expected a JSON object.")
125
+ return Prefs(
126
+ space=raw.get("space"),
127
+ env=raw.get("host"),
128
+ space_region=raw.get("space_region"),
129
+ set_at=_parse_ts(raw.get("set_at")),
130
+ )
131
+
132
+
133
+ _UNSET = object()
134
+
135
+
136
+ def store(
137
+ *,
138
+ space: str | object = _UNSET,
139
+ env: str | object = _UNSET,
140
+ space_region: str | object = _UNSET,
141
+ ) -> Path:
142
+ """Update the remembered defaults, leaving unmentioned fields alone.
143
+
144
+ Partial by design: ``fm use --env ae`` must not silently forget the space the
145
+ operator set five minutes ago.
146
+ """
147
+ current = load()
148
+
149
+ if space is _UNSET:
150
+ new_space = current.space
151
+ elif space is None:
152
+ new_space = None
153
+ else:
154
+ try:
155
+ # A UUID coming out of a file is no more trustworthy than one typed on
156
+ # a command line, so it goes through the same gate.
157
+ new_space = require_space_id(str(space))
158
+ except TargetError as exc:
159
+ raise PrefsError(str(exc)) from None
160
+
161
+ new_env = current.env if env is _UNSET else canonical_env(env) # type: ignore[arg-type]
162
+ new_region = current.space_region if space_region is _UNSET else space_region
163
+
164
+ # A space that changed identity invalidates what we knew about its region.
165
+ if space is not _UNSET and new_space != current.space and space_region is _UNSET:
166
+ new_region = None
167
+
168
+ payload = {
169
+ "space": new_space,
170
+ "host": new_env,
171
+ "space_region": new_region,
172
+ "set_at": _now_iso(),
173
+ }
174
+ directory = tokens.config_dir()
175
+ directory.mkdir(parents=True, exist_ok=True)
176
+ os.chmod(directory, stat.S_IRWXU) # 0700, it sits beside the tokens
177
+ path = prefs_path()
178
+ path.write_text(json.dumps(payload, indent=2))
179
+ return path
180
+
181
+
182
+ def clear() -> bool:
183
+ """Forget everything. True if there was anything to forget."""
184
+ path = prefs_path()
185
+ if not path.exists():
186
+ return False
187
+ path.unlink()
188
+ return True
189
+
190
+
191
+ @dataclass(frozen=True)
192
+ class Effective:
193
+ """The target a command will actually act on, and where each half came from."""
194
+
195
+ target: Target
196
+ space: str | None
197
+ env_source: str
198
+ space_source: str
199
+ for_write: bool
200
+
201
+ def banner(self) -> str:
202
+ """The provenance line printed before every command, reads included.
203
+
204
+ Goes to stderr so it never corrupts piped JSON.
205
+ """
206
+ mode = "WRITE" if self.for_write else "read"
207
+ lines = [
208
+ f"-> {mode} {self.target.name} {self.target.api_base}"
209
+ f" [host: {self.env_source}]"
210
+ ]
211
+ if self.space:
212
+ lines.append(f" space {self.space} [space: {self.space_source}]")
213
+ return "\n".join(lines)
214
+
215
+
216
+ def effective(
217
+ *,
218
+ env_flag: str | None,
219
+ space_flag: str | None,
220
+ for_write: bool,
221
+ ) -> Effective:
222
+ """Resolve the effective target, refusing rather than inheriting a write's env.
223
+
224
+ ``for_write`` is the whole switch. A read inherits ``fm use``'s environment; a
225
+ write refuses to, and says so.
226
+ """
227
+ prefs = load()
228
+ env_flag = canonical_env(env_flag)
229
+
230
+ if env_flag is not None:
231
+ env, env_source = env_flag, "--host flag"
232
+ elif for_write and prefs.env is not None:
233
+ # The one refusal this module exists for.
234
+ raise PrefsError(
235
+ f"refusing to write using a remembered environment.\n"
236
+ f" `fm use` remembers --host {prefs.env} (set {prefs.age}), and a write "
237
+ f"NEVER inherits it.\n"
238
+ "\n"
239
+ "A remembered environment is one somebody forgets they set, and the "
240
+ "cost of forgetting is a write to the wrong database. Naming it costs "
241
+ "one word and puts it in the command you just ran, and in the source "
242
+ "of any script that does this, where a reviewer sees it.\n"
243
+ "\n"
244
+ f"-> Re-run with `--host {prefs.env}` if that is what you meant."
245
+ )
246
+ elif prefs.env is not None:
247
+ env, env_source = prefs.env, f"fm use default, set {prefs.age}"
248
+ else:
249
+ env, env_source = DEFAULT_HOST, "default"
250
+
251
+ if space_flag is not None:
252
+ try:
253
+ space = require_space_id(space_flag)
254
+ except TargetError as exc:
255
+ raise PrefsError(str(exc)) from None
256
+ space_source = "--space flag"
257
+ elif prefs.space:
258
+ space, space_source = prefs.space, f"fm use default, set {prefs.age}"
259
+ else:
260
+ space, space_source = None, "not set"
261
+
262
+ try:
263
+ target = resolve(env)
264
+ except TargetError as exc:
265
+ raise PrefsError(str(exc)) from None
266
+
267
+ # Two guards, and the second one is not obvious:
268
+ #
269
+ # A recorded region describes the REMEMBERED space only. Applying it to a space
270
+ # passed explicitly would refuse a correct write, or, worse, permit a wrong one
271
+ # by vouching for a space it never described.
272
+ #
273
+ # And `space_region` is DATA RESIDENCY (`global` / `ae`, a property of the row)
274
+ # while `env` is a DEPLOYMENT TARGET (`local` / `ae` / `global`, a property of
275
+ # the host). They share two of three tokens and are not the same vocabulary. A
276
+ # local dev server reports every space it holds as `region=global`, its own
277
+ # HOME_REGION, so comparing the two refused every local write, and the
278
+ # refusal's remediation line said `--host evane`, which aims a dev payload at
279
+ # PRODUCTION. A residency claim is only meaningful about a prod target.
280
+ if (
281
+ for_write
282
+ and target.env in (REGION_GLOBAL, REGION_AE)
283
+ and space_flag is None
284
+ and prefs.space
285
+ and prefs.space_region
286
+ and prefs.space_region != target.env
287
+ ):
288
+ raise PrefsError(
289
+ f"refusing to write: the remembered space lives in "
290
+ f"{prefs.space_region!r}, but this command targets {env!r}.\n"
291
+ f" space {prefs.space} was recorded as resident in "
292
+ f"{prefs.space_region} when `fm use` was run ({prefs.age}).\n"
293
+ "\n"
294
+ "Nothing was sent. A space-scoped write must reach the region that owns "
295
+ "the row; the server would answer 421 with where to retry, and fm does "
296
+ "not follow a redirect into a mutation: a redirect is the server "
297
+ "saying your belief about WHERE was wrong, which is the one belief a "
298
+ "write must not be wrong about.\n"
299
+ "\n"
300
+ f"-> `--host {_REGION_HOSTS.get(prefs.space_region, prefs.space_region)}`, or `fm use --space <id>` to re-record "
301
+ "the region if the space has moved."
302
+ )
303
+
304
+ return Effective(
305
+ target=target,
306
+ space=space,
307
+ env_source=env_source,
308
+ space_source=space_source,
309
+ for_write=for_write,
310
+ )
311
+
312
+
313
+ def _parse_ts(value: object) -> datetime | None:
314
+ if not isinstance(value, str):
315
+ return None
316
+ try:
317
+ parsed = datetime.fromisoformat(value)
318
+ except ValueError:
319
+ return None
320
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
321
+
322
+
323
+ def _utcnow() -> datetime:
324
+ return datetime.now(timezone.utc)
325
+
326
+
327
+ def _now_iso() -> str:
328
+ return _utcnow().isoformat()