streamwright-console 0.3.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.
Files changed (55) hide show
  1. streamwright/console/__init__.py +29 -0
  2. streamwright/console/api/__init__.py +20 -0
  3. streamwright/console/api/acks.py +162 -0
  4. streamwright/console/api/app.py +401 -0
  5. streamwright/console/api/login.py +139 -0
  6. streamwright/console/api/logs.py +113 -0
  7. streamwright/console/api/openapi.py +205 -0
  8. streamwright/console/api/query.py +113 -0
  9. streamwright/console/auth/__init__.py +21 -0
  10. streamwright/console/auth/access.py +99 -0
  11. streamwright/console/auth/authenticator.py +45 -0
  12. streamwright/console/auth/passwords.py +83 -0
  13. streamwright/console/auth/sessions.py +65 -0
  14. streamwright/console/auth/sso.py +186 -0
  15. streamwright/console/auth/throttle.py +60 -0
  16. streamwright/console/auth/users.py +111 -0
  17. streamwright/console/cli/__init__.py +21 -0
  18. streamwright/console/cli/admin.py +267 -0
  19. streamwright/console/cli/main.py +110 -0
  20. streamwright/console/config/__init__.py +18 -0
  21. streamwright/console/config/check.py +48 -0
  22. streamwright/console/config/console.py +289 -0
  23. streamwright/console/config/login.py +141 -0
  24. streamwright/console/config/service.py +32 -0
  25. streamwright/console/db/__init__.py +18 -0
  26. streamwright/console/db/migrations/0001_console_users.py +40 -0
  27. streamwright/console/db/migrations/__init__.py +29 -0
  28. streamwright/console/db/tables/__init__.py +34 -0
  29. streamwright/console/db/tables/base.py +24 -0
  30. streamwright/console/db/tables/migrations.py +27 -0
  31. streamwright/console/db/tables/users.py +42 -0
  32. streamwright/console/db/users.py +95 -0
  33. streamwright/console/guide.md +99 -0
  34. streamwright/console/static/app.js +2014 -0
  35. streamwright/console/static/favicon.png +0 -0
  36. streamwright/console/static/favicon.svg +1 -0
  37. streamwright/console/static/index.html +66 -0
  38. streamwright/console/static/streamwright-logo-dark.svg +1 -0
  39. streamwright/console/static/style.css +410 -0
  40. streamwright/console/views/__init__.py +21 -0
  41. streamwright/console/views/attention.py +145 -0
  42. streamwright/console/views/filters.py +62 -0
  43. streamwright/console/views/job_page.py +97 -0
  44. streamwright/console/views/job_runs.py +222 -0
  45. streamwright/console/views/job_summaries.py +123 -0
  46. streamwright/console/views/overview.py +156 -0
  47. streamwright/console/views/reads.py +354 -0
  48. streamwright/console/views/run_log.py +77 -0
  49. streamwright/console/views/stores.py +190 -0
  50. streamwright_console-0.3.0.dist-info/METADATA +109 -0
  51. streamwright_console-0.3.0.dist-info/RECORD +55 -0
  52. streamwright_console-0.3.0.dist-info/WHEEL +5 -0
  53. streamwright_console-0.3.0.dist-info/entry_points.txt +5 -0
  54. streamwright_console-0.3.0.dist-info/licenses/LICENSE +201 -0
  55. streamwright_console-0.3.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,354 @@
