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,97 @@
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 console's page of one job, every store's (or one's): its runs in a period (how many ended how, the median and p95
19
+ duration, the newest), its batches in that period (by status, rows written, outputs, rows applied and rejected, the
20
+ rejected rows grouped by error), and its scopes' health now. Takes an OpenClient; returns (result, failed store names).
21
+ """
22
+
23
+ import math
24
+
25
+ from streamwright.console.views import reads
26
+ from streamwright.console.views.job_runs import PENDING, outputs_of, totals_of
27
+ from streamwright.console.views.reads import each_store, only_store, store_errors
28
+
29
+ __all__ = ["job_page"]
30
+
31
+ _RECENT = 20
32
+
33
+
34
+ def _percentile(durations, share):
35
+ return durations[max(0, math.ceil(share * len(durations)) - 1)] if durations else None
36
+
37
+
38
+ def _merged(parts, key):
39
+ """{name: {status: n}} of every store's part summed."""
40
+ total = {}
41
+ for part in parts:
42
+ for name, by_status in part[key].items():
43
+ entry = total.setdefault(name, {})
44
+ for status, count in by_status.items():
45
+ entry[status] = entry.get(status, 0) + count
46
+ return total
47
+
48
+
49
+ def job_page(opened, job, *, since=None, until=None, store=None, now=None):
50
+ """One job's page: runs and batches started in [since, until) (aware datetimes), its scopes' health now."""
51
+ narrowed = only_store(opened, store) if store else opened
52
+
53
+ def read(state):
54
+ period, pending = {"since": since, "until": until}, state.migrations().pending()
55
+ return {"pending": bool(pending), "counts": state.insight_counts(job, **period),
56
+ "runs": {"statuses": {}, "durations": []} if pending else state.run_stats(job, **period),
57
+ "recent": [] if pending else state.list_runs(job, limit=_RECENT, **period),
58
+ "outbox": state.insight_outbox(job, **period), "receipts": state.insight_receipts(job, **period),
59
+ "rejections": state.insight_errors(job, limit=20, **period)}
60
+
61
+ found, failed = each_store(narrowed, read)
62
+ parts = list(found.values())
63
+ statuses = {}
64
+ for part in parts:
65
+ for status, count in part["runs"]["statuses"].items():
66
+ statuses[status] = statuses.get(status, 0) + count
67
+ durations = sorted(duration for part in parts for duration in part["runs"]["durations"])
68
+ ended = statuses.get("succeeded", 0) + statuses.get("failed", 0)
69
+ counts = {"statuses": {}, "rows_written": sum(part["counts"]["rows_written"] for part in parts)}
70
+ for part in parts:
71
+ for status, count in part["counts"]["statuses"].items():
72
+ counts["statuses"][status] = counts["statuses"].get(status, 0) + count
73
+ receipts = {}
74
+ for part in parts:
75
+ for name, entry in part["receipts"].items():
76
+ total = receipts.setdefault(name, {"rows": 0, "files": 0, "batches": 0})
77
+ for key in total:
78
+ total[key] += entry[key]
79
+ outbox = _merged(parts, "outbox")
80
+ recent = sorted(({"store": name, "job": run["job_name"], "run_id": run["run_id"], "status": run["status"],
81
+ "started_at": run["started_at"], "duration_ms": run["duration_ms"], "batches": run["batches"],
82
+ "passes": run["passes"], "failed_passes": run["failed_passes"],
83
+ "unbatched_failures": run["unbatched_failures"], "error": run["error_message"]}
84
+ for name, part in found.items() for run in part["recent"]),
85
+ key=lambda run: run["started_at"] or "", reverse=True)[:_RECENT]
86
+ rejections = sorted((dict(entry, store=name) for name, part in found.items() for entry in part["rejections"]),
87
+ key=lambda entry: -entry["rows"])[:20]
88
+ scopes, also_failed = reads.jobs(narrowed, job=job, limit=200, now=now)
89
+ failed = failed + also_failed
90
+ return {"client": opened.client.id, "job": job,
91
+ "runs": {"statuses": statuses, "total": sum(statuses.values()),
92
+ "success_rate": round(100.0 * statuses.get("succeeded", 0) / ended, 1) if ended else None,
93
+ "median_ms": _percentile(durations, 0.5), "p95_ms": _percentile(durations, 0.95)},
94
+ "totals": totals_of(counts, outbox), "outputs": outputs_of(receipts, outbox), "rejections": rejections,
95
+ "recent_runs": recent, "scopes": scopes["jobs"], "scope_counts": scopes["counts"],
96
+ "errors": dict(store_errors(narrowed, failed),
97
+ **{name: PENDING for name, part in found.items() if part["pending"]})}, failed
@@ -0,0 +1,222 @@
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 console's run history of the client's stores (sw_runs): each run of a job, how it ended, and what failed in it -
19
+ also what failed before it had a batch (a lookup, a database the run could not reach), which no batch shows. A run's
20
+ batches are those it made or resumed (by its request id): their outputs, outbox and rows not applied, as a batch page
21
+ shows one batch's. As in reads, each function takes an OpenClient and returns (result, failed store names).
22
+ """
23
+
24
+ from types import MappingProxyType
25
+
26
+ from streamwright.core.jobs.state.runs import RUN_SORTS
27
+
28
+ from streamwright.console.views.attention import ack_command, unack_command
29
+ from streamwright.console.views.filters import by_store
30
+ from streamwright.console.views.reads import ack_of, batch_row, each_store, only_store, store_errors
31
+
32
+ __all__ = ["FIX_COMMANDS", "JOB_RUN_SORTS", "LOG_FIELDS", "PENDING", "RUN_STATUSES", "history", "history_errors",
33
+ "job_run", "job_run_batches", "job_run_rows", "job_runs", "outputs_of", "totals_of"]
34
+
35
+ FIX_COMMANDS = 5 # retry and resend commands a run page lists (then state list)
36
+ JOB_RUN_SORTS = tuple(RUN_SORTS)
37
+ RUN_STATUSES = ("failed", "succeeded", "skipped", "busy")
38
+ PENDING = "migrations-pending" # a store whose tables lack the run history: `state migrate` adds it
39
+ # a run's log file as the console shows it (its sw_run_logs row: no blocks)
40
+ LOG_FIELDS = ("host", "path", "status", "bytes", "stored_bytes", "line_count", "error_count", "warning_count",
41
+ "started_at", "finished_at")
42
+ _KEYS = MappingProxyType({"started": lambda run: run["started_at"] or "", "job": lambda run: run["job"],
43
+ "status": lambda run: run["status"], "duration": lambda run: run["duration_ms"] or 0})
44
+
45
+
46
+ def history(read):
47
+ """read(store), or PENDING for a store that has no run history yet (reachable: its migrations are pending)."""
48
+ return lambda store: PENDING if store.migrations().pending() else read(store)
49
+
50
+
51
+ def history_errors(opened, found, failed):
52
+ """(the stores' values without the pending ones, their errors: unreachable, not created, migrations pending)."""
53
+ pending = [name for name, value in found.items() if isinstance(value, str) and value == PENDING]
54
+ return ({name: value for name, value in found.items() if name not in pending},
55
+ dict(store_errors(opened, failed), **dict.fromkeys(pending, PENDING)))
56
+
57
+
58
+ def _shown(run, store):
59
+ return {"store": store, "job": run["job_name"], "run_id": run["run_id"], "status": run["status"],
60
+ "started_at": run["started_at"], "finished_at": run["finished_at"], "duration_ms": run["duration_ms"],
61
+ "batches": run["batches"], "passes": run["passes"], "failed_passes": run["failed_passes"],
62
+ "unbatched_failures": run["unbatched_failures"], "error": run["error_message"]}
63
+
64
+
65
+ def _log_shown(row):
66
+ return None if row is None else {key: row.get(key) for key in LOG_FIELDS}
67
+
68
+
69
+ def _with_logs(opened, runs, logs):
70
+ """Each run's `log` (LOG_FIELDS; None: no log file, or a store not in `logs`), read after the page is known."""
71
+ wanted = {}
72
+ for run in runs:
73
+ run["log"] = None
74
+ if run["store"] in logs:
75
+ wanted.setdefault(run["store"], []).append(run["run_id"])
76
+ if not wanted:
77
+ return
78
+ found, _ = each_store(opened, lambda store, run_ids: store.list_run_logs(run_ids), only=wanted)
79
+ rows = {(name, row["job_name"], row["run_id"]): row for name, part in found.items() for row in part}
80
+ for run in runs: # a store that failed meanwhile: its runs show no log
81
+ run["log"] = _log_shown(rows.get((run["store"], run["job"], run["run_id"])))
82
+
83
+
84
+ def job_runs(opened, *, job=None, text=None, statuses=(), since=None, until=None, sort="started", descending=None,
85
+ limit=50, offset=0, conditions=(), logs=()):
86
+ """
87
+ A page of the runs of the client's stores (of one `job`, or of jobs whose name holds `text`; meeting the filter
88
+ `conditions`, filters.JOB_RUN_FIELDS) started in [since, until) (aware datetimes), sorted by `sort`
89
+ (JOB_RUN_SORTS; newest first by default), with their `total` and each status's count. A run of a store in `logs`
90
+ (those whose logs the caller sees) has its log file's `log` (LOG_FIELDS), the others None.
91
+ """
92
+ descending = sort in ("started", "duration") if descending is None else descending
93
+ opened, conditions = by_store(opened, conditions)
94
+ found, failed = each_store(opened, history(lambda store: (
95
+ store.list_runs(job, statuses=statuses, since=since, until=until, text=text, sort=sort,
96
+ descending=descending, limit=offset + limit, conditions=conditions),
97
+ {status: store.count_runs(job, statuses=(status,), since=since, until=until, text=text, conditions=conditions)
98
+ for status in RUN_STATUSES})))
99
+ found, errors = history_errors(opened, found, failed)
100
+ shown = [_shown(run, name) for name, (runs, _) in found.items() for run in runs]
101
+ shown.sort(key=lambda run: (run["started_at"] or "", run["run_id"]), reverse=True) # equals: newest first
102
+ shown.sort(key=_KEYS[sort], reverse=descending)
103
+ counts = {status: sum(part[status] for _, part in found.values()) for status in RUN_STATUSES}
104
+ page = shown[offset:offset + limit]
105
+ _with_logs(opened, page, logs)
106
+ return {"client": opened.client.id, "runs": page, "counts": counts,
107
+ "total": sum(counts[status] for status in (statuses or RUN_STATUSES)), "limit": limit, "offset": offset,
108
+ "errors": errors}, failed
109
+
110
+
111
+ def totals_of(counts, outbox):
112
+ """A set of batches' totals: batches by status, rows written, and their outbox rows applied, rejected, held."""
113
+ rows = {}
114
+ for by_status in outbox.values():
115
+ for status, count in by_status.items():
116
+ rows[status] = rows.get(status, 0) + count
117
+ return {"batches": sum(counts["statuses"].values()), "statuses": counts["statuses"],
118
+ "rows_written": counts["rows_written"], "applied": rows.get("applied", 0) + rows.get("sent", 0),
119
+ "rejected": rows.get("failed", 0), "in_flight": rows.get("in_flight", 0), "pending": rows.get("pending", 0)}
120
+
121
+
122
+ def outputs_of(receipts, outbox):
123
+ """Each output of a set of batches: the rows and files its receipts hold (tables, files), its outbox by status."""
124
+ return [{"name": name, "rows": (receipts.get(name) or {}).get("rows"),
125
+ "files": (receipts.get(name) or {}).get("files", 0), "outbox": outbox.get(name, {})}
126
+ for name in sorted(set(receipts) | set(outbox))]
127
+
128
+
129
+ def _run_of(store, run_id, job):
130
+ """The run (its job's name found when not given) or {"several": why} or None."""
131
+ try:
132
+ return store.get_run(job, run_id)
133
+ except ValueError as exc:
134
+ return {"several": str(exc)}
135
+
136
+
137
+ def _fix(store, run, failed):
138
+ """The commands that settle the run's batches: retry the first failed ones, resend held ones, then list them."""
139
+ job, run_id = run["job_name"], run["run_id"]
140
+ retry = store.insight_batches(job, run_id=run_id, status="failed", limit=FIX_COMMANDS) if failed else []
141
+ commands = ["streamwright state retry --url \"$STATE_URL\" %s" % batch["batch_id"] for batch in retry]
142
+ commands += ["streamwright state resend --url \"$STATE_URL\" %s" % batch_id
143
+ for batch_id in store.insight_held(job, run_id=run_id, limit=FIX_COMMANDS)]
144
+ if failed > FIX_COMMANDS:
145
+ commands.append("streamwright state list --url \"$STATE_URL\" --job %s --request-id %s --status failed "
146
+ "--limit %d" % (job, run_id, failed))
147
+ return commands
148
+
149
+
150
+ def job_run(opened, store_name, run_id, job=None, *, log=False):
151
+ """
152
+ One run of a store: how it ended, what failed in it (`failures`: item, job ids, error), its batches' totals and
153
+ outputs, its acknowledgement (a failed run's) and the commands that settle them; None when there is none. Without
154
+ `job`, a run id that several jobs have is {"several": why}. `log`: with its log file's `log` (LOG_FIELDS; None
155
+ without one, or without `log`).
156
+ """
157
+ def read(store):
158
+ run = _run_of(store, run_id, job)
159
+ if run is None or "several" in run:
160
+ return run
161
+ name = run["job_name"]
162
+ counts, outbox = store.insight_counts(name, run_id=run_id), store.insight_outbox(name, run_id=run_id)
163
+ ack = ack_of(store, name, run_id, "run" if run["status"] == "failed" else None)
164
+ commands = _fix(store, run, counts["statuses"].get("failed", 0))
165
+ if run["status"] == "failed":
166
+ commands.append(unack_command(run_id) if ack else ack_command(run_id))
167
+ return dict(run, totals=totals_of(counts, outbox),
168
+ outputs=outputs_of(store.insight_receipts(name, run_id=run_id), outbox), ack=ack,
169
+ commands=commands, log=_log_shown(store.get_run_log(name, run_id)) if log else None)
170
+
171
+ found, failed = each_store(only_store(opened, store_name), history(read))
172
+ found, _ = history_errors(opened, found, failed)
173
+ run = found.get(store_name)
174
+ if run is None or "several" in run:
175
+ return run, failed
176
+ return dict(_shown(run, store_name), owner_id=run["owner_id"], failures=run["failures"], totals=run["totals"],
177
+ outputs=run["outputs"], ack=run["ack"], commands=run["commands"], log=run["log"]), failed
178
+
179
+
180
+ def job_run_batches(opened, store_name, run_id, job=None, *, status=None, limit=50, offset=0):
181
+ """
182
+ A page of the batches a run made or resumed (in one `status`), newest first, as a batch list shows them, each
183
+ with its scope and whether the run resumed it; with their `total`. None when there is no such run.
184
+ """
185
+ def read(store):
186
+ run = _run_of(store, run_id, job)
187
+ if run is None or "several" in run:
188
+ return run
189
+ name = run["job_name"]
190
+ batches = store.insight_batches(name, run_id=run_id, status=status, limit=limit, offset=offset)
191
+ outbox = store.count_events(name, [batch["batch_id"] for batch in batches])
192
+ statuses = store.insight_counts(name, run_id=run_id)["statuses"]
193
+ return {"job": name, "counts": statuses, "total": statuses.get(status, 0) if status else sum(statuses.values()),
194
+ "batches": [dict(batch_row(batch, outbox.get(batch["batch_id"])), scope=batch["scope"],
195
+ resumed=(batch.get("engine_metadata") or {}).get("request_id") != run_id)
196
+ for batch in batches]}
197
+
198
+ found, failed = each_store(only_store(opened, store_name), history(read))
199
+ found, _ = history_errors(opened, found, failed)
200
+ page = found.get(store_name)
201
+ return (page if page is None or "several" in page else dict(page, run_id=run_id, store=store_name, limit=limit,
202
+ offset=offset)), failed
203
+
204
+
205
+ def job_run_rows(opened, store_name, run_id, job=None, *, limit=500):
206
+ """
207
+ The rows a run's batches did not apply (failed, in flight, pending; no values), at most `limit`, and its rejected
208
+ rows grouped by output, tag and error code (`rejections`). None when there is no such run.
209
+ """
210
+ def read(store):
211
+ run = _run_of(store, run_id, job)
212
+ if run is None or "several" in run:
213
+ return run
214
+ name = run["job_name"]
215
+ return {"job": name, "rejections": store.insight_errors(name, run_id=run_id),
216
+ "rows": store.insight_rows(name, run_id=run_id, limit=limit)}
217
+
218
+ found, failed = each_store(only_store(opened, store_name), history(read))
219
+ found, _ = history_errors(opened, found, failed)
220
+ page = found.get(store_name)
221
+ return (page if page is None or "several" in page else dict(page, run_id=run_id, store=store_name,
222
+ limit=limit)), failed
@@ -0,0 +1,123 @@
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
+ """
19
+ The console's Jobs list: each job once, every store's - its scopes' health now (the worst is the job's, and a job whose
20
+ latest run failed is failed), how many of its scopes' problems a person acknowledged, its latest run, and its runs and
21
+ the rows its batches wrote, applied, rejected and hold in a period. As in reads, a function takes an OpenClient and
22
+ returns (result, failed store names).
23
+ """
24
+
25
+ from types import MappingProxyType
26
+
27
+ from streamwright.core.jobs.state.attention import batch_items, store_index, with_acks
28
+ from streamwright.core.jobs.state.conditions import meets
29
+
30
+ from streamwright.console.views.filters import by_store
31
+ from streamwright.console.views.job_runs import PENDING
32
+ from streamwright.console.views.reads import HEALTHS, each_store, store_errors
33
+
34
+ __all__ = ["JOB_SUMMARY_SORTS", "job_summaries"]
35
+
36
+ JOB_SUMMARY_SORTS = ("health", "job", "last", "runs")
37
+ _KEYS = MappingProxyType({"health": lambda job: HEALTHS.index(job["health"]), "job": lambda job: job["job"].lower(),
38
+ "last": lambda job: job["last"] or "", "runs": lambda job: job["runs"]["total"]})
39
+
40
+
41
+ def _store_jobs(store, since, until):
42
+ """A store's part: its index, the jobs of its acknowledged scopes, its latest runs, runs and rows in the period."""
43
+ pending = store.migrations().pending()
44
+ index = store_index(store)
45
+ items = batch_items(index)
46
+ with_acks(store, items, pending)
47
+ return {"index": index, "acked": [item["job"] for item in items if item["ack"]], "pending": bool(pending),
48
+ "latest": [] if pending else store.latest_runs(),
49
+ "runs": {} if pending else store.run_counts(since=since, until=until),
50
+ "totals": store.job_totals(since=since, until=until)}
51
+
52
+
53
+ def _latest(*times):
54
+ return max((time for time in times if time), default=None) # ISO texts in UTC: they sort as times
55
+
56
+
57
+ def _merged(found):
58
+ """Each job once, from every store's part (`found`: {store: part})."""
59
+ jobs = {}
60
+
61
+ def job_of(name, store):
62
+ entry = jobs.setdefault(name, {"job": name, "health": "ok", "scopes": {}, "acknowledged": 0, "last_run": None,
63
+ "runs": {"total": 0, "statuses": {}}, "stores": [], "last": None,
64
+ "rows": {"written": 0, "applied": 0, "rejected": 0, "held": 0}})
65
+ if store not in entry["stores"]:
66
+ entry["stores"].append(store)
67
+ return entry
68
+
69
+ for store, part in found.items():
70
+ for indexed in part["index"]:
71
+ entry = job_of(indexed["batch"]["job_name"], store)
72
+ entry["scopes"][indexed["health"]] = entry["scopes"].get(indexed["health"], 0) + 1
73
+ entry["last"] = _latest(entry["last"], indexed["batch"]["created_at"])
74
+ for name in part["acked"]:
75
+ job_of(name, store)["acknowledged"] += 1
76
+ for run in part["latest"]:
77
+ entry = job_of(run["job_name"], store)
78
+ if entry["last_run"] is None or (run["started_at"] or "") > (entry["last_run"]["started_at"] or ""):
79
+ entry["last_run"] = {"store": store, "run_id": run["run_id"], "status": run["status"],
80
+ "started_at": run["started_at"], "duration_ms": run["duration_ms"],
81
+ "batches": run["batches"]}
82
+ entry["last"] = _latest(entry["last"], run["started_at"])
83
+ for name, statuses in part["runs"].items():
84
+ runs = job_of(name, store)["runs"]
85
+ for status, count in statuses.items():
86
+ runs["statuses"][status] = runs["statuses"].get(status, 0) + count
87
+ runs["total"] += count
88
+ for name, totals in part["totals"].items():
89
+ rows, outbox = job_of(name, store)["rows"], totals["outbox"]
90
+ rows["written"] += totals["rows_written"]
91
+ rows["applied"] += outbox.get("applied", 0) + outbox.get("sent", 0)
92
+ rows["rejected"] += outbox.get("failed", 0)
93
+ rows["held"] += outbox.get("in_flight", 0) + outbox.get("pending", 0)
94
+ for entry in jobs.values():
95
+ worst = next((health for health in HEALTHS if entry["scopes"].get(health)), "ok")
96
+ entry["health"] = "failed" if (entry["last_run"] or {}).get("status") == "failed" else worst
97
+ entry["stores"].sort()
98
+ return list(jobs.values())
99
+
100
+
101
+ def job_summaries(opened, *, job=None, health=None, since=None, until=None, sort="health", descending=None, limit=50,
102
+ offset=0, conditions=()):
103
+ """
104
+ A page of the client's jobs, each once, every store's (of one `job`, or those meeting the filter `conditions`,
105
+ filters.JOB_SUMMARY_FIELDS) and, of those, whose health is `health`: its scopes by health now, how many of them a
106
+ person acknowledged, its latest run (any time), its runs started and the rows of its batches made in [since, until)
107
+ (aware datetimes), its stores; sorted by `sort` (JOB_SUMMARY_SORTS: the worst health first by default, then the
108
+ newest; `descending` defaults to True for last and runs). With `total` (after every filter) and `counts`: each
109
+ health's number of jobs before the health filter.
110
+ """
111
+ opened, conditions = by_store(opened, conditions)
112
+ found, failed = each_store(opened, lambda store: _store_jobs(store, since, until))
113
+ jobs = [entry for entry in _merged(found)
114
+ if job in (None, entry["job"]) and meets(conditions, {"job": entry["job"]})]
115
+ counts = {name: sum(1 for entry in jobs if entry["health"] == name) for name in HEALTHS}
116
+ listed = [entry for entry in jobs if health is None or entry["health"] == health]
117
+ descending = sort in ("last", "runs") if descending is None else descending
118
+ listed.sort(key=lambda entry: entry["job"].lower())
119
+ listed.sort(key=_KEYS["last"], reverse=True) # equals: the newest first
120
+ listed.sort(key=_KEYS[sort], reverse=descending)
121
+ errors = dict(store_errors(opened, failed), **{name: PENDING for name, part in found.items() if part["pending"]})
122
+ return {"client": opened.client.id, "jobs": listed[offset:offset + limit], "total": len(listed), "counts": counts,
123
+ "limit": limit, "offset": offset, "errors": errors}, failed
@@ -0,0 +1,156 @@
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
+ """
19
+ What the console's Overview shows of an open client: each store read once - its jobs' health, its pending migrations,
20
+ its leases past their expiry, each job's latest run, and what of them needs a person, light, with its acknowledgement
21
+ (`state ack`) - then the overview's counts, and the attention list (attention.py) filtered, counted and paged, the
22
+ items of a page read in full. As in reads, each function takes an OpenClient and returns (result, failed store names).
23
+ """
24
+
25
+ import datetime
26
+
27
+ from streamwright.core.jobs.state.attention import NEEDS, batch_items, run_items, store_index, with_acks
28
+ from streamwright.core.jobs.state.conditions import meets
29
+
30
+ from streamwright.console.views import attention as needs
31
+ from streamwright.console.views.filters import by_store
32
+ from streamwright.console.views.reads import HEALTHS, each_store, in_full, store_errors
33
+
34
+ __all__ = ["ACKED", "attention", "overview"]
35
+
36
+ ACKED = ("no", "yes", "all") # the attention list: needs a person, acknowledged, both
37
+
38
+
39
+ def _time(text):
40
+ return datetime.datetime.fromisoformat(str(text).replace("Z", "+00:00")) if text else None
41
+
42
+
43
+ def _store_summary(store):
44
+ """A store's jobs, its pending migrations, its leases past their expiry, each job's latest run (none until the
45
+ store has its tables) and what of them needs a person, light, with its acknowledgement."""
46
+ pending = store.migrations().pending()
47
+ index = store_index(store)
48
+ runs = [] if pending else store.latest_runs()
49
+ items = batch_items(index) + run_items(runs)
50
+ with_acks(store, items, pending)
51
+ return {"index": index, "pending": pending, "runs": runs, "items": items,
52
+ "expired": [lease for lease in store.all_leases() if not lease["held"] and lease["expires_at"]]}
53
+
54
+
55
+ def _summaries(opened):
56
+ """
57
+ Each store read once (a store that fails is not tried again in the pass): (its summary by store name, failed store
58
+ names, the stores as the overview lists them, every item that needs a person, light: the batches' by health -
59
+ failed, held, rejected - newest first, then the runs', the expired leases', the migrations' and the stores').
60
+ """
61
+ found, failed = each_store(opened, _store_summary)
62
+ errors = store_errors(opened, failed)
63
+ stores = [{"name": name, "reachable": name not in errors, "error": errors.get(name),
64
+ "migrations_pending": found[name]["pending"] if name in found else []} for name in opened.client.stores]
65
+ batch, runs = [], []
66
+ for name, part in found.items():
67
+ for item in part["items"]:
68
+ item["store"] = name
69
+ if "entry" in item:
70
+ item["entry"] = dict(item["entry"], store=name)
71
+ batch.append(item)
72
+ else:
73
+ runs.append(item)
74
+ batch.sort(key=lambda item: (item["job"], item["scope"], item["store"]))
75
+ batch.sort(key=lambda item: item["entry"]["batch"]["created_at"] or "", reverse=True) # equals: newest first
76
+ batch.sort(key=lambda item: NEEDS.index(item["entry"]["health"]))
77
+ expired = {name: part["expired"] for name, part in found.items()}
78
+ return found, failed, stores, batch + runs + needs.other_items(expired, stores)
79
+
80
+
81
+ def overview(opened):
82
+ """
83
+ The client's stores (reachable, pending migrations), its jobs and scopes counted by health, its failed runs (jobs
84
+ whose latest run failed where no batch shows it), how many items need a person (`attention`) and, of the cards'
85
+ items, how many a person acknowledged; the items are `attention`'s.
86
+ """
87
+ found, failed, stores, items = _summaries(opened)
88
+ indexed = [entry for part in found.values() for entry in part["index"]]
89
+ counts = {health: sum(1 for entry in indexed if entry["health"] == health) for health in HEALTHS}
90
+ acked = [needs.group_of(item) for item in items if item["ack"]]
91
+ names = {entry["batch"]["job_name"] for entry in indexed} | {run["job_name"] for part in found.values()
92
+ for run in part["runs"]}
93
+ counts.update(failed_runs=sum(1 for item in items if item["kind"] == "run"), # failures no batch shows
94
+ attention=sum(1 for item in items if not item["ack"]), jobs=len(names), scopes=len(indexed),
95
+ acknowledged={"failed": acked.count("failed"), "held": acked.count("held"),
96
+ "rejected": acked.count("rejected"), "failed_runs": acked.count("run")})
97
+ return {"client": opened.client.id, "name": opened.client.name, "stores": stores, "counts": counts}, failed
98
+
99
+
100
+ def _happened(item, since, until, now):
101
+ """Whether an item happened in [since, until): one with no time (a store down) happens now."""
102
+ when = _time(item.get("since")) or now
103
+ return (since is None or when >= since) and (until is None or when < until)
104
+
105
+
106
+ def _fill(opened, items, now):
107
+ """Reads the batch items of `items` not read yet in full (in place); the stores that failed."""
108
+ todo = [item for item in items if "entry" in item and "attempts" not in item]
109
+ if not todo:
110
+ return []
111
+ rows, failed = in_full(opened, [item["entry"] for item in todo], now, acks=False, keys=True)
112
+ found = {(row["store"], row["job"], row["scope"]): row for row in rows}
113
+ for item in todo:
114
+ row = found.get((item["store"], item["job"], item["scope"]))
115
+ if row is not None: # else purged since the index was read
116
+ item.update(needs.with_details(item, row))
117
+ return failed
118
+
119
+
120
+ def _shown(item):
121
+ shown = {key: value for key, value in item.items() if key not in ("entry", "key")}
122
+ shown.setdefault("detail", None)
123
+ return dict(shown, commands=needs.item_commands(item))
124
+
125
+
126
+ def attention(opened, *, kind=None, acked="no", since=None, until=None, conditions=(), limit=50, offset=0, now=None):
127
+ """
128
+ A page of what needs a person (`acked` no, the default), of what a person acknowledged (yes) or both (all), in
129
+ the overview's order: the items that meet the filter `conditions` (filters.ATTENTION_FIELDS; error: the item's
130
+ detail), that happened in [since, until) (aware datetimes) and, of those, of one `kind` (attention.KINDS). With
131
+ `total` (after every filter), `counts` (each kind's) and `needs_attention` and `acknowledged` (each tab's), before
132
+ the kind filter, and `jobs`: per store and job listed, the command that acknowledges (or undoes) its items in one
133
+ go. Only the page is read in full.
134
+ """
135
+ now = now or datetime.datetime.now(datetime.UTC)
136
+ opened, conditions = by_store(opened, conditions)
137
+ _, failed, _, items = _summaries(opened)
138
+ where = tuple(condition for condition in conditions if condition[0] != "error")
139
+ errors = tuple(condition for condition in conditions if condition[0] == "error")
140
+ shown = [item for item in items if _happened(item, since, until, now) and meets(where, {
141
+ "job": item.get("job"), "scope": item.get("scope"), "store": item["store"]})]
142
+ if errors: # the details of every item shown, to meet them
143
+ failed = failed + _fill(opened, shown, now)
144
+ shown = [item for item in shown if meets(errors, {"error": item.get("detail")})]
145
+ tabs = {"no": [item for item in shown if not item["ack"]], "yes": [item for item in shown if item["ack"]]}
146
+ chosen = shown if acked == "all" else tabs[acked]
147
+ counts = {name: sum(1 for item in chosen if needs.group_of(item) == name) for name in needs.KINDS}
148
+ listed = [item for item in chosen if kind is None or needs.group_of(item) == kind]
149
+ page = listed[offset:offset + limit]
150
+ failed = failed + _fill(opened, page, now)
151
+ jobs = [] if acked == "all" else needs.job_commands(
152
+ [item for item in items if bool(item["ack"]) == (acked == "yes")], acked == "yes",
153
+ {(item["store"], item.get("job")) for item in listed})
154
+ return {"client": opened.client.id, "items": [_shown(item) for item in page], "total": len(listed),
155
+ "counts": counts, "needs_attention": len(tabs["no"]), "acknowledged": len(tabs["yes"]), "jobs": jobs,
156
+ "limit": limit, "offset": offset, "errors": store_errors(opened, failed)}, failed