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,2014 @@
1
+ // Copyright 2026 Karthick Jaganathan. Licensed under the Apache License, Version 2.0.
2
+ // The StreamWright console: pick a client, see its jobs, acknowledge its problems (where console.yaml lets the person
3
+ // signed in). It changes nothing else; every value is set as text, never as HTML.
4
+
5
+ const state = { config: null, clients: [], client: null, overview: null, me: null };
6
+ const TOKEN = "sw-console-token";
7
+ const RECENT = "sw-console-recent";
8
+ const HEALTH = { failed: "fail", held: "held", rejected: "rej", running: "run", ok: "ok" };
9
+ const RUN_STATUS = { failed: "fail", succeeded: "ok", skipped: "idle", busy: "held" };
10
+ const STATUS = { completed: "ok", skipped: "ok", failed: "fail", abandoned: "fail", received: "run",
11
+ processing: "run", committed: "run", acked: "run", succeeded: "ok", queued: "idle", running: "run" };
12
+
13
+ // --- helpers -----------------------------------------------------------------------------------------------
14
+
15
+ function el(tag, attrs, ...children) {
16
+ const node = document.createElement(tag);
17
+ for (const [key, value] of Object.entries(attrs || {})) {
18
+ if (value === undefined || value === null || value === false) continue;
19
+ if (key === "class") node.className = value;
20
+ else if (key === "text") node.textContent = value;
21
+ else if (key.startsWith("on")) node.addEventListener(key.slice(2), value);
22
+ else node.setAttribute(key, value);
23
+ }
24
+ for (const child of children.flat()) {
25
+ if (child === undefined || child === null || child === false) continue;
26
+ node.append(child instanceof Node ? child : document.createTextNode(String(child)));
27
+ }
28
+ return node;
29
+ }
30
+
31
+ function put(node, ...children) {
32
+ node.replaceChildren(...children.flat(Infinity).filter(c => c !== null && c !== undefined && c !== false));
33
+ }
34
+
35
+ // text that wraps after _ : / and , (long names, scopes and paths), not in the middle of a word
36
+ function wrapAt(text) { return String(text).split(/(?<=[_:/,])/).flatMap((part, i) => i ? [el("wbr"), part] : [part]); }
37
+
38
+ function pill(text, kind) { return el("span", { class: "pill " + (kind || "idle"), text }); }
39
+ function dot(kind) { return el("span", { class: "dot " + (kind || "idle") }); }
40
+
41
+ function ago(iso) {
42
+ if (!iso) return "–";
43
+ const seconds = (Date.now() - new Date(iso).getTime()) / 1000;
44
+ if (!isFinite(seconds)) return iso;
45
+ const future = seconds < 0, s = Math.abs(seconds); // a lease's expiry is often ahead
46
+ if (s < 60) return future ? "in a moment" : "just now";
47
+ const span = s < 3600 ? Math.round(s / 60) + " min" : s < 86400 ? Math.round(s / 3600) + " h"
48
+ : Math.round(s / 86400) + " d";
49
+ return future ? "in " + span : span + " ago";
50
+ }
51
+
52
+ // stored times are UTC; a tooltip gives the viewer's local time, then UTC
53
+ function when(iso) {
54
+ const local = iso ? new Date(iso).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "long" }) : "";
55
+ return el("span", { class: "when", text: ago(iso), title: iso ? local + " · " + iso + " UTC" : "",
56
+ "data-sort": iso });
57
+ }
58
+
59
+ function duration(ms) {
60
+ if (ms === null || ms === undefined) return "–";
61
+ if (ms < 1000) return ms + " ms";
62
+ const s = Math.round(ms / 1000);
63
+ if (s < 60) return s + " s";
64
+ return Math.floor(s / 60) + " min " + (s % 60) + " s";
65
+ }
66
+
67
+ function number(n) { return n === null || n === undefined ? "–" : Number(n).toLocaleString(); }
68
+
69
+ // an input's value as written: text as it is, anything else (numbers, booleans, lists) as JSON
70
+ function shown(value) { return typeof value === "string" ? value : JSON.stringify(value); }
71
+
72
+ function outboxText(outbox) {
73
+ const parts = Object.entries(outbox || {}).map(([status, n]) => number(n) + " " + status.replace("_", " "));
74
+ return parts.join(" · ");
75
+ }
76
+
77
+ function command(text) {
78
+ return el("div", { class: "cmd" }, el("code", { text }),
79
+ el("button", { type: "button", text: "copy", onclick: event => {
80
+ const button = event.currentTarget;
81
+ if (!navigator.clipboard) return;
82
+ navigator.clipboard.writeText(text).then(() => {
83
+ button.textContent = "copied";
84
+ setTimeout(() => { button.textContent = "copy"; }, 1500);
85
+ }, () => {});
86
+ } }));
87
+ }
88
+
89
+ // an icon on the 24-unit grid of the sidebar's (stroked, round caps); `paths`: SVG path data
90
+ function icon(...paths) {
91
+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
92
+ svg.setAttribute("viewBox", "0 0 24 24");
93
+ svg.setAttribute("class", "ico");
94
+ svg.setAttribute("aria-hidden", "true");
95
+ for (const d of paths) {
96
+ const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
97
+ path.setAttribute("d", d);
98
+ svg.append(path);
99
+ }
100
+ return svg;
101
+ }
102
+
103
+ // two arcs around the centre, each ending in an arrowhead (clockwise)
104
+ const REFRESH = ["M4.5 12a7.5 7.5 0 0 1 12.8-5.3", "M17.5 3.5V7H14", "M19.5 12a7.5 7.5 0 0 1-12.8 5.3", "M6.5 20.5V17H10"];
105
+
106
+ // reload(): fetches the screen's data again (its filters, sort and page as they are); the icon turns meanwhile
107
+ function refreshButton(reload) {
108
+ const button = el("button", { type: "button", class: "refresh", title: "Refresh", "aria-label": "Refresh" },
109
+ icon(...REFRESH));
110
+ button.addEventListener("click", async () => {
111
+ button.disabled = true;
112
+ button.classList.add("turning");
113
+ try {
114
+ await Promise.all([reload(), new Promise(done => setTimeout(done, 400))]); // long enough to see it turn
115
+ button.classList.remove("failed");
116
+ button.title = "Refresh · updated " + new Date().toLocaleTimeString();
117
+ } catch (error) {
118
+ if (error.message === "unauthorized") return;
119
+ button.classList.add("failed");
120
+ button.title = "Refresh · it failed: " + error.message;
121
+ } finally {
122
+ button.disabled = false;
123
+ button.classList.remove("turning");
124
+ }
125
+ });
126
+ return button;
127
+ }
128
+
129
+ function panel(title, sub, ...body) {
130
+ return el("div", { class: "panel" }, el("h3", {}, title, sub ? el("small", { text: sub }) : null), ...body);
131
+ }
132
+
133
+ // a table's sort and column widths, by its key, kept while the page is open (a filter redraws the table)
134
+ const tables = {};
135
+ const MIN_WIDTH = 48;
136
+
137
+ // what a cell sorts by: its data-sort (or its first marked child's: a time's ISO value), else its text; blank: null
138
+ function sortValue(cell) {
139
+ const marked = cell && (cell.dataset.sort !== undefined ? cell : cell.querySelector("[data-sort]"));
140
+ const text = (marked ? marked.dataset.sort : cell ? cell.textContent : "").trim();
141
+ return text === "" || text === "–" ? null : text;
142
+ }
143
+
144
+ function compareValues(a, b) {
145
+ const x = Number(a), y = Number(b);
146
+ if (a !== "" && b !== "" && isFinite(x) && isFinite(y)) return x - y;
147
+ return a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" });
148
+ }
149
+
150
+ // headers: text or {text, num, sort}; rows: <tr>s; key: the table's name, so its sort and widths outlive a redraw.
151
+ // Click a header to sort (ascending, descending, then as given); drag a header's right edge to resize, double-click
152
+ // it to fit. `server` ({by, order, onSort}): a page of a longer list, sorted by the server: only headers with a `sort`
153
+ // key sort, through onSort(key).
154
+ function table(headers, rows, empty, key, server) {
155
+ if (!rows.length) return el("div", { class: "empty", text: empty || "Nothing to show." });
156
+ const saved = key ? (tables[key] = tables[key] || {}) : {};
157
+ const body = el("tbody", {}, rows);
158
+ const node = el("table", {});
159
+ const label = h => h.text || h;
160
+ const sortable = h => !server || h.sort;
161
+ const cells = headers.map((h, column) => el("th", { class: h.num ? "num" : "" },
162
+ sortable(h) ? el("button", { type: "button", class: "sort", text: label(h), title: "Sort by " + label(h),
163
+ onclick: () => server ? server.onSort(h.sort) : sortBy(column) })
164
+ : el("span", { class: "sort", text: label(h) }),
165
+ el("span", { class: "grip", title: "Drag to resize · double-click to fit", "aria-hidden": "true",
166
+ onpointerdown: event => resize(event, column), ondblclick: () => setWidths(null) })));
167
+ const order = () => {
168
+ if (server) {
169
+ cells.forEach((th, i) => th.setAttribute("aria-sort", headers[i].sort !== server.by ? "none"
170
+ : server.order === "asc" ? "ascending" : "descending"));
171
+ return;
172
+ }
173
+ cells.forEach((th, i) => th.setAttribute("aria-sort", i !== saved.column ? "none"
174
+ : saved.direction > 0 ? "ascending" : "descending"));
175
+ const keyed = rows.map((row, index) => [saved.direction ? sortValue(row.cells[saved.column]) : null, index, row]);
176
+ if (saved.direction) keyed.sort(([a, i], [b, j]) => a === null || b === null
177
+ ? (a === b ? i - j : a === null ? 1 : -1) // blanks last, either way
178
+ : saved.direction * compareValues(a, b) || i - j);
179
+ body.append(...keyed.map(([, , row]) => row));
180
+ };
181
+ const sortBy = column => {
182
+ saved.direction = saved.column !== column ? 1 : saved.direction === 1 ? -1 : 0;
183
+ saved.column = saved.direction ? column : null;
184
+ order();
185
+ };
186
+ const setWidths = widths => { // null: as the content wants (auto layout)
187
+ saved.widths = widths;
188
+ node.classList.toggle("fixed", Boolean(widths));
189
+ cells.forEach((th, i) => { th.style.width = widths ? widths[i] + "px" : ""; });
190
+ node.style.width = widths ? widths.reduce((a, b) => a + b, 0) + "px" : "";
191
+ };
192
+ const resize = (event, column) => {
193
+ event.preventDefault();
194
+ const grip = event.currentTarget, startX = event.clientX;
195
+ const start = cells.map(th => th.getBoundingClientRect().width);
196
+ setWidths(start.slice());
197
+ grip.setPointerCapture(event.pointerId);
198
+ grip.classList.add("active");
199
+ const move = e => {
200
+ const widths = start.slice();
201
+ widths[column] = Math.max(MIN_WIDTH, start[column] + e.clientX - startX);
202
+ setWidths(widths);
203
+ };
204
+ const stop = () => {
205
+ grip.classList.remove("active");
206
+ grip.removeEventListener("pointermove", move);
207
+ grip.removeEventListener("pointerup", stop);
208
+ grip.removeEventListener("pointercancel", stop);
209
+ };
210
+ grip.addEventListener("pointermove", move);
211
+ grip.addEventListener("pointerup", stop);
212
+ grip.addEventListener("pointercancel", stop);
213
+ };
214
+ node.append(el("thead", {}, el("tr", {}, cells)), body);
215
+ if (saved.widths && saved.widths.length === headers.length) setWidths(saved.widths);
216
+ order();
217
+ return node;
218
+ }
219
+
220
+ function logsLink(requestId, jobId) {
221
+ const link = state.config && state.config.logs_link;
222
+ if (!link || !requestId) return null;
223
+ const href = link.replace("{request_id}", encodeURIComponent(requestId))
224
+ .replace("{job_id}", encodeURIComponent(jobId || ""));
225
+ return el("a", { href, target: "_blank", rel: "noopener noreferrer", text: "open logs ↗" });
226
+ }
227
+
228
+ // --- the API -----------------------------------------------------------------------------------------------
229
+
230
+ // a GET of the API (`send`: a POST or DELETE with a JSON body), with the session, key or token of this tab; a failure
231
+ // throws an Error with the answer's message, its HTTP `status` and its `code`
232
+ async function api(path) { return send("GET", path); }
233
+
234
+ function authHeaders(headers) {
235
+ const token = sessionStorage.getItem(TOKEN);
236
+ return token ? { ...headers, Authorization: "Bearer " + token } : { ...headers };
237
+ }
238
+
239
+ async function send(method, path, body) {
240
+ const headers = authHeaders(body === undefined ? {} : { "Content-Type": "application/json" });
241
+ const response = await fetch(path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
242
+ if (response.status === 401) {
243
+ showLogin(headers.Authorization ? "Sign in again: the session ended, or the key or token was not accepted." : "");
244
+ throw new Error("unauthorized");
245
+ }
246
+ const found = await response.json().catch(() => ({}));
247
+ if (!response.ok) {
248
+ throw Object.assign(new Error(found.message || found.code || response.statusText),
249
+ { status: response.status, code: found.code });
250
+ }
251
+ return found;
252
+ }
253
+
254
+ // a file of the API (a run's log), saved under the name the server gives it; the button says when it failed
255
+ async function download(path, button) {
256
+ const label = button.textContent;
257
+ button.disabled = true;
258
+ try {
259
+ const response = await fetch(path, { headers: authHeaders({}) });
260
+ if (response.status === 401) { showLogin("Sign in again: the session ended."); return; }
261
+ if (!response.ok) {
262
+ const found = await response.json().catch(() => ({}));
263
+ throw new Error(found.message || found.code || response.statusText);
264
+ }
265
+ const named = /filename="([^"]+)"/.exec(response.headers.get("Content-Disposition") || "");
266
+ const url = URL.createObjectURL(await response.blob());
267
+ const link = el("a", { href: url, download: named ? named[1] : "run.log" });
268
+ document.body.append(link);
269
+ link.click();
270
+ link.remove();
271
+ setTimeout(() => URL.revokeObjectURL(url), 60000);
272
+ } catch (error) {
273
+ button.textContent = "Download failed";
274
+ button.title = error.message;
275
+ setTimeout(() => { button.textContent = label; }, 4000);
276
+ } finally {
277
+ button.disabled = false;
278
+ }
279
+ }
280
+
281
+ // --- sign in -----------------------------------------------------------------------------------------------
282
+
283
+ function loginError(message) {
284
+ const box = document.getElementById("login-error");
285
+ box.textContent = message || "";
286
+ box.classList.toggle("hidden", !message);
287
+ }
288
+
289
+ // the login page: what console.yaml sets up (single sign-on, console users), and an API key or token for tools
290
+ function showLogin(message) {
291
+ const login = (state.config && state.config.login) || null;
292
+ document.body.classList.add("signed-out");
293
+ document.getElementById("login").classList.remove("hidden");
294
+ document.querySelector(".wrap").classList.add("hidden");
295
+ document.getElementById("login-sso").classList.toggle("hidden", !(login && login.sso));
296
+ document.getElementById("login-sso-label").textContent = "Sign in with " + ((login && login.sso) || "SSO");
297
+ document.getElementById("login-or").classList.toggle("hidden", !(login && login.sso && login.users));
298
+ document.getElementById("login-user").classList.toggle("hidden", !(login && login.users));
299
+ const key = document.getElementById("login-key");
300
+ key.classList.toggle("alone", !login); // keys and tokens only: their form is the page
301
+ if (!login) key.open = true;
302
+ document.getElementById("login-foot").textContent = login ? "Your session is kept in this tab only, until it ends or you " +
303
+ "sign out." : "Kept in this tab only.";
304
+ loginError(message);
305
+ }
306
+
307
+ function signedIn(token) {
308
+ sessionStorage.setItem(TOKEN, token);
309
+ document.body.classList.remove("signed-out");
310
+ document.getElementById("login").classList.add("hidden");
311
+ document.querySelector(".wrap").classList.remove("hidden");
312
+ loginError("");
313
+ start();
314
+ }
315
+
316
+ document.getElementById("login-form").addEventListener("submit", event => {
317
+ event.preventDefault();
318
+ signedIn(document.getElementById("login-token").value.trim());
319
+ });
320
+
321
+ document.getElementById("login-user").addEventListener("submit", async event => {
322
+ event.preventDefault();
323
+ const button = event.currentTarget.querySelector("button");
324
+ button.disabled = true;
325
+ try {
326
+ const response = await fetch("/v1/login", { method: "POST", headers: { "Content-Type": "application/json" },
327
+ body: JSON.stringify({ user: document.getElementById("login-name").value,
328
+ password: document.getElementById("login-password").value }) });
329
+ const body = await response.json().catch(() => ({}));
330
+ if (!response.ok) {
331
+ loginError(response.status === 401 ? "The user name or password is not right. After 5 tries a name waits a minute."
332
+ : response.status === 429 ? "Too many tries: wait a minute, then sign in again."
333
+ : body.message || response.statusText);
334
+ return;
335
+ }
336
+ document.getElementById("login-password").value = "";
337
+ signedIn(body.token);
338
+ } catch (error) {
339
+ loginError("Could not sign in: " + error.message);
340
+ } finally {
341
+ button.disabled = false;
342
+ }
343
+ });
344
+
345
+ document.getElementById("login-sso-button").addEventListener("click", () => { location.href = "/login/sso"; });
346
+
347
+ // back from single sign-on: #/signed-in?code=... (swapped for a session; the code leaves the address), or
348
+ // #/signed-out?error=sso. True when the login page shows why it did not finish.
349
+ async function returning() {
350
+ const back = location.hash.match(/^#\/signed-(in|out)\?(?:code|error)=([^&]*)$/);
351
+ if (!back) return false;
352
+ history.replaceState(null, "", location.pathname + location.search);
353
+ if (back[1] === "in") {
354
+ const response = await fetch("/v1/login/exchange", { method: "POST", headers: { "Content-Type": "application/json" },
355
+ body: JSON.stringify({ code: decodeURIComponent(back[2]) }) });
356
+ const body = await response.json().catch(() => ({}));
357
+ if (response.ok) { sessionStorage.setItem(TOKEN, body.token); return false; }
358
+ }
359
+ showLogin("Single sign-on did not finish: sign in again (the console's log says why).");
360
+ return true;
361
+ }
362
+
363
+ // who signed in (top bar)
364
+ function initials(name) {
365
+ const words = String(name).replace(/[@(].*$/, "").split(/[\s._-]+/).filter(Boolean);
366
+ return (words.length > 1 ? words[0][0] + words[1][0] : (words[0] || "?").slice(0, 2)).toUpperCase();
367
+ }
368
+
369
+ function showWho(me) {
370
+ document.getElementById("who").classList.toggle("hidden", !me);
371
+ if (!me) return;
372
+ document.getElementById("who-name").textContent = me.name;
373
+ document.getElementById("who-initials").textContent = initials(me.kind === "key" ? me.id.slice(4) : me.name);
374
+ document.getElementById("who").title = "what you acknowledge is recorded as " + me.recorded_as;
375
+ }
376
+
377
+ document.getElementById("signout").addEventListener("click", event => {
378
+ event.preventDefault();
379
+ sessionStorage.removeItem(TOKEN);
380
+ closePicker();
381
+ Object.assign(state, { clients: [], client: null, overview: null, me: null });
382
+ Object.keys(views).forEach(key => delete views[key]); // the next person starts afresh
383
+ main();
384
+ put(document.getElementById("side-stores"));
385
+ document.getElementById("picker-name").textContent = "Pick a client";
386
+ document.getElementById("picker-stores").textContent = "";
387
+ document.getElementById("login-token").value = "";
388
+ showWho(null);
389
+ showLogin("");
390
+ });
391
+
392
+ // --- the client picker -------------------------------------------------------------------------------------
393
+
394
+ function recent() { try { return JSON.parse(localStorage.getItem(RECENT) || "[]"); } catch { return []; } }
395
+
396
+ function renderPicker() {
397
+ const query = document.getElementById("picker-search").value.toLowerCase();
398
+ const list = document.getElementById("picker-list");
399
+ const shown = state.clients.filter(c => (c.name + " " + c.id).toLowerCase().includes(query));
400
+ const firsts = recent().map(id => shown.find(c => c.id === id)).filter(Boolean);
401
+ const option = client => el("button", { type: "button", class: "opt" + (state.client && client.id === state.client.id ? " sel" : ""),
402
+ onclick: () => { location.hash = "#/c/" + encodeURIComponent(client.id) + "/overview"; closePicker(); } },
403
+ el("b", { text: client.name }), el("small", { text: client.stores.length + " store(s)" }));
404
+ put(list, firsts.length && !query ? el("h5", { text: "Recent" }) : null, query ? [] : firsts.map(option),
405
+ el("h5", { text: "All clients (" + shown.length + ")" }), shown.map(option));
406
+ }
407
+
408
+ function openPicker() {
409
+ document.getElementById("dropdown").classList.add("open");
410
+ document.getElementById("picker-search").focus();
411
+ renderPicker();
412
+ }
413
+ function closePicker() { document.getElementById("dropdown").classList.remove("open"); }
414
+ document.getElementById("picker").addEventListener("click", () =>
415
+ document.getElementById("dropdown").classList.contains("open") ? closePicker() : openPicker());
416
+ document.getElementById("picker-search").addEventListener("input", renderPicker);
417
+ document.getElementById("picker").addEventListener("keydown", event => {
418
+ if (event.key !== "Enter" && event.key !== " ") return;
419
+ event.preventDefault();
420
+ document.getElementById("dropdown").classList.contains("open") ? closePicker() : openPicker();
421
+ });
422
+ document.addEventListener("keydown", event => { if (event.key === "Escape") closePicker(); });
423
+ document.addEventListener("click", event => {
424
+ if (!event.target.closest("#picker, #dropdown")) closePicker();
425
+ });
426
+
427
+ // --- screens -----------------------------------------------------------------------------------------------
428
+
429
+ function main(...children) { put(document.getElementById("main"), children); }
430
+ function loading() { main(el("div", { class: "empty", text: "Loading…" })); }
431
+ function failed(error) { main(el("div", { class: "empty err", text: "Could not load: " + error.message })); }
432
+ function errorsNote(errors) {
433
+ const entries = Object.entries(errors || {});
434
+ const of = code => entries.filter(([, c]) => c === code).map(([store]) => store);
435
+ const empty = of("not-created"), pending = of("migrations-pending");
436
+ const down = entries.filter(([, code]) => code !== "not-created" && code !== "migrations-pending");
437
+ return [down.length ? el("div", { class: "note err", text: "Not reachable: " + down.map(([s, c]) => s + " (" + c + ")").join(", ") }) : null,
438
+ empty.length ? el("div", { class: "note", text: "No database yet (a first run creates it): " + empty.join(", ") }) : null,
439
+ pending.length ? el("div", { class: "note", text: "No run history yet, its migrations are pending (streamwright state " +
440
+ "migrate): " + pending.join(", ") }) : null];
441
+ }
442
+
443
+ async function overviewScreen(client) {
444
+ const sub = el("div", { class: "sub" }), cards = el("div", { class: "cards" });
445
+ const card = (n, label, kind, link) => el(link ? "a" : "div", { class: "card " + (kind || ""), href: link && link.href,
446
+ title: link && link.title },
447
+ el("div", { class: "n", text: n }), el("div", { class: "l", text: label }));
448
+ const told = (label, n) => n ? label + " · " + number(n) + " acknowledged" : label;
449
+ const draw = async () => { // the counts: again after an acknowledgement
450
+ const summary = await api("/v1/clients/" + encodeURIComponent(client.id) + "/overview");
451
+ state.overview = summary;
452
+ renderStores(summary.stores.map(s => s.reachable && s.migrations_pending.length ?
453
+ { ...s, reachable: false, error: "migrations-pending" } : s));
454
+ const counts = summary.counts, acked = counts.acknowledged || {};
455
+ const badge = document.getElementById("nav-attention");
456
+ badge.textContent = counts.attention;
457
+ badge.classList.toggle("hidden", !counts.attention);
458
+ const pending = summary.stores.reduce((n, s) => n + s.migrations_pending.length, 0);
459
+ sub.textContent = summary.stores.filter(s => s.reachable).length + " of " + summary.stores.length +
460
+ " store(s) reachable · " + number(counts.jobs) + " job(s) · " + number(counts.scopes) + " scope(s)";
461
+ put(cards, card(counts.failed, told("Failed", acked.failed), "fail"),
462
+ card(counts.held, told("Held", acked.held), "held"), card(counts.rejected, told("Rejected", acked.rejected), "rej"),
463
+ card(counts.running, "Running", "run"), card(counts.ok, "OK", "ok"),
464
+ card(counts.failed_runs || 0, told("Failed runs", acked.failed_runs), counts.failed_runs ? "fail" : "", {
465
+ href: "#/c/" + encodeURIComponent(client.id) + "/job-runs?status=failed",
466
+ title: "jobs whose latest run failed where no batch shows it (a lookup, a database it could not reach)" }),
467
+ card(pending, "Pending migrations"));
468
+ return summary;
469
+ };
470
+ const summary = await draw();
471
+ const attention = attentionPanel(client, () => Promise.all([draw(), attention.load()]));
472
+ main(el("div", { class: "titlebar" }, el("h1", { text: summary.name }),
473
+ refreshButton(() => overviewScreen(client))), sub, cards, attention.node);
474
+ await attention.load();
475
+ }
476
+
477
+ // --- acknowledging from the page (console.yaml: the client's ack_principals; never a DuckDB store) -----------
478
+
479
+ const ACK_COMMAND = /^streamwright state (ack|unack) /;
480
+
481
+ function canAck(client, store) { return Boolean(client.acknowledge && client.acknowledge.includes(store)); }
482
+
483
+ function acksPath(client, target, query) {
484
+ return "/v1/clients/" + encodeURIComponent(client.id) + "/acks" + (target ? "/" + encodeURIComponent(target) : "") +
485
+ queryString(query || {});
486
+ }
487
+
488
+ // a button that opens a note box; its `go` button sends `post(note)`, then `done()` draws the page again
489
+ function noteButton(label, go, post, done) {
490
+ const holder = el("div", { class: "acts" });
491
+ const open = () => {
492
+ const note = el("textarea", { maxlength: "500", "aria-label": "note",
493
+ placeholder: "Why (optional): what you know, what happens next" });
494
+ const said = el("span", { class: "err" });
495
+ const submit = el("button", { type: "button", class: "btn small primary", text: go, onclick: async () => {
496
+ submit.disabled = true;
497
+ try { await post(note.value); await done(); } catch (error) {
498
+ if (error.message !== "unauthorized") { said.textContent = error.message; submit.disabled = false; }
499
+ }
500
+ } });
501
+ const form = el("div", { class: "ackform" }, note, el("div", { class: "acts" }, submit,
502
+ el("button", { type: "button", class: "btn small", text: "Cancel", onclick: () => form.replaceWith(holder) }),
503
+ el("span", { class: "note", text: "recorded as " + (state.me ? state.me.recorded_as : "you") }), said));
504
+ holder.replaceWith(form);
505
+ note.focus();
506
+ };
507
+ put(holder, el("button", { type: "button", class: "btn small", text: label, onclick: open }));
508
+ return holder;
509
+ }
510
+
511
+ // a button that sends `action()` at once (an undo), then `done()`
512
+ function actButton(label, title, action, done) {
513
+ const said = el("span", { class: "err" });
514
+ const button = el("button", { type: "button", class: "btn small", text: label, title, onclick: async () => {
515
+ button.disabled = true;
516
+ try { await action(); await done(); } catch (error) {
517
+ if (error.message !== "unauthorized") { said.textContent = error.message; button.disabled = false; }
518
+ }
519
+ } });
520
+ return el("div", { class: "acts" }, button, said);
521
+ }
522
+
523
+ // an item's Acknowledge… or Undo (a batch's job id or a run's id), in place of its `state ack` / `unack` command
524
+ function ackActions(client, store, job, target, acked, done) {
525
+ return acked ? actButton("Undo", "it needs attention again", () => send("DELETE", acksPath(client, target, { store, job })), done)
526
+ : noteButton("Acknowledge…", "Acknowledge", note => send("POST", acksPath(client), { store, job, target, note }), done);
527
+ }
528
+
529
+ const ATTENTION_FIELDS = [["job", "Job"], ["scope", "Scope"], ["store", "Store"], ["error", "Error"]];
530
+ const KINDS = ["failed", "held", "rejected", "run", "other"];
531
+ const KIND_PILL = { failed: "fail", held: "held", rejected: "rej", interrupted: "held", unreachable: "fail", run: "fail" };
532
+
533
+ // one item of the attention list: what, where, since when, who acknowledged it (and why), and what to run (or, for
534
+ // a person who may acknowledge, its button instead of the `state ack` command)
535
+ function attentionItem(client, item, done) {
536
+ const ack = item.ack, can = canAck(client, item.store);
537
+ const ackable = can && (item.commands || []).some(text => ACK_COMMAND.test(text));
538
+ const commands = (item.commands || []).filter(text => !(can && ACK_COMMAND.test(text)));
539
+ return el("div", { class: "att" }, pill(item.kind, KIND_PILL[item.kind] || "idle"),
540
+ el("div", { class: "what" },
541
+ el("b", {}, item.job_id ? el("a", { href: batchHash(client, item.store, item.job_id, item.job), text: item.job })
542
+ : item.run_id ? el("a", { href: runHash(client, item.store, item.run_id, item.job), text: item.job })
543
+ : (item.job || "store " + item.store),
544
+ item.scope ? [" · ", ...wrapAt(item.scope)] : "", item.token ? " · " + item.token : "",
545
+ item.run_id ? " · " + item.run_id : "", ack ? pill("acknowledged", "idle") : null),
546
+ el("div", { class: "meta", text: [item.kind === "failed" && item.status === "abandoned" ? "abandoned" : null,
547
+ item.detail,
548
+ item.attempts ? "attempt " + item.attempts : null,
549
+ item.since ? ago(item.since) : null, "store " + item.store]
550
+ .filter(Boolean).join(" · ") }),
551
+ item.kind === "lease" && item.holder_run && showsLogs(client, item.store)
552
+ ? el("div", { class: "loglink" }, "The run that held it: ",
553
+ el("a", { href: runHash(client, item.store, item.holder_run, item.job, "log"), text: "open its log" }))
554
+ : null,
555
+ ack ? el("div", { class: "acked" }, "acknowledged " + ago(ack.at) + " by " + ack.by,
556
+ ack.note ? [": ", el("i", { text: ack.note })] : null) : null,
557
+ ackable ? ackActions(client, item.store, item.job, item.job_id || item.run_id, Boolean(ack), done) : null,
558
+ ...commands.map(command)));
559
+ }
560
+
561
+ // a job's items in one go, under the list: acknowledge them (or undo every acknowledgement of the job)
562
+ function attentionJob(client, entry, acked, done) {
563
+ const n = number(entry.items), store = entry.store, job = entry.job;
564
+ const button = !canAck(client, store) ? command(entry.command)
565
+ : acked ? actButton("Undo all " + n, "they need attention again",
566
+ () => send("DELETE", acksPath(client, null, { store, job, all: 1 })), done)
567
+ : noteButton("Acknowledge all " + n + "…", "Acknowledge " + n,
568
+ note => send("POST", acksPath(client), { store, job, all: true, note }), done);
569
+ return el("div", { class: "att job" }, pill("job", "idle"),
570
+ el("div", { class: "what" },
571
+ el("b", { text: acked ? "Every acknowledgement of " + entry.job : "Every item of " + entry.job + " (held ones aside)" }),
572
+ el("div", { class: "meta", text: n + (acked ? " acknowledged: undo them in one go"
573
+ : " need attention: acknowledge them in one go") + " · store " + store }),
574
+ button));
575
+ }
576
+
577
+ // the overview's list: what needs a person, or (the other tab) what a person acknowledged; chips by kind, the filters
578
+ // and the period (any time by default), a page at a time; `changed()`: after an acknowledgement (or its undo)
579
+ function attentionPanel(client, changed) {
580
+ const view = viewOf(client, "attention", { acked: "no", kind: "all", range: "all", limit: 25 });
581
+ const tabs = el("h3", { class: "ptabs", role: "tablist" }), chips = el("span", { class: "chips" });
582
+ const notes = el("div"), list = el("div"), pages = el("div");
583
+ let asked = 0;
584
+ const load = async () => {
585
+ const mine = ++asked;
586
+ const body = await api("/v1/clients/" + encodeURIComponent(client.id) + "/attention" + queryString({
587
+ ...rangeQuery(view), acked: view.acked, kind: view.kind === "all" ? null : view.kind, filter: filterParams(view),
588
+ limit: view.limit, offset: view.offset }));
589
+ if (mine !== asked) return;
590
+ if (!body.items.length && view.offset && body.total) { view.offset = 0; return load(); }
591
+ put(tabs, [["no", "Needs attention", body.needs_attention], ["yes", "Acknowledged", body.acknowledged]].map(
592
+ ([key, label, n]) => el("button", { type: "button", role: "tab", class: view.acked === key ? "on" : null,
593
+ "aria-selected": String(view.acked === key),
594
+ onclick: () => { view.acked = key; view.kind = "all"; view.offset = 0; load(); } },
595
+ label, el("span", { class: "n" + (key === "no" && n ? " fail" : ""), text: number(n) }))));
596
+ const all = Object.values(body.counts).reduce((a, b) => a + b, 0);
597
+ put(chips, ["all", ...KINDS].map(kind => el("button", {
598
+ type: "button", class: "chip" + (view.kind === kind ? " on" : ""), "aria-pressed": String(view.kind === kind),
599
+ text: (kind === "run" ? "runs" : kind) + " " + number(kind === "all" ? all : body.counts[kind]),
600
+ onclick: () => { view.kind = kind; view.offset = 0; load(); } })));
601
+ storeNames(client, body.errors);
602
+ put(notes, errorsNote(body.errors));
603
+ const acked = view.acked === "yes", narrowed = view.filters.length || view.range !== "all" || view.kind !== "all";
604
+ const switchTab = el("a", { href: "#", text: "Acknowledged", onclick: event => {
605
+ event.preventDefault(); view.acked = "yes"; view.kind = "all"; view.offset = 0; load(); } });
606
+ put(list, body.items.length ? [body.items.map(item => attentionItem(client, item, changed)),
607
+ body.jobs.map(entry => attentionJob(client, entry, acked, changed))]
608
+ : el("div", { class: "empty" }, narrowed ? "No item matches." : acked ? "Nothing is acknowledged."
609
+ : body.acknowledged ? ["Nothing needs a person. " + number(body.acknowledged) + " acknowledged item(s) are on the ",
610
+ switchTab, " tab."] : "Nothing needs a person."));
611
+ put(pages, body.total > view.limit || view.offset ? pager(view, body.total, load) : null);
612
+ };
613
+ const filter = filterButton(view, ATTENTION_FIELDS, () => { view.offset = 0; load(); });
614
+ const bar = el("div", { class: "pbar" }, el("div", { class: "filters" }, chips, filter.button,
615
+ rangeControl(view, () => { view.offset = 0; load(); })), filter.kept);
616
+ return { node: el("div", {}, el("div", { class: "panel" }, tabs, bar, notes, list), pages), load };
617
+ }
618
+
619
+ // a job's page: its Summary, or its "scopes" or "runs" tab (`query`: what the tab starts at, e.g. "?scope=...")
620
+ function jobHash(client, job, tab, query) {
621
+ return "#/c/" + encodeURIComponent(client.id) + "/job/" + encodeURIComponent(job) + (tab ? "/" + tab : "") +
622
+ (query || "");
623
+ }
624
+
625
+ // a link inside a clickable row: it opens its own page, not the row's
626
+ function rowLink(href, text, cls) {
627
+ return el("a", { href, text, class: cls || null, onclick: event => event.stopPropagation() });
628
+ }
629
+
630
+ // an output's outbox rows by status, as a bar and its legend
631
+ function outboxBar(output, counts) {
632
+ const total = Object.values(counts).reduce((a, b) => a + b, 0) || 1;
633
+ const bar = el("div", { class: "stack" });
634
+ for (const [status, color] of [["applied", "#86efac"], ["sent", "#86efac"], ["failed", "#f87171"],
635
+ ["in_flight", "#fbbf24"], ["pending", "#cbd5e1"]]) {
636
+ if (counts[status]) { const part = el("i"); part.style.width = (100 * counts[status] / total) + "%"; part.style.background = color; bar.append(part); }
637
+ }
638
+ return el("div", {}, el("b", { text: output }), bar, el("div", { class: "legend", text: outboxText(counts) }));
639
+ }
640
+
641
+ // the outputs of a set of batches (a run's, a job's): rows written to tables and files, and each apply output's bar
642
+ function outputsBody(outputs) {
643
+ const written = outputs.filter(o => o.rows !== null && o.rows !== undefined).map(o => el("tr", {},
644
+ el("td", { text: o.name }), el("td", { class: "num", text: number(o.rows) }), el("td", { class: "num", text: number(o.files) })));
645
+ const sent = outputs.filter(o => Object.keys(o.outbox).length).map(o => outboxBar(o.name, o.outbox));
646
+ return el("div", { class: "body" },
647
+ written.length ? table(["Written", { text: "Rows", num: true }, { text: "Files", num: true }], written, null, "written") : null,
648
+ sent.length ? sent : null, !written.length && !sent.length ? "Nothing written." : null);
649
+ }
650
+
651
+ // rejected rows grouped by output, tag and error code, the most first
652
+ function rejectionsTable(client, store, job, rejections, key) {
653
+ const rows = rejections.map(r => el("tr", {},
654
+ el("td", { text: r.output }), el("td", {}, el("span", { class: "mono", text: r.tag }), r.then ? el("span", { class: "then", text: " " + r.then }) : ""),
655
+ el("td", { class: "mono", text: r.error_code || "" }), el("td", { class: "num", text: number(r.rows) }),
656
+ el("td", {}, el("div", { class: "clip", text: r.error_message || "", title: r.error_message || null })),
657
+ el("td", {}, el("a", { class: "mono", href: batchHash(client, r.store || store, r.job_id, job), text: sequenceOf(r.job_id), title: r.job_id }))));
658
+ return table(["Output", "Tag", "Error code", { text: "Rows", num: true }, "Message", "A batch"], rows,
659
+ "No row was rejected.", key);
660
+ }
661
+
662
+ // a run's page; `tab` "log": its Log tab
663
+ function runHash(client, store, runId, job, tab) {
664
+ return "#/c/" + encodeURIComponent(client.id) + "/job-run/" + encodeURIComponent(store) + "/" +
665
+ encodeURIComponent(runId) + (tab ? "/" + tab : "") + (job ? "?job=" + encodeURIComponent(job) : "");
666
+ }
667
+
668
+ function batchHash(client, store, jobId, job) {
669
+ return "#/c/" + encodeURIComponent(client.id) + "/batch/" + encodeURIComponent(store) + "/" +
670
+ encodeURIComponent(jobId) + (job ? "?job=" + encodeURIComponent(job) : "");
671
+ }
672
+
673
+ // the state picked on a list's chips (kept while moving between screens)
674
+ const picked = { leases: "all" };
675
+
676
+ // --- long lists: the server filters, sorts and pages them -----------------------------------------------------
677
+
678
+ const PAGE_SIZES = [25, 50, 100, 200];
679
+ // a list's periods, the quick ranges of Grafana: the last N minutes count back from now; dates are UTC days, as the times
680
+ // are stored, so every viewer gets the same rows wherever they are
681
+ const RANGES = [["5m", "Last 5 minutes", 5], ["15m", "Last 15 minutes", 15], ["30m", "Last 30 minutes", 30],
682
+ ["1h", "Last 1 hour", 60], ["3h", "Last 3 hours", 180], ["6h", "Last 6 hours", 360],
683
+ ["12h", "Last 12 hours", 720], ["24h", "Last 24 hours", 1440], ["2d", "Last 2 days", 2880],
684
+ ["7d", "Last 7 days", 10080], ["30d", "Last 30 days", 43200], ["all", "Any time"],
685
+ ["custom", "Between dates (UTC)…"]];
686
+ const DESCENDING = ["last", "duration", "rows", "queued", "started", "runs"]; // these sort largest (newest) first
687
+ const views = {};
688
+
689
+ // a screen's query for a client (filters, sort, page), kept while the page is open; a list value repeats its name. A
690
+ // list's period: the last 15 minutes, unless its screen says otherwise (Needs attention: any time, as a problem waits
691
+ // for a person however old it is)
692
+ function viewOf(client, screen, defaults) {
693
+ const key = client.id + "/" + screen;
694
+ return views[key] = views[key] || { range: "15m", from: "", to: "", limit: 50, offset: 0, ...defaults };
695
+ }
696
+
697
+ function queryString(params) {
698
+ const pairs = Object.entries(params).flatMap(([k, v]) => Array.isArray(v) ? v.map(item => [k, item]) : [[k, v]])
699
+ .filter(([, v]) => v !== null && v !== undefined && v !== "");
700
+ return pairs.length ? "?" + pairs.map(([k, v]) => k + "=" + encodeURIComponent(v)).join("&") : "";
701
+ }
702
+
703
+ // since / until of a view's period: the last N minutes up to now, or UTC days (from, to: that day included), which
704
+ // the server reads as UTC midnights
705
+ function rangeQuery(view) {
706
+ const preset = RANGES.find(([name]) => name === view.range);
707
+ if (preset && preset[2]) return { since: new Date(Date.now() - preset[2] * 6e4).toISOString() };
708
+ return view.range === "custom" ? { since: view.from, until: view.to } : {};
709
+ }
710
+
711
+
712
+ const CHECK = ["M5 12.5l4.5 4.5L19 7.5"];
713
+ const UP_DOWN = ["M8 9.5l4-4 4 4", "M8 14.5l4 4 4-4"];
714
+ const CALENDAR = ["M4.5 7A1.5 1.5 0 0 1 6 5.5h12A1.5 1.5 0 0 1 19.5 7v11a1.5 1.5 0 0 1-1.5 1.5H6A1.5 1.5 0 0 1 4.5 18z",
715
+ "M4.5 10h15", "M8.5 3.5v4", "M15.5 3.5v4"];
716
+ const LEFT = ["M14.5 6l-6 6 6 6"];
717
+ const RIGHT = ["M9.5 6l6 6-6 6"];
718
+
719
+ // a menu or a calendar (.pop): its first child is the button that opens it; a click or the focus anywhere else shuts it
720
+ function shutPop(root) {
721
+ root.classList.remove("open", "up", "end");
722
+ root.firstElementChild.setAttribute("aria-expanded", "false");
723
+ }
724
+ document.addEventListener("click", event => {
725
+ const path = event.composedPath(); // as dispatched: a day redrawn since is still inside
726
+ for (const root of document.querySelectorAll(".pop.open")) if (!path.includes(root)) shutPop(root);
727
+ });
728
+ document.addEventListener("focusin", event => {
729
+ for (const root of document.querySelectorAll(".pop.open")) if (!root.contains(event.target)) shutPop(root);
730
+ });
731
+
732
+ // a select the console draws itself (a native one opens the system's own menu, which no style reaches): a button as wide
733
+ // as the longest option shows the choice and opens the options under it, or above it near the window's foot. The keys
734
+ // work as in a select: arrows, Home and End move, Enter or space picks, Escape or Tab leaves. picked(value) on a change
735
+ function menu(label, options, value, picked) {
736
+ const labels = options.map(([key, text]) => el("span", { class: key === value ? "on" : null, text }));
737
+ const button = el("button", { type: "button", class: "menu-button", "aria-haspopup": "listbox", "aria-expanded": "false",
738
+ "aria-label": label }, el("span", { class: "menu-labels" }, labels), icon(...UP_DOWN));
739
+ const items = options.map(([key, text]) => el("div", { role: "option", tabindex: "-1", "aria-selected": String(key === value),
740
+ onclick: () => choose(key), onmousemove: event => event.currentTarget.focus() }, icon(...CHECK), el("span", { text })));
741
+ const list = el("div", { class: "menu-list", role: "listbox", "aria-label": label, onkeydown: keys }, items);
742
+ const root = el("span", { class: "menu pop" }, button, list);
743
+
744
+ function open() {
745
+ document.querySelectorAll(".pop.open").forEach(pop => pop.contains(root) || shutPop(pop)); // not the one it is in
746
+ root.classList.add("open");
747
+ button.setAttribute("aria-expanded", "true");
748
+ const { top, bottom } = button.getBoundingClientRect(), below = window.innerHeight - bottom;
749
+ list.style.maxHeight = "";
750
+ const up = below < list.offsetHeight + 8 && top > below;
751
+ root.classList.toggle("up", up);
752
+ list.style.maxHeight = Math.min(440, Math.max(120, (up ? top : below) - 12)) + "px"; // scrolls in a short window
753
+ items[Math.max(0, options.findIndex(([key]) => key === value))].focus();
754
+ }
755
+ function close() { shutPop(root); button.focus(); }
756
+ function choose(key) {
757
+ close();
758
+ if (key === value) return;
759
+ value = key;
760
+ options.forEach(([k], i) => {
761
+ labels[i].classList.toggle("on", k === key);
762
+ items[i].setAttribute("aria-selected", String(k === key));
763
+ });
764
+ picked(key);
765
+ }
766
+ function keys(event) {
767
+ const at = items.indexOf(document.activeElement);
768
+ const to = { ArrowDown: at + 1, ArrowUp: at - 1, Home: 0, End: items.length - 1 }[event.key];
769
+ if (to !== undefined) items[Math.min(Math.max(to, 0), items.length - 1)].focus();
770
+ else if (event.key === "Enter" || event.key === " ") { if (at >= 0) choose(options[at][0]); }
771
+ else if (event.key === "Escape") close();
772
+ else if (event.key === "Tab") { shutPop(root); return; }
773
+ else return;
774
+ event.preventDefault();
775
+ }
776
+ button.addEventListener("click", () => root.classList.contains("open") ? close() : open());
777
+ button.addEventListener("keydown", event => {
778
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") { event.preventDefault(); open(); }
779
+ });
780
+ return root;
781
+ }
782
+
783
+ // the date pickers' days are UTC days written YYYY-MM-DD, which also sort as text; weeks start where the viewer's
784
+ // language says (Sunday when the browser does not tell)
785
+ const FIRST_DAY = (() => {
786
+ try {
787
+ const locale = new Intl.Locale(navigator.language);
788
+ return ((locale.getWeekInfo ? locale.getWeekInfo() : locale.weekInfo) || {}).firstDay % 7 || 0;
789
+ } catch { return 0; }
790
+ })();
791
+ const WEEKDAYS = Array.from({ length: 7 }, (_, i) => new Date(Date.UTC(2023, 0, 1 + (FIRST_DAY + i) % 7))
792
+ .toLocaleDateString(undefined, { weekday: "short", timeZone: "UTC" }).slice(0, 2)); // 1 Jan 2023 was a Sunday
793
+ const dayOf = day => new Date(day + "T00:00:00Z");
794
+ const isoDay = date => date.toISOString().slice(0, 10);
795
+ const todayUTC = () => isoDay(new Date());
796
+ const addDays = (day, n) => isoDay(new Date(dayOf(day).getTime() + n * 864e5));
797
+ function addMonths(day, n) {
798
+ const date = dayOf(day), year = date.getUTCFullYear(), month = date.getUTCMonth() + n;
799
+ const last = new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
800
+ return isoDay(new Date(Date.UTC(year, month, Math.min(date.getUTCDate(), last))));
801
+ }
802
+ const dayText = (day, style) => dayOf(day).toLocaleDateString(undefined, { ...style, timeZone: "UTC" });
803
+
804
+ // view.from or view.to, a date the console draws itself (a native one opens the system's own calendar): a button showing
805
+ // the day opens a month under it. Days after today, or past the range's other end, are refused; the days between the two
806
+ // ends are shaded. Arrows move a day or a week, Page Up / Page Down a month, Enter picks, Escape leaves; changed() after
807
+ // a pick
808
+ function datePicker(view, side, changed) {
809
+ const other = side === "from" ? "to" : "from";
810
+ const label = el("span");
811
+ const button = el("button", { type: "button", class: "date-button", "aria-haspopup": "dialog", "aria-expanded": "false",
812
+ title: side === "from" ? "from (UTC)" : "to, that day included (UTC)" },
813
+ icon(...CALENDAR), label);
814
+ const title = el("b");
815
+ const back = el("button", { type: "button", class: "cal-nav", "aria-label": "previous month",
816
+ onclick: () => move(addMonths(cursor, -1)) }, icon(...LEFT));
817
+ const ahead = el("button", { type: "button", class: "cal-nav", "aria-label": "next month",
818
+ onclick: () => { move(addMonths(cursor, 1)); if (ahead.disabled) back.focus(); } },
819
+ icon(...RIGHT));
820
+ const grid = el("div", { class: "cal-grid" });
821
+ const today = el("button", { type: "button", text: "Today", onclick: () => pick(todayUTC()) });
822
+ const calendar = el("div", { class: "calendar", role: "dialog", tabindex: "-1", onkeydown: keys,
823
+ "aria-label": (side === "from" ? "from" : "to") + ", a UTC day" },
824
+ el("div", { class: "cal-head" }, title, back, ahead), grid,
825
+ el("div", { class: "cal-foot" }, el("button", { type: "button", text: "Clear", onclick: () => pick("") }), today));
826
+ const root = el("span", { class: "datepick pop" }, button, calendar);
827
+ let cursor = ""; // the day the keys move from, in the month shown
828
+
829
+ const refused = day => day > todayUTC() || Boolean(side === "from" ? view.to && day > view.to
830
+ : view.from && day < view.from);
831
+ function caption() {
832
+ const day = view[side];
833
+ label.textContent = day ? dayText(day, { day: "numeric", month: "short", year: "numeric" })
834
+ : side === "from" ? "From" : "To";
835
+ button.classList.toggle("empty", !day);
836
+ button.setAttribute("aria-label", (side === "from" ? "from" : "to") + " (UTC): " + (day ? label.textContent : "not set"));
837
+ }
838
+ function move(day, focus) {
839
+ cursor = day;
840
+ const month = day.slice(0, 8) + "01", now = todayUTC();
841
+ title.textContent = dayText(month, { month: "long", year: "numeric" });
842
+ ahead.disabled = month >= now.slice(0, 8) + "01";
843
+ today.disabled = refused(now);
844
+ const lead = (dayOf(month).getUTCDay() - FIRST_DAY + 7) % 7;
845
+ const [low, high] = [view.from, view.to];
846
+ put(grid, WEEKDAYS.map(name => el("span", { class: "cal-wd", text: name })),
847
+ Array.from({ length: 42 }, (_, i) => addDays(month, i - lead)).map(d => el("button", {
848
+ type: "button", tabindex: d === day ? "0" : "-1", "data-day": d,
849
+ class: ["cal-day", d.slice(0, 7) !== month.slice(0, 7) && "out", d === now && "today", d === view[side] && "sel",
850
+ d === view[other] && "edge", low && high && d > low && d < high && "between"].filter(Boolean).join(" "),
851
+ "aria-pressed": String(d === view[side]), "aria-disabled": refused(d) ? "true" : null,
852
+ "aria-label": dayText(d, { weekday: "long", day: "numeric", month: "long", year: "numeric" }),
853
+ onclick: () => refused(d) || pick(d) }, Number(d.slice(8)))));
854
+ if (focus) grid.querySelector('[data-day="' + day + '"]').focus();
855
+ }
856
+ function open() {
857
+ document.querySelectorAll(".pop.open").forEach(shutPop);
858
+ root.classList.add("open");
859
+ button.setAttribute("aria-expanded", "true");
860
+ move(view[side] || view[other] || todayUTC(), true);
861
+ root.classList.toggle("end", calendar.getBoundingClientRect().right > document.documentElement.clientWidth - 8);
862
+ }
863
+ function close() { shutPop(root); button.focus(); }
864
+ function pick(day) {
865
+ close();
866
+ if (day === view[side]) return;
867
+ view[side] = day;
868
+ caption();
869
+ changed();
870
+ }
871
+ function keys(event) {
872
+ const step = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -7, ArrowDown: 7 }[event.key];
873
+ const onDay = Boolean(event.target.dataset && event.target.dataset.day);
874
+ if (event.key === "Escape") close();
875
+ else if (step && onDay) move(addDays(cursor, step), true);
876
+ else if ((event.key === "PageUp" || event.key === "PageDown") && onDay)
877
+ move(addMonths(cursor, event.key === "PageUp" ? -1 : 1), true);
878
+ else return;
879
+ event.preventDefault();
880
+ }
881
+ button.addEventListener("click", () => root.classList.contains("open") ? close() : open());
882
+ button.addEventListener("keydown", event => {
883
+ if (event.key === "ArrowDown") { event.preventDefault(); open(); }
884
+ });
885
+ caption();
886
+ return root;
887
+ }
888
+
889
+ // the period of a list: the menu and the dates change a draft, read when Apply is pressed (Apply stands out while the
890
+ // draft differs); the chips, the search, the sort, the pages and refresh keep the period last applied
891
+ function rangeControl(view, changed) {
892
+ const draft = { range: view.range, from: view.from, to: view.to };
893
+ const applied = () => draft.range === view.range && (draft.range !== "custom" ||
894
+ draft.from === view.from && draft.to === view.to);
895
+ const apply = el("button", { type: "button", class: "apply", text: "Apply", title: "read the list for this period",
896
+ onclick: () => { Object.assign(view, draft); mark(); changed(); } });
897
+ const mark = () => { apply.disabled = applied(); apply.classList.toggle("pending", !apply.disabled); };
898
+ const custom = el("span", { class: "custom" + (draft.range === "custom" ? "" : " hidden") },
899
+ datePicker(draft, "from", mark), " – ", datePicker(draft, "to", mark));
900
+ const when = menu("when", RANGES, draft.range, range => {
901
+ draft.range = range;
902
+ custom.classList.toggle("hidden", range !== "custom");
903
+ mark();
904
+ });
905
+ mark();
906
+ return el("span", { class: "range" }, when, custom, apply);
907
+ }
908
+
909
+ // "1–50 of 12,345", previous / next and the page size; changed() reloads
910
+ function pager(view, total, changed) {
911
+ const last = Math.min(view.offset + view.limit, total);
912
+ const go = offset => { view.offset = Math.max(0, offset); changed(); };
913
+ return el("div", { class: "pager" },
914
+ el("span", { text: total ? number(view.offset + 1) + "–" + number(last) + " of " + number(total) : "0 of 0" }),
915
+ el("button", { type: "button", text: "‹ Previous", disabled: view.offset === 0,
916
+ onclick: () => go(view.offset - view.limit) }),
917
+ el("button", { type: "button", text: "Next ›", disabled: last >= total, onclick: () => go(view.offset + view.limit) }),
918
+ menu("rows per page", PAGE_SIZES.map(size => [size, size + " per page"]), view.limit,
919
+ size => { view.limit = size; go(0); }));
920
+ }
921
+
922
+ // a header click on a server-sorted table: the same column flips, another starts with its natural order
923
+ function resort(view, key) {
924
+ view.order = view.sort === key ? (view.order === "asc" ? "desc" : "asc") : DESCENDING.includes(key) ? "desc" : "asc";
925
+ view.sort = key;
926
+ view.offset = 0;
927
+ }
928
+
929
+ // --- filters: conditions a list's rows must all meet ----------------------------------------------------------
930
+
931
+ // the comparisons, as the API names them (filter=FIELD:OP:VALUE)
932
+ const OPERATORS = [["contains", "contains"], ["not_contains", "does not contain"], ["equals", "equals"],
933
+ ["not_equals", "does not equal"], ["starts_with", "starts with"]];
934
+ const FUNNEL = ["M4 5.5h16l-6.2 7.3v5.2l-3.6 1.8v-7z"];
935
+ const PLUS = ["M12 5v14", "M5 12h14"];
936
+
937
+ // a view's filters, as the API takes them: one filter=FIELD:OP:VALUE each
938
+ function filterParams(view) { return (view.filters || []).map(f => f.field + ":" + f.op + ":" + f.value); }
939
+
940
+ // a list's filters (view.filters: the ones applied). The Filter button opens a panel of rows, each a column, a
941
+ // comparison and a value; + Add filter adds a row, × drops one. The rows are a draft until Apply (or Enter): then the
942
+ // rows with a value become the list's filters (all must hold, case aside) and applied() asks the server again. Escape
943
+ // or a click outside leaves them as they were. The button counts the filters applied; each shows as a chip under the
944
+ // filter row, whose × drops it at once. `fields`: [[key, label]]. Returns { button, kept }
945
+ function filterButton(view, fields, applied) {
946
+ view.filters = view.filters || [];
947
+ let draft = [];
948
+ const blank = () => ({ field: (fields.find(([key]) => !draft.some(f => f.field === key)) || fields[0])[0],
949
+ op: "contains", value: "" });
950
+ const name = (list, key) => (list.find(([k]) => k === key) || [key, key])[1];
951
+ const used = rows => rows.filter(f => f.value.trim()).map(f => ({ field: f.field, op: f.op, value: f.value.trim() }));
952
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
953
+ const count = el("span", { class: "n" });
954
+ const button = el("button", { type: "button", class: "fbtn", "aria-haspopup": "dialog", "aria-expanded": "false",
955
+ title: "filter the list" }, icon(...FUNNEL), "Filter", count);
956
+ const rows = el("div", { class: "frows" });
957
+ const apply = el("button", { type: "button", class: "apply", text: "Apply", title: "read the list with these filters",
958
+ onclick: () => commit() });
959
+ const panel = el("div", { class: "fpop", role: "dialog", "aria-label": "filters", onkeydown: event => {
960
+ if (event.key === "Escape" && !event.defaultPrevented) { event.preventDefault(); close(); } } },
961
+ rows,
962
+ el("div", { class: "ffoot" },
963
+ el("button", { type: "button", class: "fadd", onclick: () => { draft.push(blank()); draw(); focusLast(); } },
964
+ icon(...PLUS), "Add filter"),
965
+ el("span", { class: "spacer" }),
966
+ el("button", { type: "button", class: "fclear", text: "Clear all", onclick: () => {
967
+ draft = [blank()];
968
+ draw();
969
+ focusLast();
970
+ } }),
971
+ apply));
972
+ const root = el("span", { class: "fwrap pop" }, button, panel);
973
+ const kept = el("div", { class: "kept" });
974
+
975
+ // the button's count and the chips of the filters applied
976
+ function show() {
977
+ count.textContent = view.filters.length || "";
978
+ button.classList.toggle("on", view.filters.length > 0);
979
+ put(kept, view.filters.map(filter => el("span", { class: "fchip" },
980
+ name(fields, filter.field) + " " + name(OPERATORS, filter.op) + " ", el("b", { text: filter.value }),
981
+ el("button", { type: "button", "aria-label": "drop this filter", title: "drop this filter", text: "×",
982
+ onclick: () => set(view.filters.filter(f => f !== filter)) }))),
983
+ view.filters.length > 1 ? el("button", { type: "button", class: "clear", text: "Clear all",
984
+ onclick: () => set([]) }) : null);
985
+ }
986
+ // the filters applied become `filters`: the list is read again
987
+ function set(filters) {
988
+ view.filters = filters;
989
+ show();
990
+ applied();
991
+ }
992
+ // Apply stands out while the draft differs from the filters applied
993
+ function mark() {
994
+ apply.disabled = same(used(draft), view.filters);
995
+ apply.classList.toggle("pending", !apply.disabled);
996
+ }
997
+ function draw() {
998
+ put(rows, draft.map(filter => {
999
+ const input = el("input", { class: "finput", value: filter.value, placeholder: "value", "aria-label": "value",
1000
+ oninput: event => { filter.value = event.target.value; mark(); },
1001
+ onkeydown: event => { if (event.key === "Enter") { event.preventDefault(); commit(); } } });
1002
+ const change = key => value => { filter[key] = value; mark(); input.focus(); };
1003
+ return el("div", { class: "frow" },
1004
+ menu("column", fields.map(([key, text]) => [key, text]), filter.field, change("field")),
1005
+ menu("comparison", OPERATORS, filter.op, change("op")),
1006
+ input,
1007
+ el("button", { type: "button", class: "fx", text: "×", title: "remove this filter",
1008
+ "aria-label": "remove this filter", onclick: () => {
1009
+ draft.splice(draft.indexOf(filter), 1);
1010
+ if (!draft.length) draft.push(blank());
1011
+ draw();
1012
+ focusLast();
1013
+ } }));
1014
+ }));
1015
+ mark();
1016
+ }
1017
+ function focusLast() {
1018
+ const inputs = rows.querySelectorAll("input");
1019
+ if (inputs.length) inputs[inputs.length - 1].focus();
1020
+ }
1021
+ function open() {
1022
+ document.querySelectorAll(".pop.open").forEach(shutPop);
1023
+ draft = view.filters.map(f => ({ ...f }));
1024
+ if (!draft.length) draft.push(blank());
1025
+ draw();
1026
+ root.classList.add("open");
1027
+ button.setAttribute("aria-expanded", "true");
1028
+ root.classList.toggle("end", panel.getBoundingClientRect().right > document.documentElement.clientWidth - 8);
1029
+ focusLast();
1030
+ }
1031
+ function close() {
1032
+ shutPop(root);
1033
+ button.focus();
1034
+ }
1035
+ function commit() {
1036
+ const filters = used(draft);
1037
+ close();
1038
+ if (!same(filters, view.filters)) set(filters);
1039
+ }
1040
+ button.addEventListener("click", () => root.classList.contains("open") ? close() : open());
1041
+ show();
1042
+ return { button: root, kept };
1043
+ }
1044
+
1045
+ const JOB_SUMMARY_FIELDS = [["job", "Job"], ["store", "Store"]];
1046
+ const SCOPE_FIELDS = [["scope", "Scope"], ["store", "Store"]];
1047
+ const JOB_RUN_FIELDS = [["job", "Job"], ["run", "Run id"], ["store", "Store"], ["error", "Error"]];
1048
+ const RUN_OF_JOB_FIELDS = [["run", "Run id"], ["store", "Store"], ["error", "Error"]];
1049
+ const SERVE_RUN_FIELDS = [["job", "Job"], ["run", "Run id"], ["caller", "Caller"], ["store", "Store"],
1050
+ ["error", "Error code"]];
1051
+
1052
+ const HEALTH_ORDER = ["failed", "held", "rejected", "running", "ok"];
1053
+
1054
+ // Jobs: each job once, the worst first: its scopes' health now, its latest run, its runs and rows in the period
1055
+ async function jobsScreen(client) {
1056
+ const view = viewOf(client, "jobs", { health: "all", sort: "health", order: "asc" });
1057
+ const chips = el("span", { class: "chips" }), notes = el("div"), box = el("div", { class: "panel", id: "jobs-table" });
1058
+ const pages = el("div");
1059
+ let asked = 0;
1060
+ const load = async () => {
1061
+ const mine = ++asked;
1062
+ const body = await api("/v1/clients/" + encodeURIComponent(client.id) + "/job-summaries" + queryString({
1063
+ ...rangeQuery(view), health: view.health === "all" ? null : view.health, filter: filterParams(view),
1064
+ sort: view.sort, order: view.order, limit: view.limit, offset: view.offset }));
1065
+ if (mine !== asked) return;
1066
+ if (!body.jobs.length && view.offset && body.total) { view.offset = 0; return load(); }
1067
+ const all = Object.values(body.counts).reduce((a, b) => a + b, 0);
1068
+ put(chips, ["all", ...HEALTH_ORDER].map(health => el("button", {
1069
+ type: "button", class: "chip" + (view.health === health ? " on" : ""), "aria-pressed": String(view.health === health),
1070
+ text: health + " " + number(health === "all" ? all : body.counts[health]),
1071
+ onclick: () => { view.health = health; view.offset = 0; load(); } })));
1072
+ put(notes, errorsNote(body.errors));
1073
+ storeNames(client, body.errors);
1074
+ const rows = body.jobs.map(job => {
1075
+ const run = job.last_run, rows = job.rows;
1076
+ const lines = [[rows.written, "written"], [rows.applied, "applied"], [rows.rejected, "rejected", "issue rej"],
1077
+ [rows.held, "held", "issue held"]].filter(([n]) => n);
1078
+ return el("tr", { class: "click", onclick: () => location.hash = jobHash(client, job.job) },
1079
+ el("td", {}, pill(job.health, HEALTH[job.health])),
1080
+ el("td", {}, el("div", { class: "job" }, rowLink(jobHash(client, job.job), job.job))),
1081
+ el("td", {}, Object.keys(job.scopes).length
1082
+ ? el("div", { class: "hc" }, HEALTH_ORDER.filter(h => job.scopes[h]).map(h => pill(number(job.scopes[h]) + " " + h, HEALTH[h])))
1083
+ : el("span", { class: "muted", text: "no batch yet" }),
1084
+ job.acknowledged ? el("div", { class: "scope acked", text: number(job.acknowledged) + " acknowledged" }) : null),
1085
+ el("td", {}, run ? [el("div", {}, pill(run.status, RUN_STATUS[run.status]), " ",
1086
+ rowLink(runHash(client, run.store, run.run_id, job.job), ago(run.started_at))),
1087
+ el("div", { class: "scope", text: duration(run.duration_ms) + " · " + number(run.batches) +
1088
+ " batch(es)" })] : "–"),
1089
+ el("td", { class: "num", "data-sort": job.runs.total }, number(job.runs.total),
1090
+ job.runs.statuses.failed ? el("div", { class: "issue", text: number(job.runs.statuses.failed) + " failed" }) : null),
1091
+ el("td", { class: "num lines" }, lines.length ? lines.map(([n, what, cls]) =>
1092
+ el("div", { class: cls || null, text: number(n) + " " + what })) : "–"),
1093
+ el("td", { text: job.stores.join(", ") }));
1094
+ });
1095
+ put(box, table(
1096
+ [{ text: "Health", sort: "health" }, { text: "Job", sort: "job" }, "Scopes now", { text: "Last run", sort: "last" },
1097
+ { text: "Runs", num: true, sort: "runs" }, { text: "Rows", num: true }, "Store"],
1098
+ rows, view.filters.length ? "No job matches the filters." : all ? "No job matches." : "No job yet.", "job-summaries",
1099
+ { by: view.sort, order: view.order, onSort: key => { resort(view, key); load(); } }));
1100
+ put(pages, body.total ? pager(view, body.total, load) : null);
1101
+ };
1102
+ const filter = filterButton(view, JOB_SUMMARY_FIELDS, () => { view.offset = 0; load(); });
1103
+ main(el("h1", { text: "Jobs" }),
1104
+ el("div", { class: "sub", text: client.name + " · each job once: its scopes' health now, its runs and rows in the period" }),
1105
+ el("div", { class: "filters" }, chips, filter.button, rangeControl(view, () => { view.offset = 0; load(); }),
1106
+ el("span", { class: "spacer" }), refreshButton(load)),
1107
+ filter.kept, notes, box, pages);
1108
+ await load();
1109
+ }
1110
+
1111
+ // a job's Scopes tab: each scope's newest batch, newest first (`scope`: the one it starts at; `several`: the job is in
1112
+ // several stores, so a Store column); a row opens the batch
1113
+ function scopesTab(client, job, scope, several) {
1114
+ const view = viewOf(client, "scopes:" + job, { health: "all", sort: "last", order: "desc" });
1115
+ if (scope !== null) { view.filters = [{ field: "scope", op: "equals", value: scope }]; view.health = "all"; view.offset = 0; }
1116
+ const chips = el("span", { class: "chips" }), notes = el("div"), box = el("div", { class: "panel", id: "jobs-table" });
1117
+ const pages = el("div");
1118
+ let asked = 0;
1119
+ const load = async () => {
1120
+ const mine = ++asked;
1121
+ const body = await api("/v1/clients/" + encodeURIComponent(client.id) + "/jobs" + queryString({
1122
+ job, ...rangeQuery(view), health: view.health === "all" ? null : view.health, filter: filterParams(view),
1123
+ sort: view.sort, order: view.order, limit: view.limit, offset: view.offset }));
1124
+ if (mine !== asked) return;
1125
+ if (!body.jobs.length && view.offset && body.total) { view.offset = 0; return load(); }
1126
+ const all = Object.values(body.counts).reduce((a, b) => a + b, 0);
1127
+ put(chips, ["all", ...HEALTH_ORDER].map(health => el("button", {
1128
+ type: "button", class: "chip" + (view.health === health ? " on" : ""), "aria-pressed": String(view.health === health),
1129
+ text: health + " " + number(health === "all" ? all : body.counts[health]),
1130
+ onclick: () => { view.health = health; view.offset = 0; load(); } })));
1131
+ put(notes, errorsNote(body.errors));
1132
+ storeNames(client, body.errors);
1133
+ const rows = body.jobs.map(row => el("tr", { class: "click", onclick: () => location.hash =
1134
+ batchHash(client, row.store, row.last.job_id, row.job) },
1135
+ el("td", {}, pill(row.health, HEALTH[row.health]), row.ack ? el("div", { class: "acked" }, el("span", {
1136
+ class: "pill idle", text: "acknowledged", title: "acknowledged " + ago(row.ack.at) + " by " + row.ack.by +
1137
+ (row.ack.note ? ": " + row.ack.note : "") })) : null),
1138
+ el("td", { class: "mono" }, el("div", { class: "long" }, wrapAt(row.scope || "–"))),
1139
+ several ? el("td", { text: row.store }) : null,
1140
+ el("td", {}, when(row.last.created_at)),
1141
+ el("td", { class: "num", text: duration(row.last.duration_ms) }),
1142
+ el("td", { class: "num" }, number(row.last.rows_written),
1143
+ Object.entries(row.last.outbox).map(([status, n]) =>
1144
+ el("div", { class: "scope", text: number(n) + " " + status.replace("_", " ") }))),
1145
+ el("td", { class: "day", title: "open the row: its batch page lists this scope's batches" },
1146
+ Object.entries(row.day).map(([s, n]) => el("div", { text: n + " " + s })), Object.keys(row.day).length ? null : "–"),
1147
+ el("td", { class: "issue " + (HEALTH[row.health] || "") }, el("div", { class: "clip", text: row.issue || "", title: row.issue || null }))));
1148
+ put(box, table(
1149
+ [{ text: "Health", sort: "health" }, { text: "Scope", sort: "job" }, several ? { text: "Store", sort: "store" } : null,
1150
+ { text: "Last batch", sort: "last" }, { text: "Duration", num: true, sort: "duration" },
1151
+ { text: "Rows", num: true, sort: "rows" }, "Last 24 h", "Issue"].filter(Boolean),
1152
+ rows, view.filters.length ? "No scope matches the filters." : view.range !== "all" ? "No scope ran in this period."
1153
+ : all ? "No scope matches." : "No batch yet.", "scopes",
1154
+ { by: view.sort, order: view.order, onSort: key => { resort(view, key); load(); } }));
1155
+ put(pages, body.outside ? el("div", { class: "outside", text: number(body.outside) + " more scope(s) last ran " +
1156
+ "outside this period" }) : null,
1157
+ body.total ? pager(view, body.total, load) : null);
1158
+ };
1159
+ const filter = filterButton(view, SCOPE_FIELDS, () => { view.offset = 0; load(); });
1160
+ return { node: el("div", {}, el("div", { class: "filters" }, chips, filter.button,
1161
+ rangeControl(view, () => { view.offset = 0; load(); })),
1162
+ filter.kept, notes, box, pages), load };
1163
+ }
1164
+
1165
+ const HISTORY = 20;
1166
+ const sequenceOf = id => { const tail = id.split("-").pop(); return /^\d+$/.test(tail) ? "#" + Number(tail) : id; };
1167
+
1168
+ // the batches of a batch's job and scope, newest first (this one marked); each other one opens it
1169
+ async function scopeBatches(client, store, batch) {
1170
+ let body;
1171
+ try {
1172
+ body = await api("/v1/clients/" + encodeURIComponent(client.id) + "/jobs/" + encodeURIComponent(batch.job) +
1173
+ "/batches?store=" + encodeURIComponent(store) + "&scope=" + encodeURIComponent(batch.scope || "") +
1174
+ "&limit=" + HISTORY);
1175
+ } catch (error) {
1176
+ return null; // the batch itself still shows
1177
+ }
1178
+ const rows = body.batches.map(b => {
1179
+ const current = b.job_id === batch.job_id;
1180
+ return el("tr", { class: current ? "current" : "click", "aria-current": current ? "page" : null,
1181
+ onclick: current ? null : () => { location.hash = batchHash(client, store, b.job_id, batch.job); } },
1182
+ el("td", { class: "mono", text: sequenceOf(b.job_id), title: b.job_id, "data-sort": b.job_id }),
1183
+ el("td", {}, pill(b.status, STATUS[b.status])), el("td", {}, when(b.created_at)),
1184
+ el("td", { class: "num", text: duration(b.duration_ms), "data-sort": b.duration_ms }),
1185
+ el("td", { class: "num", text: number(b.rows_written), "data-sort": b.rows_written }),
1186
+ el("td", { class: "nowrap", text: outboxText(b.outbox) || "–" }),
1187
+ el("td", { class: "issue fail", text: b.error || "", title: b.error || null }));
1188
+ });
1189
+ return panel("Batches", "this job and scope, newest first" + (rows.length >= HISTORY ? " · the last " + HISTORY : ""),
1190
+ el("div", { class: "history" },
1191
+ table(["Batch", "Status", "Created", { text: "Duration", num: true }, { text: "Rows", num: true }, "Outbox",
1192
+ "Error"], rows, "No batch.", "history")));
1193
+ }
1194
+
1195
+ // who acknowledged a batch's or a run's problem, when and why; its Undo (`state unack` under Fix it otherwise)
1196
+ function acknowledged(ack, undo) {
1197
+ return ack ? panel("Acknowledged", ago(ack.at) + " by " + ack.by, el("div", { class: "body" },
1198
+ ack.note || el("span", { class: "muted", text: "no note" }), undo)) : null;
1199
+ }
1200
+
1201
+ // a batch's or a run's Fix it: its commands; for a person who may acknowledge, Acknowledge… instead of `state ack`
1202
+ function fixIt(client, store, job, target, ack, commands, done) {
1203
+ const can = canAck(client, store), ackable = can && !ack && commands.some(text => ACK_COMMAND.test(text));
1204
+ const shown = commands.filter(text => !(can && ACK_COMMAND.test(text)));
1205
+ return shown.length || ackable ? panel("Fix it", can ? "acknowledge here; the other fixes with the state CLI"
1206
+ : "actions come to the console later; today, with the state CLI",
1207
+ el("div", { class: "body" }, ackable ? ackActions(client, store, job, target, false, done) : null,
1208
+ shown.map(command))) : null;
1209
+ }
1210
+
1211
+ async function batchScreen(client, store, jobId, job) {
1212
+ const query = "?store=" + encodeURIComponent(store) + (job ? "&job=" + encodeURIComponent(job) : "");
1213
+ const batch = await api("/v1/clients/" + encodeURIComponent(client.id) + "/batches/" + encodeURIComponent(jobId) + query);
1214
+ const steps = [["received", batch.created_at], ["processing", batch.started_at]];
1215
+ const failedStep = ["failed", "abandoned"].includes(batch.status);
1216
+ const ended = failedStep || ["completed", "skipped"].includes(batch.status);
1217
+ steps.push([failedStep ? batch.status + (batch.failed_from ? " (from " + batch.failed_from + ")" : "") : batch.status,
1218
+ batch.finished_at || (ended ? batch.updated_at : null)]);
1219
+ const timeline = el("div", { class: "timeline" }, steps.map(([name, at], i) =>
1220
+ el("div", { class: "step" + (i === steps.length - 1 && failedStep ? " x" : "") + (at || i === 0 ? "" : " n") },
1221
+ el("div", { class: "c", text: i === steps.length - 1 && failedStep ? "✕" : "✓" }),
1222
+ el("b", { text: name }), el("small", { text: at ? at.replace("T", " ").replace("Z", " UTC") : "–" }))));
1223
+ const manifest = batch.manifest || {};
1224
+ const kv = el("dl", { class: "kv" });
1225
+ const add = (k, v) => { if (v !== undefined && v !== null && v !== "") kv.append(el("dt", {}, wrapAt(k)), el("dd", { class: "mono" }, wrapAt(v))); };
1226
+ add("scope", batch.scope); add("job key", batch.job_key); add("batch time", manifest.batch_ts);
1227
+ add("run", manifest.run_id); add("duration", duration(batch.duration_ms));
1228
+ if (manifest.inputs && manifest.inputs.config) Object.entries(manifest.inputs.config).forEach(([k, v]) => add(k, shown(v)));
1229
+ if (manifest.input) add("input rows", number(manifest.input.rows) + " (sha256 " + String(manifest.input.sha256 || "").slice(0, 12) + "…)");
1230
+ if (manifest.messages) add("messages", manifest.messages);
1231
+ if (manifest.pinned) add("pinned values", manifest.pinned.join(", "));
1232
+ const receipts = Object.entries(batch.receipts || {}).map(([output, r]) => el("tr", {},
1233
+ el("td", { text: output }), el("td", { class: "num", text: number(r.rows), "data-sort": r.rows }),
1234
+ el("td", { class: "mono", text: (r.files && r.files.length > 1 ? r.files.length + " files" : r.destination) || "–" })));
1235
+ const outbox = Object.entries(batch.outbox || {}).map(([output, counts]) => outboxBar(output, counts));
1236
+ const rows = (batch.outbox_rows || []).map(r => el("tr", {}, el("td", { text: r.output }),
1237
+ el("td", { class: "num", text: r.row }), el("td", {}, pill(r.status.replace("_", " "), STATUS[r.status] || (r.status === "in_flight" ? "held" : "fail"))),
1238
+ el("td", {}, r.tag ? el("span", { class: "mono", text: r.tag }) : "", r.then ? el("span", { class: "then", text: " " + r.then }) : ""),
1239
+ el("td", { class: "num", text: r.attempts }), el("td", { class: "mono", text: r.error_code || "" }),
1240
+ el("td", { text: r.error_message || "" })));
1241
+ const history = await scopeBatches(client, store, batch), redraw = () => batchScreen(client, store, jobId, job);
1242
+ const log = batchLogPanel(client, store, batch);
1243
+ main(el("div", { class: "crumbs" }, el("a", { href: "#/c/" + encodeURIComponent(client.id) + "/jobs", text: "Jobs" }),
1244
+ " / ", el("a", { href: jobHash(client, batch.job), text: batch.job }), " / ",
1245
+ el("a", { href: jobHash(client, batch.job, "scopes", "?scope=" + encodeURIComponent(batch.scope || "")),
1246
+ title: "this scope on its job's Scopes tab" }, wrapAt(batch.scope || "–")), " / store " + store),
1247
+ el("div", { class: "bhead" }, el("h1", { class: "mono", text: batch.job_id }), pill(batch.status, STATUS[batch.status]),
1248
+ el("span", { class: "meta", text: "attempt " + batch.attempts + (batch.error ? " · " + batch.error : "") }),
1249
+ batch.request_id ? el("span", { class: "meta" }, "run ",
1250
+ el("a", { class: "mono", href: runHash(client, store, batch.request_id, batch.job), text: batch.request_id }),
1251
+ batch.resumed_by ? [" · resumed by ", el("a", { class: "mono", href: runHash(client, store, batch.resumed_by, batch.job),
1252
+ text: batch.resumed_by })] : null,
1253
+ " ", logsLink(batch.request_id, batch.job_id)) : null,
1254
+ refreshButton(() => batchScreen(client, store, jobId, job))),
1255
+ acknowledged(batch.ack, batch.ack && canAck(client, store) ?
1256
+ ackActions(client, store, batch.job, batch.job_id, true, redraw) : null),
1257
+ panel("Timeline", "times in UTC", el("div", { class: "body" }, timeline)),
1258
+ history,
1259
+ el("div", { class: "grid2 wide-first" },
1260
+ panel("Pinned", "no row values, no secrets", el("div", { class: "body" }, kv)),
1261
+ panel("Outputs", null, el("div", { class: "body" },
1262
+ receipts.length ? table(["Written", { text: "Rows", num: true }, "Where"], receipts, null, "receipts") : null,
1263
+ outbox.length ? outbox : null, !receipts.length && !outbox.length ? "No output yet." : null))),
1264
+ panel("Rows not applied", (batch.outbox_rows || []).length + " · row values are not shown",
1265
+ table(["Output", { text: "Row", num: true }, "Status", "Tag", { text: "Attempts", num: true }, "Error code", "Message"], rows,
1266
+ Object.keys(batch.outbox || {}).length ? "Every row was applied or sent." : "No row was queued to apply.",
1267
+ "rows")),
1268
+ fixIt(client, store, batch.job, batch.job_id, batch.ack, batch.commands || [], redraw),
1269
+ log ? log.node : null); // its lines last: what the page says first, how it went after
1270
+ if (log) await log.load();
1271
+ }
1272
+
1273
+ async function runsScreen(client) {
1274
+ const view = viewOf(client, "runs", { sort: "queued", order: "desc" });
1275
+ const notes = el("div"), box = el("div", { class: "panel" }), pages = el("div");
1276
+ let asked = 0;
1277
+ const load = async () => {
1278
+ const mine = ++asked;
1279
+ const body = await api("/v1/clients/" + encodeURIComponent(client.id) + "/runs" + queryString({
1280
+ ...rangeQuery(view), filter: filterParams(view), sort: view.sort, order: view.order, limit: view.limit,
1281
+ offset: view.offset }));
1282
+ if (mine !== asked) return;
1283
+ const rows = body.runs.map(run => el("tr", {},
1284
+ el("td", { class: "mono small", text: run.run_id }), el("td", { text: run.job }), el("td", { text: run.caller }),
1285
+ el("td", {}, pill(run.status, STATUS[run.status])), el("td", {}, when(run.created_at)),
1286
+ el("td", { class: "result" },
1287
+ Object.entries(run.result.responses).map(([n, r]) => el("div", { text: n + ": " + number(r.total) + " row(s)",
1288
+ title: r.expired ? "its rows were cleared after response.ttl" : null }, r.expired ? el("span", { class: "muted", text: " · cleared" }) : null)),
1289
+ Object.entries(run.result.downloads).map(([n, f]) => el("div", { text: n + ": " + f + " file(s)" })),
1290
+ (run.result.outputs || []).filter(o => !(o.name in run.result.responses) && !(o.name in run.result.downloads))
1291
+ .map(o => el("div", { text: o.name + ": " + number(o.rows) + " row(s) written" })),
1292
+ run.error_code ? el("div", { class: "issue", text: run.error_code }) : null)));
1293
+ storeNames(client, body.errors);
1294
+ put(notes, errorsNote(body.errors));
1295
+ put(box, el("h3", {}, "Requests", el("small", { text: "inputs and row values are never shown" })),
1296
+ table([{ text: "Run", sort: "run" }, { text: "Job", sort: "job" }, { text: "Caller", sort: "caller" },
1297
+ { text: "Status", sort: "status" }, { text: "Queued", sort: "queued" }, "Result"],
1298
+ rows, view.filters.length ? "No serve request matches the filters." : view.range === "all"
1299
+ ? "No serve request in these stores." : "No serve request in this period.", "runs",
1300
+ { by: view.sort, order: view.order, onSort: key => { resort(view, key); load(); } }));
1301
+ put(pages, body.total ? pager(view, body.total, load) : null);
1302
+ };
1303
+ const filter = filterButton(view, SERVE_RUN_FIELDS, () => { view.offset = 0; load(); });
1304
+ main(el("h1", { text: "Serve requests" }),
1305
+ el("div", { class: "sub", text: client.name + " · the runs callers asked serve for, in stores that are a serve queue" }),
1306
+ el("div", { class: "filters" }, filter.button, rangeControl(view, () => { view.offset = 0; load(); }),
1307
+ el("span", { class: "spacer" }), refreshButton(load)),
1308
+ filter.kept, notes, box, pages);
1309
+ await load();
1310
+ }
1311
+
1312
+ // the runs of the jobs (sw_runs), newest first: how each ended, its batches and passes, and what failed where no batch
1313
+ // shows it. `job`: one job's (its page's Runs tab: no job column, no job filter; `several`: in several stores, so a Store
1314
+ // column); `status`, `jobFilter`: where the Runs page starts (a link's ?status= or ?job=); `refresh`: the list has its
1315
+ // own refresh button
1316
+ function runsTable(client, { job = null, several = true, status = null, jobFilter = null, refresh = false } = {}) {
1317
+ const view = viewOf(client, job ? "runs-of:" + job : "job-runs", { status: "all", sort: "started", order: "desc" });
1318
+ // a link's runs (the overview's Failed runs: their jobs' latest runs, however old) are in the list whatever their age
1319
+ if (status) { view.status = status; view.offset = 0; view.range = "all"; }
1320
+ if (jobFilter) {
1321
+ view.filters = [{ field: "job", op: "equals", value: jobFilter }];
1322
+ Object.assign(view, { status: "all", offset: 0, range: "all" });
1323
+ }
1324
+ const chips = el("span", { class: "chips" }), notes = el("div"), box = el("div", { class: "panel" });
1325
+ const pages = el("div"), logs = Boolean(client.logs && client.logs.length);
1326
+ several = several || !job; // the Runs page always has its Store column
1327
+ let asked = 0;
1328
+ const load = async () => {
1329
+ const mine = ++asked;
1330
+ const body = await api("/v1/clients/" + encodeURIComponent(client.id) + "/job-runs" + queryString({
1331
+ job, ...rangeQuery(view), status: view.status === "all" ? null : view.status, filter: filterParams(view),
1332
+ sort: view.sort, order: view.order, limit: view.limit, offset: view.offset }));
1333
+ if (mine !== asked) return;
1334
+ const all = Object.values(body.counts).reduce((a, b) => a + b, 0);
1335
+ put(chips, ["all", "failed", "succeeded", "skipped", "busy"].map(s => el("button", {
1336
+ type: "button", class: "chip" + (view.status === s ? " on" : ""), "aria-pressed": String(view.status === s),
1337
+ text: s + " " + number(s === "all" ? all : body.counts[s]),
1338
+ onclick: () => { view.status = s; view.offset = 0; load(); } })));
1339
+ storeNames(client, body.errors);
1340
+ put(notes, errorsNote(body.errors));
1341
+ const rows = body.runs.map(run => el("tr", { class: "click", onclick: () => location.hash =
1342
+ runHash(client, run.store, run.run_id, run.job) },
1343
+ el("td", {}, pill(run.status, RUN_STATUS[run.status])),
1344
+ job ? el("td", { class: "mono", text: run.run_id })
1345
+ : el("td", {}, el("div", { class: "job" }, rowLink(jobHash(client, run.job), run.job)),
1346
+ el("div", { class: "scope mono", text: run.run_id })),
1347
+ several ? el("td", { text: run.store }) : null, el("td", {}, when(run.started_at)),
1348
+ el("td", { class: "num", text: duration(run.duration_ms) }),
1349
+ el("td", { class: "num", text: number(run.batches), title: "the scopes it worked on (a batch each)" }),
1350
+ el("td", { class: "num", text: run.passes === null ? "–" : number(run.passes) +
1351
+ (run.failed_passes ? " (" + number(run.failed_passes) + " failed)" : "") }),
1352
+ el("td", { class: "num" + (run.unbatched_failures ? " err" : ""),
1353
+ text: run.unbatched_failures ? number(run.unbatched_failures) : "–" }),
1354
+ el("td", { class: "issue fail" }, el("div", { class: "clip", text: run.error || "", title: run.error || null })),
1355
+ logs ? logCell(client, run) : null));
1356
+ put(box, table(
1357
+ [{ text: "Status", sort: "status" }, job ? "Run" : { text: "Job · run", sort: "job" }, several ? "Store" : null,
1358
+ { text: "Started", sort: "started" }, { text: "Duration", num: true, sort: "duration" },
1359
+ { text: "Batches", num: true }, { text: "Passes", num: true }, { text: "Before a batch", num: true }, "Error",
1360
+ logs ? "Log" : null].filter(Boolean),
1361
+ rows, view.filters.length ? "No run matches the filters." : view.range === "all"
1362
+ ? "No run is recorded in these stores." : "No run in this period.", job ? "runs-of-job" : "job-runs",
1363
+ { by: view.sort, order: view.order, onSort: key => { resort(view, key); load(); } }));
1364
+ put(pages, body.total ? pager(view, body.total, load) : null);
1365
+ };
1366
+ const filter = filterButton(view, job ? RUN_OF_JOB_FIELDS : JOB_RUN_FIELDS, () => { view.offset = 0; load(); });
1367
+ return { node: el("div", {}, el("div", { class: "filters" }, chips, filter.button,
1368
+ rangeControl(view, () => { view.offset = 0; load(); }),
1369
+ refresh ? [el("span", { class: "spacer" }), refreshButton(load)] : null),
1370
+ filter.kept, notes, box, pages), load };
1371
+ }
1372
+
1373
+ // Runs: every run of every job, newest first (a link's ?status= or ?job= is where it starts)
1374
+ async function jobRunsScreen(client, status, job) {
1375
+ const runs = runsTable(client, { status, jobFilter: job, refresh: true });
1376
+ main(el("h1", { text: "Runs" }),
1377
+ el("div", { class: "sub", text: client.name + " · every run of every job, newest first, also those that failed " +
1378
+ "before a batch" }), runs.node);
1379
+ await runs.load();
1380
+ }
1381
+
1382
+ // a few numbers in cards: [value, label, kind]
1383
+ function cardsOf(items) {
1384
+ return el("div", { class: "cards" }, items.map(([n, label, kind]) =>
1385
+ el("div", { class: "card " + (kind || "") }, el("div", { class: "n", text: n }), el("div", { class: "l", text: label }))));
1386
+ }
1387
+
1388
+ // the rows a set of batches did not apply: output, row, status, tag, attempts, error (never the row's values)
1389
+ function notAppliedTable(client, store, job, rows, key) {
1390
+ return table(["Batch", "Output", { text: "Row", num: true }, "Status", "Tag", { text: "Attempts", num: true }, "Error code", "Message"],
1391
+ rows.map(r => el("tr", {},
1392
+ el("td", {}, el("a", { class: "mono", href: batchHash(client, store, r.job_id, job), text: sequenceOf(r.job_id), title: r.job_id })),
1393
+ el("td", { text: r.output }), el("td", { class: "num", text: r.row }),
1394
+ el("td", {}, pill(r.status.replace("_", " "), STATUS[r.status] || (r.status === "in_flight" ? "held" : "fail"))),
1395
+ el("td", {}, r.tag ? el("span", { class: "mono", text: r.tag }) : "", r.then ? el("span", { class: "then", text: " " + r.then }) : ""),
1396
+ el("td", { class: "num", text: r.attempts }), el("td", { class: "mono", text: r.error_code || "" }),
1397
+ el("td", {}, el("div", { class: "clip", text: r.error_message || "", title: r.error_message || null })))),
1398
+ "Every row was applied or sent.", key);
1399
+ }
1400
+
1401
+ // a run's batches (those it made or resumed): the scopes it worked on, a page at a time
1402
+ function runBatches(client, store, run) {
1403
+ const view = viewOf(client, "run-batches:" + run.run_id, { status: "all", limit: 25, range: "all" });
1404
+ const chips = el("span", { class: "chips" }), box = el("div"), pages = el("div");
1405
+ const base = "/v1/clients/" + encodeURIComponent(client.id) + "/job-runs/" + encodeURIComponent(run.run_id) + "/batches";
1406
+ const load = async () => {
1407
+ const body = await api(base + queryString({ store, job: run.job, status: view.status === "all" ? null : view.status,
1408
+ limit: view.limit, offset: view.offset }));
1409
+ const all = Object.values(body.counts).reduce((a, b) => a + b, 0);
1410
+ put(chips, ["all", ...Object.keys(body.counts).sort()].map(s => el("button", {
1411
+ type: "button", class: "chip" + (view.status === s ? " on" : ""), "aria-pressed": String(view.status === s),
1412
+ text: s + " " + number(s === "all" ? all : body.counts[s]), onclick: () => { view.status = s; view.offset = 0; load(); } })));
1413
+ put(box, table(["Scope", "Batch", "Status", "Created", { text: "Duration", num: true }, { text: "Rows", num: true }, "Outbox", "Error"],
1414
+ body.batches.map(b => el("tr", { class: "click", onclick: () => { location.hash = batchHash(client, store, b.job_id, run.job); } },
1415
+ el("td", { class: "mono" }, el("div", { class: "long" }, wrapAt(b.scope || "–"))),
1416
+ el("td", { class: "mono", text: sequenceOf(b.job_id), title: b.job_id }),
1417
+ el("td", {}, pill(b.status, STATUS[b.status]), b.resumed ? el("span", { class: "muted", text: " resumed" }) : null),
1418
+ el("td", {}, when(b.created_at)), el("td", { class: "num", text: duration(b.duration_ms) }),
1419
+ el("td", { class: "num", text: number(b.rows_written) }), el("td", { class: "nowrap", text: outboxText(b.outbox) || "–" }),
1420
+ el("td", { class: "issue fail" }, el("div", { class: "clip", text: b.error || "", title: b.error || null })))),
1421
+ "No scope: the run failed before a batch, or had nothing new.", "run-batches"));
1422
+ put(pages, body.total > view.limit ? pager(view, body.total, load) : null);
1423
+ };
1424
+ return { load, panel: panel("Scopes it worked on", "a batch each, made or resumed by this run",
1425
+ el("div", { class: "body" }, el("div", { class: "filters" }, chips)), box, pages) };
1426
+ }
1427
+
1428
+ // --- a run's own log file (--log-dir), where the store's console.yaml entry sets logs.dir --------------------------
1429
+
1430
+ const LOG_VIEW = { level: "", q: "", job_id: "" };
1431
+ const LOG_LEVELS = [["", "All"], ["error", "Errors"], ["warning", "Warnings"], ["info", "Info"], ["debug", "Debug"]];
1432
+ const LOG_KINDS = { CRITICAL: "ERROR", ERROR: "ERROR", WARNING: "WARNING", INFO: "INFO", DEBUG: "DEBUG" };
1433
+ const LOG_TAGS = ["item", "scope", "step", "output", "lookup"]; // the log context a line shows
1434
+ const LOG_STATUS = { writing: ["run", "the run is still writing it"], complete: ["ok", null],
1435
+ cut: ["held", "lines were dropped from its middle: it reached --log-max-size"],
1436
+ failed: ["fail", "writing it failed part way: the file ends early"] };
1437
+ const NO_LOG = "This run wrote no log file: it ran without --log-dir (or STREAMWRIGHT_LOG_DIR).";
1438
+ const FOLLOW_MS = 5000;
1439
+ const FOLLOW_IDLE = 120; // reads without a new line (10 minutes) before following pauses
1440
+
1441
+ function showsLogs(client, store) { return Boolean(client.logs && client.logs.includes(store)); }
1442
+
1443
+ // a count and its noun: "1 error", "2 errors"
1444
+ function counted(n, one, many) { return number(n) + " " + (Number(n) === 1 ? one : many); }
1445
+
1446
+ function logBase(client, runId) {
1447
+ return "/v1/clients/" + encodeURIComponent(client.id) + "/job-runs/" + encodeURIComponent(runId) + "/log";
1448
+ }
1449
+
1450
+ function sizeOf(bytes) {
1451
+ if (bytes === null || bytes === undefined) return "–";
1452
+ const units = ["B", "KB", "MB", "GB", "TB"];
1453
+ let value = bytes, unit = 0;
1454
+ while (value >= 1024 && unit < units.length - 1) { value /= 1024; unit += 1; }
1455
+ return (unit ? value.toFixed(value < 10 ? 1 : 0) : value) + " " + units[unit];
1456
+ }
1457
+
1458
+ // a path as a shell reads it: quoted when it holds more than letters, digits and / . _ - : , = + @ %
1459
+ function shellWord(text) { return /^[\w@%+=:,./-]+$/.test(text) ? text : "'" + text.replace(/'/g, "'\\''") + "'"; }
1460
+
1461
+ // one line: its number (a finished file's), time (UTC), level, logger, message, context and traceback; its batch is a
1462
+ // button where onBatch(job_id) picks it
1463
+ function logLine(line, numbered, onBatch) {
1464
+ const level = line.level ? String(line.level) : "", kind = LOG_KINDS[level] || "";
1465
+ const labels = line.labels && typeof line.labels === "object" ? Object.entries(line.labels) : [];
1466
+ const batch = line.job_id ? String(line.job_id) : null;
1467
+ const tags = [...LOG_TAGS.filter(key => line[key]).map(key => el("span", {
1468
+ text: key === "item" ? String(line.item) : key + "=" + line[key] })),
1469
+ ...labels.map(([key, value]) => el("span", { text: key + "=" + value })),
1470
+ batch && onBatch ? el("button", { type: "button", text: "batch " + sequenceOf(batch),
1471
+ title: "only this batch's lines · " + batch, onclick: () => onBatch(batch) })
1472
+ : batch ? el("span", { text: "batch " + sequenceOf(batch), title: batch }) : null].filter(Boolean);
1473
+ return el("tr", { class: kind || null },
1474
+ numbered ? el("td", { class: "n", text: line.line === undefined ? "" : number(line.line) }) : null,
1475
+ el("td", { class: "t", text: line.time ? String(line.time).slice(11, 23) : "", title: line.time || null }),
1476
+ el("td", { class: "lv" }, level ? el("span", { class: "lvl " + kind, text: level }) : null),
1477
+ el("td", { class: "lg", text: String(line.logger || "").replace(/^streamwright\.(core\.)?/, ""),
1478
+ title: line.logger || null }),
1479
+ el("td", { class: "msg" }, line.message === undefined ? "" : String(line.message),
1480
+ tags.length ? el("div", { class: "ctx" }, tags) : null,
1481
+ line.exception ? el("pre", { class: "exc", text: String(line.exception) }) : null,
1482
+ line.stack ? el("pre", { class: "exc", text: String(line.stack) }) : null));
1483
+ }
1484
+
1485
+ // a run's lines meeting filters() ({level, q, job_id}): a page of its last lines (a short log: all of it) in a box that
1486
+ // opens at its top, "Load earlier" above them; a file still written is followed (new lines every FOLLOW_MS, the box
1487
+ // staying at its end once scrolled there) until the run ends it, the person pauses, or none came for a while.
1488
+ // shown(body): each first page's answer (where the file is, whether this host reads it); onBatch(job_id): a line's batch
1489
+ function logLines(client, store, runId, job, filters, { shown = () => {}, onBatch = null } = {}) {
1490
+ const rows = el("tbody"), top = el("div"), foot = el("div");
1491
+ const box = el("div", { class: "logscroll" }, top, el("table", { class: "loglines" }, rows));
1492
+ const node = el("div", {}, box, foot);
1493
+ const ask = cursor => api(logBase(client, runId) + queryString({ store, job, ...filters(), ...cursor }));
1494
+ const narrowed = () => Object.values(filters()).some(Boolean);
1495
+ let before = null, after = null, numbered = false, following = false, paused = false, idle = 0, timer = null;
1496
+ let asked = 0, turns = 0, first = null; // first: the number of the first line shown (a finished file's)
1497
+ const draw = (lines, atStart) => {
1498
+ const made = lines.map(line => logLine(line, numbered, onBatch));
1499
+ if (atStart) rows.prepend(...made); else rows.append(...made);
1500
+ if (lines.length && lines[0].line !== undefined && (atStart || first === null)) first = lines[0].line;
1501
+ };
1502
+ const earlier = () => before ? el("div", { class: "more" }, el("button", {
1503
+ type: "button", class: "btn small", text: narrowed() ? "Search earlier lines"
1504
+ : "Load earlier lines" + (first > 1 ? " (" + number(first - 1) + " more)" : ""),
1505
+ onclick: async event => {
1506
+ const button = event.currentTarget, mine = asked;
1507
+ button.disabled = true;
1508
+ try {
1509
+ const body = await ask({ before });
1510
+ if (mine !== asked) return;
1511
+ if (body.reset) { load(); return; } // the run ended it since: its last lines again
1512
+ const height = box.scrollHeight;
1513
+ before = body.before;
1514
+ draw(body.lines, true);
1515
+ put(top, earlier());
1516
+ box.scrollTop += box.scrollHeight - height; // the lines in view stay in view
1517
+ put(foot, ending());
1518
+ } catch (error) {
1519
+ button.disabled = false;
1520
+ button.title = "It failed: " + error.message;
1521
+ }
1522
+ } })) : null;
1523
+ const ending = () => [
1524
+ rows.children.length ? null : el("div", { class: "empty", text: narrowed() ? "No line matches." + (before
1525
+ ? " Search earlier lines for more." : "") : following ? "No line yet." : "The log has no line." }),
1526
+ following ? el("div", { class: "follow" }, el("span", { class: "live" + (paused ? " off" : "") }),
1527
+ paused ? (idle >= FOLLOW_IDLE ? "No new line for 10 minutes: paused" : "Paused")
1528
+ : "Following: new lines every " + FOLLOW_MS / 1000 + " seconds",
1529
+ el("button", { type: "button", class: "btn small", text: paused ? "Resume" : "Pause", onclick: () => {
1530
+ paused = !paused;
1531
+ idle = 0;
1532
+ put(foot, ending());
1533
+ if (!paused) tick();
1534
+ } })) : null];
1535
+ const tick = async () => {
1536
+ clearTimeout(timer);
1537
+ if (!node.isConnected || paused || !following) return; // another page, or not followed now
1538
+ const mine = asked, turn = ++turns; // a later turn (Resume) takes over
1539
+ try {
1540
+ const body = await ask({ after });
1541
+ if (mine !== asked || turn !== turns || !node.isConnected) return;
1542
+ if (body.reset || body.log.status !== "writing") { load(); return; } // the run ended it: as it is now
1543
+ after = body.after;
1544
+ idle = body.lines.length ? 0 : idle + 1;
1545
+ const atEnd = box.scrollHeight - box.scrollTop - box.clientHeight < 40; // at the end: it stays there
1546
+ draw(body.lines, false);
1547
+ if (atEnd) box.scrollTop = box.scrollHeight;
1548
+ paused = idle >= FOLLOW_IDLE;
1549
+ put(foot, ending());
1550
+ } catch (error) {
1551
+ if (error.message === "unauthorized" || mine !== asked || turn !== turns) return;
1552
+ }
1553
+ if (!paused) timer = setTimeout(tick, FOLLOW_MS);
1554
+ };
1555
+ const load = async () => {
1556
+ const mine = ++asked;
1557
+ clearTimeout(timer);
1558
+ let body;
1559
+ try {
1560
+ body = await ask({});
1561
+ } catch (error) {
1562
+ if (mine !== asked || error.message === "unauthorized") return;
1563
+ following = false;
1564
+ put(rows);
1565
+ put(top);
1566
+ put(foot, el("div", { class: "empty" + (error.code === "no-log" ? "" : " err"),
1567
+ text: error.code === "no-log" ? NO_LOG : "Could not read the log: " + error.message }));
1568
+ return;
1569
+ }
1570
+ if (mine !== asked) return;
1571
+ numbered = body.lines.some(line => line.line !== undefined);
1572
+ [before, after, first] = [body.before, body.after, null];
1573
+ following = body.readable && body.log.status === "writing";
1574
+ idle = 0;
1575
+ put(rows);
1576
+ draw(body.lines, false);
1577
+ put(top, earlier());
1578
+ shown(body);
1579
+ put(foot, body.readable ? ending() : null);
1580
+ box.scrollTop = 0; // its first lines in view
1581
+ if (following && !paused) timer = setTimeout(tick, FOLLOW_MS);
1582
+ };
1583
+ return { node, load };
1584
+ }
1585
+
1586
+ // a log toolbar's level chips (All, Errors, ...) in `node`: view.level; counts ({error, warning} or null) by the chips
1587
+ function levelChips(node, view, counts, changed) {
1588
+ put(node, LOG_LEVELS.map(([key, label]) => {
1589
+ const n = counts ? counts[key] : null;
1590
+ return el("button", { type: "button", class: "chip" + (view.level === key ? " on" : ""),
1591
+ "aria-pressed": String(view.level === key),
1592
+ text: label + (n === null || n === undefined ? "" : " " + number(n)),
1593
+ onclick: () => { view.level = key; levelChips(node, view, counts, changed); changed(); } });
1594
+ }));
1595
+ }
1596
+
1597
+ // a search box: its text (trimmed) in view.q, then changed(), at Enter or after a pause in the typing
1598
+ function searchBox(view, changed) {
1599
+ const box = el("input", { type: "search", class: "search", placeholder: "Search messages",
1600
+ "aria-label": "Search the log's messages", value: view.q || null });
1601
+ let typing = null;
1602
+ const apply = () => {
1603
+ clearTimeout(typing);
1604
+ if (box.value.trim() === view.q) return;
1605
+ view.q = box.value.trim();
1606
+ changed();
1607
+ };
1608
+ box.addEventListener("input", () => { clearTimeout(typing); typing = setTimeout(apply, 500); });
1609
+ box.addEventListener("keydown", event => { if (event.key === "Enter") apply(); });
1610
+ return box;
1611
+ }
1612
+
1613
+ // where a run's log file is: its path (as the host that wrote it names it), state, lines, size, host and start
1614
+ function logWhere(log) {
1615
+ const [kind, why] = LOG_STATUS[log.status] || ["idle", null];
1616
+ const known = value => value !== null && value !== undefined;
1617
+ return el("div", { class: "where" }, el("span", { class: "mono", text: log.path || "–" }),
1618
+ el("span", { title: why }, pill(log.status, kind)),
1619
+ known(log.line_count) ? el("span", { text: counted(log.line_count, "line", "lines") }) : null,
1620
+ known(log.bytes) ? el("span", { text: sizeOf(log.bytes) + (known(log.stored_bytes) && log.stored_bytes !== log.bytes
1621
+ ? " (" + sizeOf(log.stored_bytes) + " stored)" : "") }) : null,
1622
+ log.host ? el("span", { text: "written on " + log.host }) : null, el("span", {}, "started ", when(log.started_at)));
1623
+ }
1624
+
1625
+ // a log this host cannot show: why, and how to open it where it is (or in the log tool, links.logs)
1626
+ function logNotice(runId, body) {
1627
+ const log = body.log, host = log.host || "the host that wrote it", file = log.path || "", link = logsLink(runId, null);
1628
+ const open = (file.endsWith(".gz") ? "gzip -dc " : log.status === "writing" ? "tail -f " : "cat ") + shellWord(file);
1629
+ return el("div", { class: "notice" }, el("b", { text: "This log cannot be shown here" }),
1630
+ ": " + String(body.message || "").replace(/\.$/, "") + ".",
1631
+ body.reason === "refused" ? el("div", { text: "Its row names a file that is not this run's log: the console's own " +
1632
+ "log says which." })
1633
+ : [el("div", {}, "Give this store a ", el("code", { text: "logs.dir" }), " the console can read (a shared folder " +
1634
+ "such as NFS or EFS), or open it on " + host + ":"), file ? command(open) : null],
1635
+ link ? el("div", {}, link, " (links.logs)") : null);
1636
+ }
1637
+
1638
+ // a run's Log tab: its lines with a toolbar (a level, a search, one batch, the file to download) and where the file is;
1639
+ // or, when this host cannot read it, where it is and how to open it. `listBatches`: false for a run with no history
1640
+ // (the batch list needs one; a line's batch tag still picks a batch)
1641
+ function runLogPanel(client, store, runId, job, { listBatches = true } = {}) {
1642
+ const view = viewOf(client, "log:" + store + ":" + runId, LOG_VIEW);
1643
+ const chips = el("span", { class: "chips" }), batches = el("span"), where = el("div");
1644
+ const sub = el("small", { text: "its own log file" });
1645
+ const file = el("button", { type: "button", class: "btn small", text: "Download", title: "the whole file",
1646
+ onclick: () => download(logBase(client, runId) + "/download" + queryString({ store, job }),
1647
+ file) });
1648
+ let counts = null, listed = [];
1649
+ const pick = id => { view.job_id = id; drawBatches(); part.load(); };
1650
+ const part = logLines(client, store, runId, job, () => ({ level: view.level || null, q: view.q || null,
1651
+ job_id: view.job_id || null }), {
1652
+ onBatch: pick,
1653
+ shown: body => {
1654
+ const log = body.log, done = log.status !== "writing";
1655
+ counts = done ? { error: log.error_count, warning: log.warning_count } : null;
1656
+ levelChips(chips, view, counts, () => part.load());
1657
+ bar.hidden = !body.readable;
1658
+ file.textContent = done ? "Download" : "Download so far";
1659
+ sub.textContent = body.readable ? "its own log file" : [log.status,
1660
+ done ? counted(log.line_count, "line", "lines") : null, done ? counted(log.error_count, "error", "errors") : null,
1661
+ done ? counted(log.warning_count, "warning", "warnings") : null].filter(Boolean).join(" · ");
1662
+ put(where, body.readable ? logWhere(log) : logNotice(runId, body));
1663
+ } });
1664
+ const bar = el("div", { class: "pbar" }, el("div", { class: "filters" }, chips, searchBox(view, () => part.load()),
1665
+ batches, el("span", { class: "spacer" }), file));
1666
+ // the batch menu: the run's first batches (a line's batch tag picks any other)
1667
+ const drawBatches = () => {
1668
+ const options = listed.map(b => [b.job_id, sequenceOf(b.job_id) + " · " + clipped(b.scope || "–", 32)]);
1669
+ if (view.job_id && !options.some(([id]) => id === view.job_id)) options.unshift([view.job_id, sequenceOf(view.job_id)]);
1670
+ put(batches, options.length ? menu("batch", [["", "All batches"], ...options], view.job_id, pick) : null);
1671
+ };
1672
+ const loadBatches = async () => {
1673
+ try {
1674
+ listed = listBatches ? (await api("/v1/clients/" + encodeURIComponent(client.id) + "/job-runs/" +
1675
+ encodeURIComponent(runId) + "/batches" + queryString({ store, job, limit: 50 })))
1676
+ .batches : [];
1677
+ } catch (error) {
1678
+ listed = [];
1679
+ }
1680
+ drawBatches();
1681
+ };
1682
+ levelChips(chips, view, counts, () => part.load());
1683
+ drawBatches();
1684
+ return { node: el("div", { class: "panel log" }, el("h3", {}, "Log", sub), bar, where, part.node),
1685
+ load: () => Promise.all([part.load(), loadBatches()]) };
1686
+ }
1687
+
1688
+ function clipped(text, size) { return text.length > size ? text.slice(0, size - 1) + "…" : text; }
1689
+
1690
+ // a batch's Log: its lines (its job_id) in the log of the run that made it and of the one that resumed it, each under
1691
+ // its run, whose link opens that run's Log tab on this batch
1692
+ function batchLogPanel(client, store, batch) {
1693
+ const runs = [[batch.request_id, "made it"], [batch.resumed_by, "resumed it"]]
1694
+ .filter(([id], i, all) => id && all.findIndex(([other]) => other === id) === i);
1695
+ if (!showsLogs(client, store) || !runs.length) return null;
1696
+ const view = viewOf(client, "batch-log:" + store + ":" + batch.job_id, LOG_VIEW);
1697
+ const filters = () => ({ level: view.level || null, q: view.q || null, job_id: batch.job_id });
1698
+ const groups = runs.map(([runId, role]) => {
1699
+ const title = el("div", { class: "group" });
1700
+ const link = el("a", { class: "mono", href: runHash(client, store, runId, batch.job, "log"), text: runId,
1701
+ title: "the run's Log tab, on this batch", onclick: () => {
1702
+ viewOf(client, "log:" + store + ":" + runId, LOG_VIEW).job_id = batch.job_id; } });
1703
+ put(title, "Run ", link, " · " + role);
1704
+ const part = logLines(client, store, runId, batch.job, filters, { shown: body => put(title, "Run ", link,
1705
+ " · " + role, body.log.host ? " · " + body.log.host : "", " · started ", when(body.log.started_at),
1706
+ body.readable ? null : el("div", { class: "muted", text: "This log cannot be shown here: " + body.message })) });
1707
+ return { node: el("div", { class: "loggroup" }, title, part.node), load: part.load };
1708
+ });
1709
+ const chips = el("span", { class: "chips" });
1710
+ const load = () => Promise.all(groups.map(group => group.load()));
1711
+ levelChips(chips, view, null, load);
1712
+ return { node: el("div", { class: "panel log" },
1713
+ el("h3", {}, "Log", el("small", { text: "this batch's lines, from each run that worked on it" })),
1714
+ el("div", { class: "pbar" }, el("div", { class: "filters" }, chips, searchBox(view, load))),
1715
+ groups.map(group => group.node)), load };
1716
+ }
1717
+
1718
+ // a run's Log cell on a runs list: its log's errors and warnings (or that it is still written), its Log tab a click away
1719
+ function logCell(client, run) {
1720
+ const log = run.log;
1721
+ if (!showsLogs(client, run.store)) return el("td", { class: "logcol muted", text: "–" });
1722
+ if (!log) return el("td", { class: "logcol muted", text: "none", title: NO_LOG });
1723
+ const errors = log.error_count || 0, warnings = log.warning_count || 0;
1724
+ return el("td", { class: "logcol" }, rowLink(runHash(client, run.store, run.run_id, run.job, "log"), "Log"),
1725
+ el("div", {}, log.status === "writing" ? el("span", { class: "muted", text: "writing" })
1726
+ : errors || warnings ? [errors ? el("span", { class: "e", text: number(errors) + " err" }) : null,
1727
+ errors && warnings ? " " : null,
1728
+ warnings ? el("span", { class: "w", text: number(warnings) + " warn" }) : null]
1729
+ : el("span", { class: "muted", text: "no errors" })));
1730
+ }
1731
+
1732
+ // a run's tabs where its store shows logs: Overview, and Log (its errors; "live" while the run writes it)
1733
+ function runTabs(client, store, run, tab) {
1734
+ const log = run.log, errors = log && log.status !== "writing" ? log.error_count : 0;
1735
+ const count = log && log.status === "writing" ? el("span", { class: "n", text: "live" })
1736
+ : errors ? el("span", { class: "n fail", text: counted(errors, "error", "errors") }) : null;
1737
+ const on = tab === "log" ? "log" : "overview";
1738
+ return el("div", { class: "tabs", role: "tablist" }, [["overview", "Overview", null], ["log", "Log", count]].map(
1739
+ ([key, label, extra]) => el("a", { href: runHash(client, store, run.run_id, run.job, key === "log" ? "log" : null),
1740
+ role: "tab", class: key === on ? "on" : null, "aria-selected": String(key === on) },
1741
+ label, extra)));
1742
+ }
1743
+
1744
+ // a run with no history (sw_runs) but a log file: still going, or it stopped before it could record how it ended
1745
+ async function unrecordedRunScreen(client, store, runId, job, missing) {
1746
+ let found;
1747
+ try {
1748
+ found = await api(logBase(client, runId) + queryString({ store, job, limit: 1 }));
1749
+ } catch (error) {
1750
+ throw error.status === 404 ? missing : error;
1751
+ }
1752
+ const log = found.log, part = runLogPanel(client, store, runId, found.job, { listBatches: false });
1753
+ main(el("div", { class: "crumbs" }, el("a", { href: "#/c/" + encodeURIComponent(client.id) + "/job-runs", text: "Runs" }),
1754
+ " / ", el("a", { href: jobHash(client, found.job), text: found.job }), " / store " + store),
1755
+ el("div", { class: "bhead" }, el("h1", { class: "mono", text: runId }), pill("no history", "held"),
1756
+ el("span", { class: "meta" }, found.job + " · started ", when(log.started_at), log.host ? " · on " + log.host : ""),
1757
+ refreshButton(() => jobRunScreen(client, store, runId, job, "log"))),
1758
+ el("div", { class: "sub", text: "It has no run history yet: the run is still going, or it stopped before it could " +
1759
+ "record how it ended (it died). Its log is below." }),
1760
+ part.node);
1761
+ await part.load();
1762
+ }
1763
+
1764
+ // one run: how it ended, its batches' totals, outputs and rows not applied, what failed before a batch, how to settle
1765
+ // it; where its store shows logs, its Log tab too (`tab` "log"); a run with no history but a log: that log
1766
+ async function jobRunScreen(client, store, runId, job, tab) {
1767
+ const base = "/v1/clients/" + encodeURIComponent(client.id) + "/job-runs/" + encodeURIComponent(runId);
1768
+ const query = "?store=" + encodeURIComponent(store) + (job ? "&job=" + encodeURIComponent(job) : "");
1769
+ const logs = showsLogs(client, store), onLog = logs && tab === "log";
1770
+ let run, notApplied;
1771
+ try {
1772
+ [run, notApplied] = await Promise.all([api(base + query), onLog ? null : api(base + "/rows" + query)]);
1773
+ } catch (error) {
1774
+ if (logs && error.status === 404) return unrecordedRunScreen(client, store, runId, job, error);
1775
+ throw error;
1776
+ }
1777
+ const crumbs = el("div", { class: "crumbs" },
1778
+ el("a", { href: "#/c/" + encodeURIComponent(client.id) + "/job-runs", text: "Runs" }),
1779
+ " / ", el("a", { href: jobHash(client, run.job), text: run.job }), " / store " + store);
1780
+ const head = el("div", { class: "bhead" }, el("h1", { class: "mono", text: run.run_id }),
1781
+ pill(run.status, RUN_STATUS[run.status]),
1782
+ el("span", { class: "meta" }, run.job + " · started " + run.started_at.replace("T", " ").replace("Z", " UTC") + " · " +
1783
+ duration(run.duration_ms) + " ", logsLink(run.run_id, null)),
1784
+ refreshButton(() => jobRunScreen(client, store, runId, job, tab)));
1785
+ const tabs = logs ? runTabs(client, store, run, tab) : null;
1786
+ if (onLog) {
1787
+ const part = run.log ? runLogPanel(client, store, run.run_id, run.job) : null;
1788
+ main(crumbs, head, tabs, part ? part.node : panel("Log", null, el("div", { class: "empty", text: NO_LOG })));
1789
+ if (part) await part.load();
1790
+ return;
1791
+ }
1792
+ const t = run.totals;
1793
+ const kv = el("dl", { class: "kv" });
1794
+ const add = (k, v) => { if (v !== undefined && v !== null && v !== "") kv.append(el("dt", {}, wrapAt(k)), el("dd", {}, wrapAt(v))); };
1795
+ add("store", run.store); add("started", run.started_at.replace("T", " ").replace("Z", " UTC"));
1796
+ add("finished", run.finished_at.replace("T", " ").replace("Z", " UTC")); add("duration", duration(run.duration_ms));
1797
+ if (run.passes !== null) add("passes", number(run.passes) + (run.failed_passes ? ", " + number(run.failed_passes) + " failed or not run" : ""));
1798
+ add("ran on", run.owner_id);
1799
+ const before = run.failures.filter(f => !f.job_ids.length && f.status !== "busy");
1800
+ const busy = run.failures.filter(f => f.status === "busy");
1801
+ const batches = runBatches(client, store, run), redraw = () => jobRunScreen(client, store, runId, job, tab);
1802
+ main(crumbs, head, tabs,
1803
+ cardsOf([[number(t.batches), "Batches"], [number(t.statuses.failed || 0), "Failed batches", t.statuses.failed ? "fail" : ""],
1804
+ [number(t.rows_written), "Rows written"], [number(t.applied), "Rows applied", "ok"],
1805
+ [number(t.rejected), "Rows rejected", t.rejected ? "rej" : ""], [number(t.in_flight + t.pending), "Rows held", t.in_flight ? "held" : ""],
1806
+ [number(run.unbatched_failures), "Failed before a batch", run.unbatched_failures ? "fail" : ""]]),
1807
+ acknowledged(run.ack, run.ack && canAck(client, store) ? ackActions(client, store, run.job, run.run_id, true, redraw)
1808
+ : null),
1809
+ run.error ? panel("Error", "redacted", el("div", { class: "body issue fail", text: run.error })) : null,
1810
+ before.length ? panel("Failed before a batch", before.length + " · no batch shows these",
1811
+ table(["Item", "Error"], before.map(f => el("tr", {}, el("td", { class: "mono", text: f.item }),
1812
+ el("td", { class: "issue fail", text: f.error_message || "" }))), null, "before")) : null,
1813
+ busy.length ? panel("Busy", busy.length + " · another run held their lease; a later run does them",
1814
+ table(["Item", "Held by"], busy.map(f => el("tr", {}, el("td", { class: "mono", text: f.item }),
1815
+ el("td", { class: "issue", text: f.error_message || "" }))), null, "busy")) : null,
1816
+ el("div", { class: "grid2" }, panel("Run", "times in UTC", el("div", { class: "body" }, kv)),
1817
+ panel("Outputs", "this run's batches", outputsBody(run.outputs))),
1818
+ batches.panel,
1819
+ panel("Rows not applied", notApplied.rows.length + (notApplied.rows.length >= notApplied.limit ? "+" : "") +
1820
+ " · row values are not shown",
1821
+ notApplied.rejections.length ? el("div", { class: "body" }, el("b", { text: "Rejected, by error" }),
1822
+ rejectionsTable(client, store, run.job, notApplied.rejections, "run-rejections")) : null,
1823
+ notAppliedTable(client, store, run.job, notApplied.rows, "run-rows")),
1824
+ fixIt(client, store, run.job, run.run_id, run.ack, run.commands, redraw),
1825
+ panel("From the state CLI", null, el("div", { class: "body" },
1826
+ command("streamwright state runs --url \"$STATE_URL\" --run-id " + run.run_id + " --job " + run.job),
1827
+ command("streamwright state list --url \"$STATE_URL\" --job " + run.job + " --request-id " + run.run_id))));
1828
+ await batches.load();
1829
+ }
1830
+
1831
+ // a job's Summary tab: its runs and batches in a period (the last 15 minutes by default), its outputs and rejected rows
1832
+ function jobSummary(client, job) {
1833
+ const view = viewOf(client, "job:" + job, {});
1834
+ const body = el("div"), notes = el("div");
1835
+ let asked = 0;
1836
+ const load = async () => {
1837
+ const mine = ++asked;
1838
+ const data = await api("/v1/clients/" + encodeURIComponent(client.id) + "/jobs/" + encodeURIComponent(job) +
1839
+ queryString(rangeQuery(view)));
1840
+ if (mine !== asked) return;
1841
+ storeNames(client, data.errors);
1842
+ put(notes, errorsNote(data.errors));
1843
+ const r = data.runs, t = data.totals;
1844
+ put(body,
1845
+ cardsOf([[number(r.statuses.succeeded || 0), "Runs succeeded", "ok"], [number(r.statuses.failed || 0), "Runs failed", r.statuses.failed ? "fail" : ""],
1846
+ [r.success_rate === null ? "–" : r.success_rate + "%", "Success rate"], [r.median_ms === null ? "–" : duration(r.median_ms), "Median run"],
1847
+ [r.p95_ms === null ? "–" : duration(r.p95_ms), "p95 run"], [number(t.rows_written), "Rows written"],
1848
+ [number(t.applied), "Rows applied", "ok"], [number(t.rejected), "Rows rejected", t.rejected ? "rej" : ""],
1849
+ [number(data.scope_counts.failed || 0), "Scopes failing now", data.scope_counts.failed ? "fail" : ""]]),
1850
+ panel("Outputs", "the period's batches", outputsBody(data.outputs)),
1851
+ panel("Rejected, by error", "the period's batches", rejectionsTable(client, null, job, data.rejections, "job-rejections")));
1852
+ };
1853
+ return { node: el("div", {}, el("div", { class: "filters" }, rangeControl(view, load)), notes, body), load };
1854
+ }
1855
+
1856
+ const JOB_TABS = [["summary", "Summary"], ["scopes", "Scopes"], ["runs", "Runs"]];
1857
+
1858
+ // one job, every store's: its Summary, its Scopes (each scope's newest batch) and its Runs, as tabs; the line under its
1859
+ // name gives its stores and its last run, the tabs how many scopes and runs it has (a Store column only for a job in
1860
+ // several stores)
1861
+ async function jobScreen(client, job, tab, scope) {
1862
+ tab = JOB_TABS.some(([key]) => key === tab) ? tab : "summary";
1863
+ const sub = el("div", { class: "sub", text: client.name }), tabs = el("div", { class: "tabs", role: "tablist" });
1864
+ const summary = async () => (await api("/v1/clients/" + encodeURIComponent(client.id) + "/job-summaries" +
1865
+ queryString({ job }))).jobs[0];
1866
+ const show = found => {
1867
+ const run = found && found.last_run;
1868
+ put(sub, client.name + (found ? " · " + (found.stores.length > 1 ? "stores " : "store ") + found.stores.join(", ") : "") +
1869
+ (run ? " · last run " + run.status + " " + ago(run.started_at) : ""));
1870
+ const counts = { scopes: found ? Object.values(found.scopes).reduce((a, b) => a + b, 0) : 0,
1871
+ runs: found ? found.runs.total : 0 };
1872
+ put(tabs, JOB_TABS.map(([key, label]) => el("a", {
1873
+ href: jobHash(client, job, key === "summary" ? null : key), role: "tab", class: key === tab ? "on" : null,
1874
+ "aria-selected": String(key === tab) }, label, key in counts ? el("span", { class: "n", text: number(counts[key]) }) : null)));
1875
+ };
1876
+ const found = await summary();
1877
+ const several = found ? found.stores.length > 1 : client.stores.length > 1;
1878
+ const part = tab === "scopes" ? scopesTab(client, job, scope, several) : tab === "runs" ? runsTable(client, { job, several })
1879
+ : jobSummary(client, job);
1880
+ show(found);
1881
+ main(el("div", { class: "crumbs" }, el("a", { href: "#/c/" + encodeURIComponent(client.id) + "/jobs", text: "Jobs" }), " / " + job),
1882
+ el("div", { class: "titlebar" }, el("h1", { text: job }),
1883
+ refreshButton(() => Promise.all([summary().then(show), part.load()]))),
1884
+ sub, tabs, part.node);
1885
+ await part.load();
1886
+ }
1887
+
1888
+ const LEASE_PILL = { held: "run", expired: "held" };
1889
+ const LEASE_FIELDS = [["job", "Job"], ["token", "Token"], ["holder", "Holder"], ["store", "Store"]];
1890
+
1891
+ function leaseState(lease) { return lease.held ? "held" : "expired"; } // a row lives while it is held
1892
+
1893
+ // a lease's holder; its run's id opens that run's log where the store shows logs
1894
+ function holderOf(client, lease) {
1895
+ if (!lease.holder) return "–";
1896
+ if (!lease.holder_run || !showsLogs(client, lease.store)) return lease.holder;
1897
+ return [el("a", { href: runHash(client, lease.store, lease.holder_run, lease.job, "log"), text: lease.holder_run,
1898
+ title: "its run's log" }), lease.holder.slice(lease.holder_run.length)];
1899
+ }
1900
+
1901
+ async function leasesScreen(client) {
1902
+ const view = viewOf(client, "leases", {});
1903
+ let body = { leases: [], errors: {} };
1904
+ const chips = el("span", { class: "chips" }), notes = el("div"), box = el("div", { class: "panel", id: "leases-table" });
1905
+ const render = () => {
1906
+ const met = body.leases;
1907
+ put(chips, ["all", "held", "expired"].map(state => el("button", {
1908
+ type: "button", class: "chip" + (picked.leases === state ? " on" : ""), "aria-pressed": String(picked.leases === state),
1909
+ text: state + " " + met.filter(lease => state === "all" || leaseState(lease) === state).length,
1910
+ onclick: () => { picked.leases = state; render(); } })));
1911
+ const shown = met.filter(lease => picked.leases === "all" || leaseState(lease) === picked.leases);
1912
+ const rows = shown.map(lease => el("tr", {},
1913
+ el("td", { text: lease.job }), el("td", { class: "mono" }, el("div", { class: "long" }, wrapAt(lease.token || "(job)"))),
1914
+ el("td", { class: "mono" }, holderOf(client, lease)), el("td", { class: "num", text: lease.epoch }),
1915
+ el("td", {}, pill(leaseState(lease), LEASE_PILL[leaseState(lease)])),
1916
+ el("td", {}, when(lease.expires_at)), el("td", { text: lease.store })));
1917
+ put(box, table(
1918
+ ["Job", "Token", "Holder", { text: "Epoch", num: true }, "State", "Expires", "Store"], rows,
1919
+ body.leases.length ? "No lease matches." : view.filters.length ? "No lease matches the filters." : "No lease.",
1920
+ "leases"));
1921
+ };
1922
+ const load = async () => {
1923
+ body = await api("/v1/clients/" + encodeURIComponent(client.id) + "/leases" +
1924
+ queryString({ filter: filterParams(view) }));
1925
+ storeNames(client, body.errors);
1926
+ put(notes, errorsNote(body.errors));
1927
+ render();
1928
+ };
1929
+ const filter = filterButton(view, LEASE_FIELDS, load);
1930
+ main(el("h1", { text: "Leases" }), el("div", { class: "sub", text: client.name + " · who holds which job's lease" }),
1931
+ el("div", { class: "filters" }, chips, filter.button, el("span", { class: "spacer" }), refreshButton(load)),
1932
+ filter.kept, notes, box);
1933
+ await load();
1934
+ }
1935
+
1936
+ // the sidebar's stores after a screen read them: the ones in `errors` failed, the others answered (`known`: false
1937
+ // before anything was read, so their dots stay grey)
1938
+ function storeNames(client, errors, known = true) {
1939
+ renderStores(client.stores.map(name => ({ name, reachable: !(errors || {})[name], error: (errors || {})[name], known })));
1940
+ }
1941
+
1942
+ function renderStores(stores) {
1943
+ const SIDE = { "not-created": ["idle", "not created yet"], "migrations-pending": ["held", "migrations pending"] };
1944
+ put(document.getElementById("side-stores"), stores.map(s => el("div", { class: "store" },
1945
+ dot(s.reachable ? (s.known === false ? "idle" : "ok") : (SIDE[s.error] || ["fail"])[0]),
1946
+ el("span", { class: "name", text: s.name, title: s.name }),
1947
+ s.reachable ? null : el("small", { text: (SIDE[s.error] || [null, s.error])[1] }))));
1948
+ }
1949
+
1950
+ // --- routing -----------------------------------------------------------------------------------------------
1951
+
1952
+ async function route() {
1953
+ const match = location.hash.match(/^#\/c\/([^/]+)\/([a-z-]+)(?:\/([^/?]+))?(?:\/([^?]+))?(?:\?(job|status|scope)=(.*))?$/);
1954
+ if (!match) {
1955
+ if (state.clients.length) {
1956
+ const first = recent().find(id => state.clients.some(c => c.id === id)) || state.clients[0].id;
1957
+ location.hash = "#/c/" + encodeURIComponent(first) + "/overview";
1958
+ } else main(el("div", { class: "empty", text: "No client is listed for you." }));
1959
+ return;
1960
+ }
1961
+ const [, id, view, store, jobId, param, value] = match;
1962
+ const job = param === "job" ? value : null;
1963
+ const client = state.clients.find(c => c.id === decodeURIComponent(id));
1964
+ if (!client) { main(el("div", { class: "empty err", text: "No such client." })); return; }
1965
+ if (!state.client || state.client.id !== client.id) {
1966
+ state.client = client;
1967
+ localStorage.setItem(RECENT, JSON.stringify([client.id, ...recent().filter(r => r !== client.id)].slice(0, 5)));
1968
+ document.getElementById("picker-name").textContent = client.name;
1969
+ document.getElementById("picker-stores").textContent = client.stores.join(" · ");
1970
+ document.getElementById("side-stores").replaceChildren();
1971
+ storeNames(client, {}, false);
1972
+ }
1973
+ document.querySelectorAll("[data-nav]").forEach(a => {
1974
+ a.classList.toggle("active", a.dataset.nav === ({ batch: "jobs", job: "jobs", "job-run": "job-runs" }[view] || view));
1975
+ a.href = "#/c/" + encodeURIComponent(client.id) + "/" + a.dataset.nav;
1976
+ });
1977
+ loading();
1978
+ try {
1979
+ if (view === "overview") await overviewScreen(client);
1980
+ else if (view === "jobs") await jobsScreen(client);
1981
+ else if (view === "batch") await batchScreen(client, decodeURIComponent(store), decodeURIComponent(jobId),
1982
+ job ? decodeURIComponent(job) : null);
1983
+ else if (view === "job-runs") await jobRunsScreen(client, param === "status" ? decodeURIComponent(value) : null,
1984
+ job ? decodeURIComponent(job) : null);
1985
+ else if (view === "job" && store) await jobScreen(client, decodeURIComponent(store), jobId || null,
1986
+ param === "scope" ? decodeURIComponent(value) : null);
1987
+ else if (view === "job-run") {
1988
+ const [run, tab] = (jobId || "").split("/"); // <run id>/log: its Log tab
1989
+ await jobRunScreen(client, decodeURIComponent(store), decodeURIComponent(run), job ? decodeURIComponent(job) : null,
1990
+ tab === "log" ? "log" : null);
1991
+ }
1992
+ else if (view === "runs") await runsScreen(client);
1993
+ else if (view === "leases") await leasesScreen(client);
1994
+ else main(el("div", { class: "empty err", text: "No such page." }));
1995
+ } catch (error) { if (error.message !== "unauthorized") failed(error); }
1996
+ }
1997
+
1998
+ async function start() {
1999
+ try {
2000
+ state.config = await api("/v1/config");
2001
+ document.getElementById("signout").classList.toggle("hidden", !state.config.auth); // no auth: nobody signs in
2002
+ if (await returning()) return;
2003
+ if (state.config.auth && !sessionStorage.getItem(TOKEN)) { showLogin(""); return; }
2004
+ const [listed, me] = await Promise.all([api("/v1/clients"), api("/v1/me")]); // signed in: the logs link too
2005
+ state.clients = listed.clients;
2006
+ state.config.logs_link = listed.logs_link;
2007
+ state.me = me;
2008
+ showWho(me);
2009
+ route();
2010
+ } catch (error) { if (error.message !== "unauthorized") failed(error); }
2011
+ }
2012
+
2013
+ window.addEventListener("hashchange", route);
2014
+ start();