1
+ #!/usr/bin/env python
2
+ # /*************************************************************************
3
+ # * Copyright 2026 Karthick Jaganathan
4
+ # *
5
+ # * Licensed under the Apache License, Version 2.0 (the "License");
6
+ # * you may not use this file except in compliance with the License.
7
+ # * You may obtain a copy of the License at
8
+ # *
9
+ # * https://www.apache.org/licenses/LICENSE-2.0
10
+ # *
11
+ # * Unless required by applicable law or agreed to in writing, software
12
+ # * distributed under the License is distributed on an "AS IS" BASIS,
13
+ # * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # * See the License for the specific language governing permissions and
15
+ # * limitations under the License.
16
+ # **************************************************************************/
17
+ """
18
+ What the console shows of an open client, read from its stores: each job and scope's health and latest batch, a job's
19
+ batches, one batch, the leases and the serve runs (the overview's: `overview`). Every function takes an OpenClient and
20
+ returns (result, failed): `failed` names the stores a read could not reach (their error code goes in the result).
21
+ Outbox payloads and results, input rows, serve request bodies and response rows are never read here; error messages
22
+ are shown as the vendor or database wrote them, and may quote a value it rejected.
23
+
24
+ Health of a job and scope, from its latest batch:
25
+ running a batch in received, processing, committed or acked, and the job's lease is held
26
+ held rows whose outcome is unknown wait for `state resend` or `skip`; or a batch was interrupted (the next run
27
+ resumes it)
28
+ failed the latest batch failed or was abandoned
29
+ ok the latest batch completed (or was skipped)
30
+ An acknowledgement (`state ack`) changes no health: it moves an item from Needs attention to Acknowledged.
31
+ """
32
+
33
+ import datetime
34
+ import logging
35
+ from types import MappingProxyType
36
+
37
+ from streamwright.core.jobs.state.attention import batch_items, store_index, with_acks
38
+ from streamwright.core.jobs.state.conditions import meets
39
+
40
+ from streamwright.console.views import attention as needs
41
+ from streamwright.console.views.filters import by_store
42
+
43
+ __all__ = ["HEALTHS", "RUN_SORTS", "SORTS", "ack_of", "batch", "batch_row", "batches", "each_store", "in_full", "jobs",
44
+ "leases", "only_store", "runs", "store_errors"]
45
+
46
+ LOG = logging.getLogger("streamwright.console")
47
+ HEALTHS = ("failed", "held", "rejected", "running", "ok") # what needs a person first
48
+ SORTS = ("last", "job", "health", "duration", "rows", "store")
49
+ RUN_SORTS = ("queued", "job", "caller", "status", "run")
50
+ _DAY = datetime.timedelta(hours=24)
51
+ _ROW_LIMIT = 500
52
+
53
+
54
+ def each_store(opened, read, only=None):
55
+ """
56
+ {store: read(store)} of the reachable stores, the others in errors; (found, failed store names). With `only`
57
+ ({store: value}): read(store, value) of those stores alone.
58
+ """
59
+ found, failed = {}, []
60
+ for name, store in opened.stores.items():
61
+ if only is not None and name not in only:
62
+ continue
63
+ try:
64
+ found[name] = read(store) if only is None else read(store, only[name])
65
+ except Exception as exc: # a driver's own error: the store is unreachable for now
66
+ LOG.warning("%s", opened.redact("client %s, store %s: %s: %s" % (
67
+ opened.client.id, name, type(exc).__name__, str(exc).splitlines()[0] if str(exc) else "")))
68
+ failed.append(name)
69
+ return found, failed
70
+
71
+
72
+ def store_errors(opened, failed):
73
+ return {**opened.errors, **dict.fromkeys(failed, "unreachable")}
74
+
75
+
76
+ def batch_row(batch, outbox):
77
+ """A batch as the console lists it (no manifest): status, times, rows written, its outbox by status, its error."""
78
+ return {"job_id": batch["batch_id"], "status": batch["status"], "attempts": batch["attempts"],
79
+ "failed_from": batch["failed_from"], "created_at": batch["created_at"], "started_at": batch["started_at"],
80
+ "finished_at": batch["finished_at"], "updated_at": batch["updated_at"], "duration_ms": batch["duration_ms"],
81
+ "rows_written": batch["rows_written"], "outbox": outbox or {},
82
+ "request_id": (batch.get("engine_metadata") or {}).get("request_id"),
83
+ "resumed_by": (batch.get("engine_metadata") or {}).get("resumed_by"), "error": batch["error"]}
84
+
85
+
86
+ def _tagged(tags, ignored):
87
+ """"3 unclassified, 2 bad_email": rows by tag ({(tag, then): rows}), the ignored ones or the others, most first."""
88
+ picked = sorted(((rows, tag) for (tag, then), rows in (tags or {}).items() if (then == "ignore") == ignored),
89
+ key=lambda item: (-item[0], item[1]))
90
+ return ", ".join("%d %s" % item for item in picked)
91
+
92
+
93
+ def _issue(health, batch, unknown, *, rejected=0, outbox=None, tags=None):
94
+ if health == "held":
95
+ return ("%d row(s) with an unknown outcome: check the vendor, then resend or skip" % unknown if unknown
96
+ else "interrupted while %s: the next run resumes it" % batch["status"])
97
+ if health == "failed":
98
+ return batch["error"] or batch["status"]
99
+ ignored = sum(rows for (_, then), rows in (tags or {}).items() if then == "ignore")
100
+ known = "%d ignored (%s)" % (ignored, _tagged(tags, True)) if ignored else None
101
+ if health == "rejected":
102
+ named = _tagged(tags, False)
103
+ return "%d of %d row(s) rejected%s%s" % (rejected, max(rejected, sum((outbox or {}).values())),
104
+ " (%s)" % named if named else "", "; " + known if known else "")
105
+ return known if health == "ok" else None
106
+
107
+
108
+ def _details(store, entries, now, *, acks=True, keys=False):
109
+ """
110
+ The rows shown of a store's index `entries`: each newest batch in full, its outbox and rejected rows by tag, last
111
+ success, last 24 h, and (`acks`) the acknowledgement of what it needs; `keys`: the job key an abandoned one still
112
+ claims (forget-key lets it go).
113
+ """
114
+ ids = {}
115
+ for entry in entries:
116
+ ids.setdefault(entry["batch"]["job_name"], []).append(entry["batch"]["batch_id"])
117
+ batches, outbox, tags, claimed = {}, {}, {}, {}
118
+ for job_name, batch_ids in ids.items():
119
+ batches.update(((job_name, batch["batch_id"]), batch) for batch in store.batches_by_id(job_name, batch_ids))
120
+ outbox.update(store.count_events(job_name, batch_ids))
121
+ tags.update(store.rejected_tags(job_name, batch_ids))
122
+ abandoned = [entry["batch"]["batch_id"] for entry in entries
123
+ if entry["batch"]["job_name"] == job_name and entry["batch"]["status"] == "abandoned"]
124
+ if keys and abandoned:
125
+ claimed.update(((job_name, batch_id), key) for batch_id, key in store.job_keys_of(job_name,
126
+ abandoned).items())
127
+ counts, succeeded = store.batch_counts(now - _DAY, sorted(ids)), store.last_completed(sorted(ids))
128
+ light = batch_items(entries) if acks else []
129
+ with_acks(store, light)
130
+ acked = {(item["job"], item["scope"]): item["ack"] for item in light}
131
+ rows = []
132
+ for entry in entries:
133
+ key = (entry["batch"]["job_name"], entry["batch"]["scope"])
134
+ batch, held, lease = batches.get((key[0], entry["batch"]["batch_id"])), entry["held"], entry["lease"]
135
+ if batch is None: # purged since the index was read
136
+ continue
137
+ row = {"job": key[0], "scope": key[1], "health": entry["health"],
138
+ "issue": _issue(entry["health"], batch, entry["unknown"], rejected=entry["rejected"],
139
+ outbox=outbox.get(batch["batch_id"]), tags=tags.get(batch["batch_id"])),
140
+ "last": batch_row(batch, outbox.get(batch["batch_id"])), "last_success": succeeded.get(key),
141
+ "day": counts.get(key, {}), "unknown_rows": entry["unknown"], "rejected_rows": entry["rejected"],
142
+ "held_batch": (batch["batch_id"] if batch["batch_id"] in held else held[0]) if held else None,
143
+ "lease": {"holder": lease["owner_id"], "expires_at": lease["expires_at"]} if lease else None,
144
+ "ack": acked.get(key)}
145
+ if keys:
146
+ row["key"] = claimed.get((key[0], batch["batch_id"]))
147
+ rows.append(row)
148
+ return rows
149
+
150
+
151
+ def _when(text):
152
+ return datetime.datetime.fromisoformat(str(text).replace("Z", "+00:00")) if text else None
153
+
154
+
155
+ _SORT_KEYS = MappingProxyType({
156
+ "last": lambda entry: _when(entry["batch"]["created_at"]),
157
+ "job": lambda entry: (entry["batch"]["job_name"].lower(), entry["batch"]["scope"].lower()),
158
+ "health": lambda entry: HEALTHS.index(entry["health"]),
159
+ "duration": lambda entry: entry["batch"]["duration_ms"],
160
+ "rows": lambda entry: entry["batch"]["rows_written"],
161
+ "store": lambda entry: entry["store"].lower(),
162
+ })
163
+
164
+
165
+ def _ordered(entries, sort, descending):
166
+ """`entries` by `sort` (equal ones newest first; a missing value last, either way)."""
167
+ entries = sorted(entries, key=lambda entry: (entry["batch"]["job_name"], entry["batch"]["scope"], entry["store"]))
168
+ entries.sort(key=_SORT_KEYS["last"], reverse=True)
169
+ key = _SORT_KEYS[sort]
170
+ present = sorted((entry for entry in entries if key(entry) is not None), key=key, reverse=descending)
171
+ return present + [entry for entry in entries if key(entry) is None]
172
+
173
+
174
+ def _matches(entry, text, since, until):
175
+ created = _when(entry["batch"]["created_at"])
176
+ found = " ".join((entry["batch"]["job_name"], entry["batch"]["scope"], entry["store"])).lower()
177
+ return ((not text or text.lower() in found) and (since is None or (created and created >= since))
178
+ and (until is None or (created and created < until)))
179
+
180
+
181
+ def jobs(opened, *, health=None, text=None, since=None, until=None, sort="last", descending=None, store=None,
182
+ limit=50, offset=0, now=None, job=None, conditions=()):
183
+ """
184
+ A page of the client's jobs and scopes, every store's (or `store`'s), of one `job` or all: those whose job, scope or
185
+ store holds `text` and that meet the filter `conditions` (on job, scope and store), whose newest batch was made in
186
+ [since, until) (aware datetimes) and, of those, whose health is `health`; sorted by `sort` (SORTS: newest first by
187
+ default; `descending` defaults to True for last, duration and rows). With `total`
188
+ (after every filter), `counts`: each health's number before the health filter, and `outside`: the jobs and scopes
189
+ the text would show whose newest batch is outside [since, until). Only the page is read in full.
190
+ """
191
+ now = now or datetime.datetime.now(datetime.UTC)
192
+ opened = only_store(opened, store) if store else opened
193
+ found, failed = each_store(opened, store_index)
194
+ named = [entry for entry in (dict(entry, store=name) for name, entries in found.items() for entry in entries)
195
+ if _matches(entry, text, None, None) and job in (None, entry["batch"]["job_name"])
196
+ and meets(conditions, {"job": entry["batch"]["job_name"], "scope": entry["batch"]["scope"],
197
+ "store": entry["store"]})]
198
+ listed = [entry for entry in named if _matches(entry, None, since, until)]
199
+ counts = {name: sum(1 for entry in listed if entry["health"] == name) for name in HEALTHS}
200
+ listed = [entry for entry in listed if health is None or entry["health"] == health]
201
+ descending = sort in ("last", "duration", "rows") if descending is None else descending
202
+ page = _ordered(listed, sort, descending)[offset:offset + limit]
203
+ rows, also_failed = in_full(opened, page, now)
204
+ failed = failed + also_failed
205
+ return {"client": opened.client.id, "jobs": rows, "total": len(listed), "counts": counts,
206
+ "outside": len(named) - sum(counts.values()), "limit": limit, "offset": offset,
207
+ "errors": store_errors(opened, failed)}, failed
208
+
209
+
210
+ def in_full(opened, entries, now, **options):
211
+ """The rows of index `entries` (of several stores) in full, in their order (`options`: _details'); (rows, failed
212
+ store names)."""
213
+ per_store = {}
214
+ for entry in entries:
215
+ per_store.setdefault(entry["store"], []).append(entry)
216
+ found, failed = each_store(opened, lambda store, mine: _details(store, mine, now, **options), per_store)
217
+ rows = {(name, row["job"], row["scope"]): dict(row, store=name) for name, items in found.items() for row in items}
218
+ keys = ((entry["store"], entry["batch"]["job_name"], entry["batch"]["scope"]) for entry in entries)
219
+ return [rows[key] for key in keys if key in rows], failed
220
+
221
+
222
+ def batches(opened, store_name, job, *, scope=None, status=None, limit=50):
223
+ """A job's batches in one store, newest first, as `streamwright state list --json` lists them."""
224
+ def read(store):
225
+ found = store.find_batches(job_name=job, scope=scope, status=status, limit=limit)
226
+ outbox = store.count_events(job, [batch["batch_id"] for batch in found])
227
+ return [dict(batch_row(batch, outbox.get(batch["batch_id"])), scope=batch["scope"]) for batch in found]
228
+
229
+ found, failed = each_store(only_store(opened, store_name), read)
230
+ return {"client": opened.client.id, "store": store_name, "job": job, "batches": found.get(store_name, []),
231
+ "errors": store_errors(only_store(opened, store_name), failed)}, failed
232
+
233
+
234
+ def batch(opened, store_name, job_id, job=None):
235
+ """
236
+ One batch: its record, a summary of its manifest (no row), its receipts and its outbox (no payload), its problem
237
+ (failed, held, interrupted, rejected or none), its acknowledgement and the commands that settle it.
238
+ """
239
+ def read(store):
240
+ matches = store.find_batches(job_name=job, batch_id=job_id, limit=2)
241
+ if len(matches) != 1:
242
+ return None
243
+ found = matches[0]
244
+ name, status = found["job_name"], found["status"]
245
+ receipts = {output: {key: receipt.get(key) for key in ("destination", "rows", "files", "version",
246
+ "already_committed")}
247
+ for output, receipt in store.get_receipts(name, job_id).items()}
248
+ problem = store.batch_problem(name, job_id, status)
249
+ ack = ack_of(store, name, job_id, problem)
250
+ key = store.job_keys_of(name, [job_id]).get(job_id) if status == "abandoned" else None
251
+ return dict(batch_row(found, None), job=name, scope=found["scope"], job_key=found["job_key"],
252
+ manifest=_manifest(found["manifest"]), receipts=receipts,
253
+ outbox=store.outbox_counts(name, job_id),
254
+ outbox_rows=store.batch_outbox(name, job_id, ("failed", "in_flight", "pending"), _ROW_LIMIT),
255
+ problem=problem, ack=ack, commands=needs.batch_commands(
256
+ name, job_id, status, held=problem == "held", problem=problem, ack=ack, key=key))
257
+
258
+ found, failed = each_store(only_store(opened, store_name), read)
259
+ return found.get(store_name), failed
260
+
261
+
262
+ def ack_of(store, job_name, target, kind):
263
+ """The acknowledgement ({by, at, note}) of a batch's or run's problem `kind` (none: None)."""
264
+ item = {"kind": kind, "job": job_name, "job_id": target, "ack": None}
265
+ if kind:
266
+ with_acks(store, [item])
267
+ return item["ack"]
268
+
269
+
270
+ def _manifest(manifest):
271
+ """What a batch pinned, without its rows: its time and run, lock inputs, input rows' count and fingerprint."""
272
+ manifest = manifest or {}
273
+ shown = {"batch_ts": manifest.get("batch_ts"), "run_id": manifest.get("run_id")}
274
+ if isinstance(manifest.get("inputs"), dict):
275
+ inputs = manifest["inputs"]
276
+ shown["inputs"] = {key: inputs.get(key) for key in ("config", "tokens") if key in inputs}
277
+ if isinstance(manifest.get("input"), dict):
278
+ shown["input"] = {key: manifest["input"].get(key) for key in ("rows", "sha256")}
279
+ if manifest.get("messages"):
280
+ shown["messages"] = len(manifest["messages"])
281
+ for key in ("pinned", "carry"): # their values come from data: only their names
282
+ if manifest.get(key):
283
+ shown[key] = sorted(manifest[key])
284
+ return shown
285
+
286
+
287
+ def leases(opened, now=None, conditions=()):
288
+ """Every lease of the client's stores (meeting the filter `conditions`): job, token, holder, epoch, expiry, held."""
289
+ opened, conditions = by_store(opened, conditions)
290
+ found, failed = each_store(opened, lambda store: store.all_leases(conditions))
291
+ return {"client": opened.client.id, "leases": [
292
+ {"store": name, "job": lease["job_name"], "token": lease["token"], "holder": lease["owner_id"],
293
+ "holder_run": needs.holder_run(lease["owner_id"]), "epoch": lease["epoch"], "expires_at": lease["expires_at"],
294
+ "held": lease["held"]}
295
+ for name, items in found.items() for lease in items], "errors": store_errors(opened, failed)}, failed
296
+
297
+
298
+ # a run sort: (the store's column, the shown run's key, in the order the store gives)
299
+ _RUN_KEYS = MappingProxyType({
300
+ "queued": ("created_at", lambda run: _when(run["created_at"])),
301
+ "job": ("job_name", lambda run: run["job"].lower()),
302
+ "caller": ("principal", lambda run: run["caller"].lower()),
303
+ "status": ("status", lambda run: run["status"].lower()),
304
+ "run": ("run_id", lambda run: run["run_id"].lower()),
305
+ })
306
+
307
+
308
+ def runs(opened, *, job=None, statuses=(), since=None, until=None, sort="queued", descending=None, limit=50,
309
+ offset=0, conditions=()):
310
+ """
311
+ A page of the serve runs of the client's stores that are serve queues, made in [since, until) (aware datetimes)
312
+ and meeting the filter `conditions` (filters.SERVE_RUN_FIELDS), sorted by `sort` (RUN_SORTS: newest first by
313
+ default; `descending` defaults to True for queued), with their `total`: who asked, how it went; never inputs or
314
+ rows.
315
+ """
316
+ column, key = _RUN_KEYS[sort]
317
+ descending = sort == "queued" if descending is None else descending
318
+ opened, conditions = by_store(opened, conditions)
319
+ found, failed = each_store(opened, lambda store: (
320
+ store.list_requests(job_name=job, statuses=statuses, since=since, until=until, sort=column,
321
+ descending=descending, limit=offset + limit, conditions=conditions),
322
+ store.count_requests(statuses, job, since=since, until=until, conditions=conditions)))
323
+ shown = [dict(_run(run), store=name) for name, (items, _) in found.items() for run in items]
324
+ shown.sort(key=lambda run: (_when(run["created_at"]), run["run_id"]), reverse=True) # equals: newest first
325
+ shown.sort(key=key, reverse=descending)
326
+ return {"client": opened.client.id, "runs": shown[offset:offset + limit],
327
+ "total": sum(total for _, total in found.values()), "limit": limit, "offset": offset,
328
+ "errors": store_errors(opened, failed)}, failed
329
+
330
+
331
+ def _run(run):
332
+ result = run["result"] if isinstance(run["result"], dict) else {}
333
+ summary = {"outputs": result.get("outputs") or [],
334
+ "responses": {name: {key: entry.get(key) for key in ("total", "complete", "truncated", "expired")}
335
+ for name, entry in (result.get("responses") or {}).items()},
336
+ "downloads": {name: len(entry.get("files") or ())
337
+ for name, entry in (result.get("downloads") or {}).items()}}
338
+ return {"run_id": run["run_id"], "job": run["job_name"], "caller": run["principal"], "status": run["status"],
339
+ "attempts": run["attempts"], "request_id": run["request_id"], "created_at": run["created_at"],
340
+ "started_at": run["started_at"], "finished_at": run["finished_at"], "error_code": run["error_code"],
341
+ "error_message": run["error_message"], "result": summary}
342
+
343
+
344
+ def only_store(opened, store_name):
345
+ """The OpenClient narrowed to one store (KeyError for a store the client does not have)."""
346
+ if store_name not in opened.client.stores:
347
+ raise KeyError(store_name)
348
+ narrowed = type(opened)(opened.client, opened_at=opened.opened_at, redact=opened.redact)
349
+ if store_name in opened.stores:
350
+ narrowed.stores = {store_name: opened.stores[store_name]}
351
+ if store_name in opened.errors:
352
+ narrowed.errors = {store_name: opened.errors[store_name]}
353
+ return narrowed
354
+
@@ -0,0 +1,77 @@
1
+ #!/usr/bin/env python
2
+ # /*************************************************************************
3
+ # * Copyright 2026 Karthick Jaganathan
4
+ # *
5
+ # * Licensed under the Apache License, Version 2.0 (the "License");
6
+ # * you may not use this file except in compliance with the License.
7
+ # * You may obtain a copy of the License at
8
+ # *
9
+ # * https://www.apache.org/licenses/LICENSE-2.0
10
+ # *
11
+ # * Unless required by applicable law or agreed to in writing, software
12
+ # * distributed under the License is distributed on an "AS IS" BASIS,
13
+ # * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # * See the License for the specific language governing permissions and
15
+ # * limitations under the License.
16
+ # **************************************************************************/
17
+ """
18
+ A run's own log file (sw_run_logs, written with --log-dir), as the console shows it: where it is, and a page of its
19
+ lines read from the store's logs.dir (core's run_log_read); or why this host cannot read it: the file is on another
20
+ host, retention deleted it, or its path is not that run's (refused).
21
+ """
22
+
23
+ from streamwright.core.runtime.logs.run_log_read import LogPathError, RunLogReader, resolve
24
+
25
+ from streamwright.console.views.job_runs import LOG_FIELDS, PENDING, history
26
+ from streamwright.console.views.reads import each_store, only_store
27
+
28
+ __all__ = ["is_pending", "log_entry", "log_page", "log_reader"]
29
+
30
+
31
+ def log_entry(opened, store_name, run_id, job=None):
32
+ """
33
+ (the run's sw_run_logs row, failed stores): None when it has none; PENDING when the store's tables need a
34
+ migration; {"several": why} for a run id several jobs have (without `job`).
35
+ """
36
+ def read(store):
37
+ try:
38
+ return store.get_run_log(job, run_id)
39
+ except ValueError as exc: # the run id is several jobs'
40
+ return {"several": str(exc)}
41
+
42
+ found, failed = each_store(only_store(opened, store_name), history(read))
43
+ return found.get(store_name), failed
44
+
45
+
46
+ def log_reader(directory, entry, run_id):
47
+ """(the reader of the run's file under `directory`, None) or (None, (reason, why)): refused, missing, unreadable."""
48
+ try:
49
+ return RunLogReader(resolve(directory, entry, entry["job_name"], run_id), entry.get("blocks")), None
50
+ except LogPathError as exc:
51
+ return None, ("refused", str(exc))
52
+ except FileNotFoundError:
53
+ return None, ("missing", "not in this host's log folder: the run wrote it on %s, or it is past its "
54
+ "retention" % (entry.get("host") or "another host"))
55
+ except OSError as exc:
56
+ return None, ("unreadable", "this host cannot read it: %s" % (exc.strerror or exc))
57
+
58
+
59
+ def log_page(directory, entry, run_id, **page):
60
+ """
61
+ {log: where the run's log is (its sw_run_logs row: host, path, status, sizes, counts, times), readable, and a page
62
+ of its lines (RunLogReader.page's: lines, before, after, more, reset); or reason (refused, missing, unreadable) and
63
+ message: why this host cannot read it}.
64
+ """
65
+ shown = {"log": {key: entry.get(key) for key in LOG_FIELDS}}
66
+ reader, problem = log_reader(directory, entry, run_id)
67
+ if reader is not None:
68
+ try:
69
+ return dict(shown, readable=True, reason=None, message=None, **reader.page(**page))
70
+ except OSError as exc: # deleted (retention) or compressed while it was read
71
+ problem = ("missing", "it went while it was read: %s" % (exc.strerror or exc))
72
+ return dict(shown, readable=False, reason=problem[0], message=problem[1], lines=[], before=None, after=None,
73
+ more=False, reset=False)
74
+
75
+
76
+ def is_pending(found):
77
+ return isinstance(found, str) and found == PENDING
@@ -0,0 +1,190 @@
1
+ #!/usr/bin/env python
2
+ # /*************************************************************************
3
+ # * Copyright 2026 Karthick Jaganathan
4
+ # *
5
+ # * Licensed under the Apache License, Version 2.0 (the "License");
6
+ # * you may not use this file except in compliance with the License.
7
+ # * You may obtain a copy of the License at
8
+ # *
9
+ # * https://www.apache.org/licenses/LICENSE-2.0
10
+ # *
11
+ # * Unless required by applicable law or agreed to in writing, software
12
+ # * distributed under the License is distributed on an "AS IS" BASIS,
13
+ # * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # * See the License for the specific language governing permissions and
15
+ # * limitations under the License.
16
+ # **************************************************************************/
17
+ """
18
+ The clients a console has open. When a client is picked its lookups run (the jobs' Lookups resolve its secrets), its
19
+ state blocks are rendered with them and its stores opened as they are: nothing is created or migrated, a SQLite or
20
+ DuckDB file must exist. A client stays open for cache.ttl, at most cache.clients of them (the least recently used is
21
+ dropped first). The resolved values live only here; log lines pass through the client's redactor, and a store that
22
+ cannot be opened is an error code to the caller (`secrets-failed`, `secrets-missing`, `unreachable`). A store is
23
+ opened to write only to record an acknowledgement (writer), never a DuckDB file (a job holds it).
24
+ """
25
+
26
+ import logging
27
+ import os
28
+ import threading
29
+ import time
30
+ import urllib.parse
31
+ from collections import OrderedDict
32
+ from dataclasses import dataclass, field, replace
33
+ from typing import Any
34
+
35
+ from streamwright.core.http_service.state import state_spec
36
+ from streamwright.core.http_service.state_store import open_state
37
+ from streamwright.core.jobs.lookups import LookupExecNotAllowedError, LookupFailedError, Lookups, LookupValueError
38
+ from streamwright.core.jobs.state.url import StateDatabaseMissingError
39
+ from streamwright.core.runtime.redact import Redactor
40
+
41
+ __all__ = ["ERROR_SECONDS", "ClientStores", "OpenClient", "bounded", "duckdb_store"]
42
+
43
+ ERROR_SECONDS = 30 # a lookup that failed (a throttled secrets API) is tried again
44
+
45
+ LOG = logging.getLogger("streamwright.console")
46
+ _LOOKUP_ERRORS = (LookupFailedError, LookupExecNotAllowedError, LookupValueError, OSError, ValueError, KeyError)
47
+
48
+
49
+ @dataclass
50
+ class OpenClient:
51
+ """A picked client: its open stores by name, and the stores that could not be opened (name -> error code)."""
52
+ client: Any
53
+ stores: dict = field(default_factory=dict)
54
+ errors: dict = field(default_factory=dict)
55
+ specs: dict = field(default_factory=dict) # name -> its StateSpec, secrets rendered (to open a writer)
56
+ opened_at: float = 0.0
57
+ redact: Any = None
58
+
59
+
60
+ class ClientStores:
61
+ def __init__(self, console, *, environ=None, clock=time.monotonic, opener=None, writer=None):
62
+ """`opener(spec)`: a StateStore from a StateSpec (default: the serve queue's, for existing databases only);
63
+ `writer(spec)`: the same, opened to write."""
64
+ self.console, self.environ, self.clock = console, environ, clock
65
+ self.opener = opener or (lambda spec: open_state(bounded(spec), existing=True, read_only=True))
66
+ self.write_opener = writer or (lambda spec: open_state(bounded(spec), existing=True))
67
+ self._open = OrderedDict() # client id -> OpenClient, least recently used first
68
+ self._lock = threading.Lock()
69
+ self._locks = {} # client id -> the lock its opening holds
70
+
71
+ def _fresh(self, found):
72
+ """A client stays open for cache.ttl; one whose stores could not be opened, ERROR_SECONDS at most."""
73
+ kept = min(self.console.cache_seconds, ERROR_SECONDS) if found.errors else self.console.cache_seconds
74
+ return self.clock() - found.opened_at < kept
75
+
76
+ def get(self, client_id):
77
+ """The OpenClient of `client_id` (opened when it is not, or no longer is, open)."""
78
+ with self._lock:
79
+ found = self._open.get(client_id)
80
+ if found is not None and self._fresh(found):
81
+ self._open.move_to_end(client_id)
82
+ return found
83
+ opening = self._locks.setdefault(client_id, threading.Lock())
84
+ with opening: # one opening per client; others wait for it
85
+ with self._lock:
86
+ found = self._open.get(client_id)
87
+ if found is not None and self._fresh(found):
88
+ return found
89
+ opened = self._opened(self.console.clients[client_id])
90
+ with self._lock:
91
+ self._open[client_id] = opened
92
+ self._open.move_to_end(client_id)
93
+ while len(self._open) > self.console.cache_clients:
94
+ self._open.popitem(last=False)
95
+ return opened
96
+
97
+ def reopen(self, client_id, failed):
98
+ """
99
+ The client opened again, its secrets looked up afresh (a rotated password), after a read of `failed` (the
100
+ OpenClient it used) failed; None while `failed` was opened less than ERROR_SECONDS ago (a store that is down
101
+ is not looked up again on every call). Concurrent failures reopen it once.
102
+ """
103
+ if self.clock() - failed.opened_at < ERROR_SECONDS:
104
+ return None
105
+ with self._lock:
106
+ if self._open.get(client_id) is failed:
107
+ self._open.pop(client_id)
108
+ return self.get(client_id)
109
+
110
+ def _opened(self, client):
111
+ redact = Redactor()
112
+ opened = OpenClient(client, opened_at=self.clock(), redact=redact)
113
+ try:
114
+ secrets = self._secrets(client, redact)
115
+ except _LOOKUP_ERRORS as exc:
116
+ LOG.warning("%s", redact("client %s: its secrets cannot be looked up: %s: %s" % (
117
+ client.id, type(exc).__name__, exc)))
118
+ opened.errors = dict.fromkeys(client.stores, "secrets-failed")
119
+ return opened
120
+ for name, block in client.stores.items():
121
+ problems = []
122
+ environ = os.environ if self.environ is None else self.environ
123
+ spec = state_spec(block["state"], client.folder, environ, problems, known=secrets, queue=False,
124
+ enrol=redact.add)
125
+ if problems:
126
+ LOG.warning("%s", redact("client %s, store %s: %s" % (client.id, name, "; ".join(problems))))
127
+ opened.errors[name] = "secrets-missing"
128
+ continue
129
+ try:
130
+ opened.stores[name] = self.opener(spec)
131
+ opened.specs[name] = spec
132
+ except StateDatabaseMissingError as exc: # a SQLite or DuckDB file no run has created yet
133
+ LOG.info("%s", redact("client %s, store %s: %s" % (client.id, name, exc)))
134
+ opened.errors[name] = "not-created"
135
+ except (ValueError, ImportError, OSError) as exc:
136
+ LOG.warning("%s", redact("client %s, store %s: cannot be opened: %s" % (client.id, name, exc)))
137
+ opened.errors[name] = "unreachable"
138
+ return opened
139
+
140
+ def writer(self, client_id, name):
141
+ """(the client's store `name` opened to write, None), or (None, why: its error code, or `duckdb`)."""
142
+ opened = self.get(client_id)
143
+ if duckdb_store(opened.client.stores[name]):
144
+ return None, "duckdb"
145
+ if name not in opened.specs:
146
+ return None, opened.errors.get(name, "unreachable")
147
+ try:
148
+ return self.write_opener(opened.specs[name]), None
149
+ except (StateDatabaseMissingError, ValueError, ImportError, OSError) as exc:
150
+ LOG.warning("%s", opened.redact("client %s, store %s: cannot be opened to write: %s" % (
151
+ client_id, name, exc)))
152
+ return None, "unreachable"
153
+
154
+ def _secrets(self, client, redact):
155
+ """The client's secrets by name: its lookups' values (STREAMWRIGHT_SECRET_* fill the others)."""
156
+ if not client.secrets:
157
+ return {}
158
+ definitions = {name: {"type": "string", **dict(definition or {})}
159
+ for name, definition in client.secrets.items()}
160
+ job = {"spec": {"lookups": dict(client.lookups), "secrets": definitions}}
161
+ lookups = Lookups(job, allow_exec=self.console.allow_lookup_exec, enrol=redact.add, base_dir=client.folder)
162
+ _, found = lookups.inputs()
163
+ for value in found.values():
164
+ if isinstance(value, str) and value:
165
+ redact.add(value)
166
+ return {name: value for name, value in found.items() if value is not None}
167
+
168
+
169
+ def bounded(spec):
170
+ """
171
+ The StateSpec with a 5-second connect timeout for a PostgreSQL URL that sets none: a store down does not hold a
172
+ page for the operating system's TCP timeout. (libpq applies it client-side, so PgBouncer is unaffected; MySQL's
173
+ driver already stops after 10 seconds.)
174
+ """
175
+ if spec.url is None:
176
+ return spec
177
+ parsed = urllib.parse.urlsplit(spec.url)
178
+ query = urllib.parse.parse_qsl(parsed.query, keep_blank_values=True)
179
+ if parsed.scheme.lower() not in ("postgresql", "postgres") or any(key == "connect_timeout" for key, _ in query):
180
+ return spec
181
+ query.append(("connect_timeout", "5"))
182
+ return replace(spec, url=urllib.parse.urlunsplit(parsed._replace(
183
+ query=urllib.parse.urlencode(query, quote_via=urllib.parse.quote))))
184
+
185
+
186
+ def duckdb_store(block):
187
+ """Whether a client's store (its `state` block) is a DuckDB file: one process writes it at a time (a job)."""
188
+ state = block.get("state") or {}
189
+ return str(state.get("url") or "").startswith("duckdb:") or str(
190
+ (state.get("connection") or {}).get("provider") or "") == "duckdb"