@intentius/behold 0.29.27 → 0.29.29

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intentius/behold",
3
- "version": "0.29.27",
3
+ "version": "0.29.29",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "description": "behold — a live control plane on chant. See your whole estate (every substrate in one graph), coloured by drift; act through delegated, gated Ops.",
package/web/kiosk-runs.js CHANGED
@@ -14,6 +14,7 @@ import { rootColour, rootPaint, rootSegments, rootText, rootsOfWave, waveOfJob }
14
14
  import { TOUR, chipWords, docsUrl, jobMarks, runFeatures } from "./kiosk-annotations.js";
15
15
  import { iconSvg } from "./forge-mark.js";
16
16
  import { TOOLS, jobTools } from "./tool-mark.js";
17
+ import { traceSource, traceStyle } from "./kiosk-trace.js";
17
18
 
18
19
  /** The run, job and step statuses, as a viewer reads them. */
19
20
  export const STATUS_WORDS = {
@@ -497,7 +498,7 @@ export function toolMarks(job, repoTools = [], { light = false, hideLine = null,
497
498
  return box;
498
499
  }
499
500
 
500
- export function renderRun(host, answer, ui, { now = new Date(), pickJob = () => {}, toggleStep = () => {}, toggleSetup = () => {}, jump = () => {}, toggleFeats = () => {}, featsOpen = false, note = null, flash = null, entry = null, roots = [], waves = [], tools = [], rootTools = {}, light = false, hideLine = null } = {}) {
501
+ export function renderRun(host, answer, ui, { now = new Date(), pickJob = () => {}, toggleStep = () => {}, toggleSetup = () => {}, jump = () => {}, toggleFeats = () => {}, featsOpen = false, note = null, flash = null, entry = null, roots = [], waves = [], tools = [], rootTools = {}, light = false, hideLine = null, trace = null, jobView = "steps", pickView = () => {} } = {}) {
501
502
  // behold#571: a root's name with its colour's dot, where the line names one.
502
503
  const textOf = (cls, text) => {
503
504
  if (!roots.length || !rootSegments(text, roots).some((x) => x.root)) return el("span", cls, text);
@@ -596,7 +597,24 @@ export function renderRun(host, answer, ui, { now = new Date(), pickJob = () =>
596
597
  }
597
598
 
598
599
  if (!job) return { log: null, steps: null, key: null };
599
- host.appendChild(el("div", "r-label", "Steps of the job, with its log"));
600
+ // behold#571: a job with a trace in Tempo offers it beside its steps (web/kiosk-trace.js).
601
+ if (trace && trace.has(job.name)) {
602
+ const tabs = el("div", "t-tabs");
603
+ for (const [view, words] of [["steps", "Steps of the job, with its log"], ["trace", "Trace"]]) {
604
+ const b = el("button", "t-tab", words);
605
+ b.type = "button";
606
+ b.setAttribute("aria-pressed", String((jobView === "trace") === (view === "trace")));
607
+ b.addEventListener("click", () => pickView(view));
608
+ tabs.appendChild(b);
609
+ }
610
+ host.appendChild(tabs);
611
+ if (jobView === "trace") {
612
+ const box = el("div", "r-steps r-trace");
613
+ trace.draw(box, job.name);
614
+ host.appendChild(box);
615
+ return { log: null, steps: box, key: null };
616
+ }
617
+ } else host.appendChild(el("div", "r-label", "Steps of the job, with its log"));
600
618
  const stepsBox = el("div", "r-steps");
601
619
  const sh = el("div", "r-steps-head");
602
620
  sh.append(statusIcon(job.status), el("span", "r-steps-job", job.name), el("span", "r-steps-word", job.status === "waiting" ? "waits for an approval at the gate" : STATUS_WORDS[job.status] || job.status));
@@ -798,6 +816,10 @@ export function startRuns(
798
816
  // The open log and whether the pane follows its end; a viewer who scrolls up stops it until they come back.
799
817
  let logShown = null;
800
818
  let logFollow = true;
819
+ // behold#571: the job pane's view, its steps or its trace, kept as a viewer moves between jobs.
820
+ let jobView = "steps";
821
+ const traces = traceSource({ fetchJson, onChange: () => draw() });
822
+ if (typeof document !== "undefined") traceStyle(document);
801
823
  const following = () => follow || now().getTime() - s.picked > PICK_HOLD_MS;
802
824
  const selectedId = () => {
803
825
  const runs = s.index && s.index.doc ? s.index.doc.runs : [];
@@ -845,6 +867,13 @@ export function startRuns(
845
867
  rootTools: rootTools(),
846
868
  light: light(),
847
869
  hideLine,
870
+ trace: traceFor(ans),
871
+ jobView,
872
+ pickView: (view) => {
873
+ jobView = view;
874
+ hold();
875
+ draw();
876
+ },
848
877
  note: s.note,
849
878
  flash: s.flash ? s.flash.key : null,
850
879
  featsOpen: s.featsOpen,
@@ -992,6 +1021,25 @@ export function startRuns(
992
1021
  }
993
1022
  });
994
1023
  }
1024
+ /** The selected run's traces, by the repo and run id its document names. */
1025
+ const traceFor = (ans) => {
1026
+ const doc = ans && ans.doc;
1027
+ if (!doc || !doc.repo) return null;
1028
+ return {
1029
+ has: (job) => traces.has(doc.repo, doc.id, job),
1030
+ draw: (box, job) =>
1031
+ traces.draw(box, {
1032
+ repo: doc.repo,
1033
+ run: doc.id,
1034
+ job,
1035
+ pickJob: (name) => {
1036
+ s.ui = { job: name, open: null, setup: null };
1037
+ hold();
1038
+ draw();
1039
+ },
1040
+ }),
1041
+ };
1042
+ };
995
1043
  const hold = () => {
996
1044
  follow = false;
997
1045
  s.selected = selectedId() ?? s.selected;
@@ -0,0 +1,392 @@
1
+ // behold#571: a job's trace as a waterfall, from Tempo through /api/traces
2
+ // (src/tempo-traces.ts). The run's jobs on one time line, then the selected
3
+ // job: terragucci's stage, its phases (plan, gate, apply, report, upload),
4
+ // each root's init, plan and apply, and OpenTofu's own spans under them.
5
+ //
6
+ // It shows what Tempo holds and nothing else: a job with no trace has no
7
+ // Trace view. Deep levels start folded; a click on a row opens or folds it.
8
+ // The spans that make up the job's critical path are lit, and so is a wait:
9
+ // the gate, or a state lock.
10
+ //
11
+ // Two ways in, both GET only:
12
+ // - `traceSource({ fetchJson })`: the kiosk's job pane asks it, on every
13
+ // redraw, whether a job has a trace (`has`) and draws it (`draw`). It reads
14
+ // a run once per TRACE_POLL_MS and calls `onChange` when an answer lands.
15
+ // - `mountTrace(host, { project, run, job })`: the same waterfall as a
16
+ // component of its own, for any layout that wants one job's trace.
17
+
18
+ /** How often a run's traces are asked for again. The route shares one read of Tempo for 10 s. */
19
+ export const TRACE_POLL_MS = 15_000;
20
+ /** Rows deeper than this start folded: the stage, its phases and the roots show; the binary's spans wait for a click. */
21
+ export const OPEN_DEPTH = 3;
22
+ /** Two spans closer than this, in ms, count as touching on the critical path. */
23
+ const EPS = 0.5;
24
+
25
+ /** The URL a run's traces are read at, or null when the run cannot be named. */
26
+ export function traceUrl({ repo, run, commit = null }) {
27
+ if (!repo || typeof repo !== "string") return null;
28
+ const q = new URLSearchParams({ project: repo });
29
+ if (run !== null && run !== undefined && /^[1-9][0-9]{0,15}$/.test(String(run))) q.set("run", String(run));
30
+ else if (commit && /^[0-9a-f]{7,64}$/.test(commit)) q.set("commit", commit);
31
+ else return null;
32
+ return `/api/traces?${q}`;
33
+ }
34
+
35
+ /** "70 ms", "6.4 s", "48 s", "2 min 5 s". */
36
+ export function msWords(ms) {
37
+ if (typeof ms !== "number" || !Number.isFinite(ms) || ms < 0) return "";
38
+ if (ms < 1) return "<1 ms";
39
+ if (ms < 1000) return `${Math.round(ms)} ms`;
40
+ const s = ms / 1000;
41
+ if (s < 10) return `${Math.round(s * 10) / 10} s`;
42
+ if (s < 60) return `${Math.round(s)} s`;
43
+ const m = Math.floor(s / 60);
44
+ const r = Math.round(s - m * 60);
45
+ if (m < 60) return r ? `${m} min ${r} s` : `${m} min`;
46
+ const h = Math.floor(m / 60);
47
+ return m % 60 ? `${h} h ${m % 60} min` : `${h} h`;
48
+ }
49
+
50
+ const end = (s) => s.start + s.ms;
51
+
52
+ /** The spans as a tree: each one's children, earliest first, and the tops (spans whose parent is not in the trace). */
53
+ export function spanTree(spans) {
54
+ const ids = new Set(spans.map((s) => s.id));
55
+ const kids = new Map();
56
+ const tops = [];
57
+ for (const s of [...spans].sort((a, b) => a.start - b.start)) {
58
+ if (s.parent && ids.has(s.parent)) {
59
+ if (!kids.has(s.parent)) kids.set(s.parent, []);
60
+ kids.get(s.parent).push(s);
61
+ } else tops.push(s);
62
+ }
63
+ return { kids, tops };
64
+ }
65
+
66
+ /**
67
+ * The job's critical path: from the end of each top span back to its start,
68
+ * the child that ended last before that point, then the one that ended last
69
+ * before it began, and so on down each. A sibling still running when the
70
+ * chosen one began, such as a root that planned beside it and finished
71
+ * sooner, stays off it.
72
+ */
73
+ export function criticalPath(spans) {
74
+ const { kids, tops } = spanTree(spans);
75
+ const on = new Set();
76
+ const walk = (s, bound) => {
77
+ on.add(s.id);
78
+ let t = Math.min(end(s), bound);
79
+ const children = [...(kids.get(s.id) || [])].sort((a, b) => end(b) - end(a));
80
+ for (const c of children) {
81
+ // A child still running at the point, or starting after it, is not what the point waited on.
82
+ if (c.start >= t - EPS || end(c) > t + EPS) continue;
83
+ walk(c, t);
84
+ t = c.start;
85
+ }
86
+ };
87
+ for (const s of tops) walk(s, Infinity);
88
+ return on;
89
+ }
90
+
91
+ /** Whether a span is a wait: the wave's gate, or a state lock. */
92
+ export function isWait(s) {
93
+ return s.attrs["terragucci.phase"] === "gate" || s.name === "State lock wait";
94
+ }
95
+
96
+ /** A span's label and the words after it. */
97
+ export function spanWords(s) {
98
+ const a = s.attrs || {};
99
+ if (a["terragucci.stage"]) {
100
+ const wave = a["terragucci.wave"];
101
+ return { label: `${a["terragucci.stage"]}${wave ? `, wave ${wave}` : ""}`, sub: a["terragucci.result"] ? String(a["terragucci.result"]) : "" };
102
+ }
103
+ if (a["terragucci.phase"] === "gate") {
104
+ const held = a["terragucci.gate.held_seconds"];
105
+ const status = a["terragucci.gate.status"];
106
+ const sub = typeof held === "number" ? `approved after ${msWords(held * 1000)} held` : status === "not-required" ? "no approval needed" : status === "waiting" ? "waits for an approval" : status ? String(status) : "";
107
+ return { label: "gate", sub };
108
+ }
109
+ if (a["terragucci.phase"]) return { label: String(a["terragucci.phase"]), sub: "" };
110
+ if (a["terragucci.root"] && s.name.startsWith("root ")) return { label: s.name, sub: a["terragucci.status"] ? String(a["terragucci.status"]) : "" };
111
+ const address = a["opentofu.resource_instance.address"] || a["opentofu.resource.address"];
112
+ if (address) {
113
+ const verb = /^(Plan|Apply|Refresh|Validate|Read)\b/.exec(s.name);
114
+ return { label: String(address), sub: verb ? verb[1].toLowerCase() : s.name };
115
+ }
116
+ if (s.name === "Configure provider" && a["opentofu.provider.source"]) return { label: "Configure provider", sub: String(a["opentofu.provider.source"]).replace(/^registry\.(opentofu|terraform)\.(org|io)\//, "") };
117
+ if (s.name === "tofu" && s.service !== "terragucci") return { label: "OpenTofu", sub: "" };
118
+ if (a["rpc.method"]) return { label: String(a["rpc.method"]), sub: a["opentofu.provider.address"] ? String(a["opentofu.provider.address"]) : "" };
119
+ return { label: s.name, sub: "" };
120
+ }
121
+
122
+ /**
123
+ * The rows a trace draws, top to bottom: each visible span with its depth,
124
+ * its place on the job's time line (0..1), and whether it is on the critical
125
+ * path, a wait or failed. `open` is the set of span ids a viewer opened past
126
+ * OPEN_DEPTH, `shut` the ones they folded above it.
127
+ */
128
+ export function waterfallRows(trace, { open = new Set(), shut = new Set() } = {}) {
129
+ const spans = trace.spans || [];
130
+ if (!spans.length) return [];
131
+ const { kids, tops } = spanTree(spans);
132
+ const crit = criticalPath(spans);
133
+ const t0 = Math.min(...spans.map((s) => s.start));
134
+ const span = Math.max(1e-6, Math.max(...spans.map(end)) - t0);
135
+ const rows = [];
136
+ const visit = (s, depth) => {
137
+ const children = kids.get(s.id) || [];
138
+ const isOpen = children.length > 0 && (depth < OPEN_DEPTH ? !shut.has(s.id) : open.has(s.id));
139
+ const words = spanWords(s);
140
+ rows.push({
141
+ id: s.id,
142
+ depth,
143
+ label: words.label,
144
+ sub: words.sub,
145
+ service: s.service,
146
+ ms: s.ms,
147
+ at: (s.start - t0) / span,
148
+ width: s.ms / span,
149
+ critical: crit.has(s.id),
150
+ wait: isWait(s),
151
+ error: s.error || null,
152
+ kids: children.length,
153
+ open: isOpen,
154
+ });
155
+ if (isOpen) for (const c of children) visit(c, depth + 1);
156
+ };
157
+ for (const s of tops) visit(s, 0);
158
+ return rows;
159
+ }
160
+
161
+ /** The run's jobs on one time line: each job's newest trace, 0..1 across the run. */
162
+ export function runStrip(traces) {
163
+ const newest = new Map();
164
+ for (const t of traces) if (t.job && (!newest.has(t.job) || newest.get(t.job).start < t.start)) newest.set(t.job, t);
165
+ const list = [...newest.values()].sort((a, b) => a.start - b.start);
166
+ if (!list.length) return [];
167
+ const t0 = Math.min(...list.map((t) => t.start));
168
+ const span = Math.max(1e-6, Math.max(...list.map((t) => t.start + t.ms)) - t0);
169
+ return list.map((t) => ({ job: t.job, wave: t.wave, result: t.result, ms: t.ms, at: (t.start - t0) / span, width: t.ms / span }));
170
+ }
171
+
172
+ const STYLE = `
173
+ .t-trace { padding: 0.2em 0 0.6em; font-size: 0.86em; }
174
+ .t-tabs { display: flex; gap: 0.3em; padding: 0.5em 1em 0.1em; flex-wrap: wrap; }
175
+ .t-tab { font: 600 0.78em var(--font-mono); text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted); background: transparent; border: 1px solid var(--rule); border-radius: 999px; padding: 0.2em 0.8em; cursor: pointer; }
176
+ .t-tab[aria-pressed="true"] { color: var(--fg); background: var(--active); border-color: var(--focus); }
177
+ .t-sec { font: 600 0.8em var(--font-mono); text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted); padding: 0.6em 1em 0.25em; }
178
+ .t-strip, .t-rows { display: flex; flex-direction: column; }
179
+ .t-row { display: grid; grid-template-columns: minmax(10em, 38%) minmax(0, 1fr) 4.6em; align-items: center; gap: 0.6em; padding: 0.08em 1em; min-height: 1.55em; cursor: default; }
180
+ .t-row:nth-child(odd) { background: var(--zebra-row); }
181
+ .t-row.t-can { cursor: pointer; }
182
+ .t-row.t-can:hover, .t-row.t-sel { background: var(--active); }
183
+ .t-name { display: flex; gap: 0.35em; align-items: baseline; min-width: 0; padding-left: calc(var(--d, 0) * 0.85em); }
184
+ .t-caret { color: var(--muted); width: 0.8em; flex: none; font-size: 0.85em; }
185
+ .t-label { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-family: var(--font-mono); }
186
+ .t-sub { color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-size: 0.9em; }
187
+ .t-track { position: relative; height: 0.8em; border-radius: 3px; background: color-mix(in srgb, var(--rule) 45%, transparent); }
188
+ .t-bar { position: absolute; top: 0; bottom: 0; min-width: 2px; border-radius: 3px; background: color-mix(in srgb, var(--muted) 75%, transparent); }
189
+ .t-bin .t-bar { background: color-mix(in srgb, var(--managed) 70%, transparent); }
190
+ .t-crit .t-bar { background: var(--runtime); box-shadow: 0 0 0 1px color-mix(in srgb, var(--runtime) 55%, transparent); }
191
+ .t-wait .t-bar { background: repeating-linear-gradient(135deg, var(--foreign) 0 4px, color-mix(in srgb, var(--foreign) 45%, transparent) 4px 8px); }
192
+ .t-err .t-bar { background: var(--degraded); }
193
+ .t-ms { color: var(--muted); text-align: right; font: 0.9em var(--font-mono); white-space: nowrap; }
194
+ .t-crit .t-ms, .t-wait .t-ms { color: var(--fg); }
195
+ .t-key { display: flex; flex-wrap: wrap; gap: 0.3em 1.1em; padding: 0.5em 1em 0; color: var(--muted); font-size: 0.85em; }
196
+ .t-key span { display: inline-flex; align-items: center; gap: 0.35em; }
197
+ .t-sw { display: inline-block; width: 1.4em; height: 0.6em; border-radius: 2px; }
198
+ .t-sw.t-c { background: var(--runtime); }
199
+ .t-sw.t-w { background: repeating-linear-gradient(135deg, var(--foreign) 0 4px, color-mix(in srgb, var(--foreign) 45%, transparent) 4px 8px); }
200
+ .t-sw.t-b { background: color-mix(in srgb, var(--managed) 70%, transparent); }
201
+ .t-note { color: var(--muted); padding: 0.3em 1em; font-size: 0.9em; }
202
+ @media (max-width: 600px) {
203
+ .t-row { grid-template-columns: minmax(0, 1fr) 4.2em; grid-template-areas: "name ms" "track track"; row-gap: 0.15em; padding: 0.25em 0.8em; }
204
+ .t-name { grid-area: name; }
205
+ .t-ms { grid-area: ms; }
206
+ .t-track { grid-area: track; margin-left: calc(var(--d, 0) * 0.85em); }
207
+ }
208
+ `;
209
+
210
+ const el = (doc, tag, cls, text) => {
211
+ const n = doc.createElement(tag);
212
+ if (cls) n.className = cls;
213
+ if (text !== undefined && text !== null) n.textContent = text;
214
+ return n;
215
+ };
216
+
217
+ /** Put the waterfall's style on the page once. */
218
+ export function traceStyle(doc = document) {
219
+ if (!doc.head || doc.getElementById("t-trace-style")) return;
220
+ const style = el(doc, "style");
221
+ style.id = "t-trace-style";
222
+ style.textContent = STYLE;
223
+ doc.head.appendChild(style);
224
+ }
225
+
226
+ function bar(doc, at, width) {
227
+ const track = el(doc, "div", "t-track");
228
+ const b = el(doc, "div", "t-bar");
229
+ b.style.left = `${Math.min(100, Math.max(0, at * 100))}%`;
230
+ b.style.width = `${Math.min(100 - at * 100, Math.max(0, width * 100))}%`;
231
+ track.appendChild(b);
232
+ return track;
233
+ }
234
+
235
+ /**
236
+ * Draw one job's trace into `host`: the run's jobs on a strip (when `run`
237
+ * holds more than this job), the job's waterfall, and its key. `ui` holds
238
+ * the viewer's folds (`open`, `shut`, sets of span ids) and calls `toggle(id)`
239
+ * and `pickJob(name)`.
240
+ */
241
+ export function renderTrace(host, { traces, run = [], job }, { doc = document, toggle = () => {}, pickJob = null, open = new Set(), shut = new Set() } = {}) {
242
+ traceStyle(doc);
243
+ const box = el(doc, "div", "t-trace");
244
+ const strip = runStrip(run);
245
+ if (strip.length > 1) {
246
+ box.appendChild(el(doc, "div", "t-sec", "The run's jobs"));
247
+ const rows = el(doc, "div", "t-strip");
248
+ for (const r of strip) {
249
+ const row = el(doc, "div", `t-row${pickJob ? " t-can" : ""}${r.job === job ? " t-sel" : ""}${r.result === "failed" ? " t-err" : r.result === "waiting" ? " t-wait" : ""}`);
250
+ const name = el(doc, "div", "t-name");
251
+ name.append(el(doc, "span", "t-label", r.job), el(doc, "span", "t-sub", r.result || ""));
252
+ row.append(name, bar(doc, r.at, r.width), el(doc, "div", "t-ms", msWords(r.ms)));
253
+ if (pickJob) row.addEventListener("click", () => pickJob(r.job));
254
+ rows.appendChild(row);
255
+ }
256
+ box.appendChild(rows);
257
+ }
258
+ traces.forEach((t, i) => {
259
+ const when = new Date(t.start);
260
+ const head = traces.length > 1 ? `Attempt ${i + 1} of ${traces.length}, ${when.toISOString().slice(11, 19)} UTC` : `This job, ${msWords(t.ms)}`;
261
+ box.appendChild(el(doc, "div", "t-sec", head));
262
+ const rows = el(doc, "div", "t-rows");
263
+ for (const r of waterfallRows(t, { open, shut })) {
264
+ const cls = ["t-row", r.kids ? "t-can" : "", r.service !== "terragucci" ? "t-bin" : "", r.critical ? "t-crit" : "", r.wait ? "t-wait" : "", r.error ? "t-err" : ""].filter(Boolean).join(" ");
265
+ const row = el(doc, "div", cls);
266
+ row.style.setProperty("--d", String(r.depth));
267
+ const name = el(doc, "div", "t-name");
268
+ name.append(el(doc, "span", "t-caret", r.kids ? (r.open ? "▾" : "▸") : ""), el(doc, "span", "t-label", r.label));
269
+ if (r.sub) name.appendChild(el(doc, "span", "t-sub", r.sub));
270
+ row.title = [r.label, r.sub, msWords(r.ms), r.critical ? "on the critical path" : "", r.error ? `error: ${r.error}` : "", r.kids && !r.open ? `${r.kids} spans inside` : ""].filter(Boolean).join(" · ");
271
+ row.append(name, bar(doc, r.at, r.width), el(doc, "div", "t-ms", msWords(r.ms)));
272
+ if (r.kids) row.addEventListener("click", () => toggle(r.id, r.depth));
273
+ rows.appendChild(row);
274
+ }
275
+ box.appendChild(rows);
276
+ if (t.left_out) box.appendChild(el(doc, "div", "t-note", `${t.left_out} of the deepest spans stay in Tempo; this view keeps the run's shape.`));
277
+ });
278
+ const key = el(doc, "div", "t-key");
279
+ const sw = (c, words) => {
280
+ const k = el(doc, "span");
281
+ k.append(el(doc, "i", `t-sw ${c}`), words);
282
+ return k;
283
+ };
284
+ key.append(sw("t-c", "critical path"), sw("t-w", "a wait at the gate or for a state lock"), sw("t-b", "OpenTofu's own spans"));
285
+ box.appendChild(key);
286
+ host.appendChild(box);
287
+ return box;
288
+ }
289
+
290
+ /** The viewer's folds: a click on a row opens it or folds it, whatever its depth. */
291
+ export function foldState() {
292
+ const open = new Set();
293
+ const shut = new Set();
294
+ return {
295
+ open,
296
+ shut,
297
+ toggle(id, depth) {
298
+ if (depth < OPEN_DEPTH) {
299
+ if (shut.has(id)) shut.delete(id);
300
+ else shut.add(id);
301
+ } else if (open.has(id)) open.delete(id);
302
+ else open.add(id);
303
+ },
304
+ };
305
+ }
306
+
307
+ /**
308
+ * The kiosk's reader of runs' traces. `has(repo, run, job)` and
309
+ * `traces(repo, run, job)` answer from what it read, and ask again when the
310
+ * run's answer is older than TRACE_POLL_MS; `onChange` runs when an answer
311
+ * lands. One answer per run, shared by its jobs.
312
+ */
313
+ export function traceSource({ fetchJson, onChange = () => {}, now = () => Date.now() }) {
314
+ const runs = new Map();
315
+ const folds = foldState();
316
+ const read = (repo, run) => {
317
+ const url = traceUrl({ repo, run });
318
+ if (!url) return null;
319
+ let r = runs.get(url);
320
+ const t = now();
321
+ if (!r || (!r.pending && t - r.at >= TRACE_POLL_MS)) {
322
+ r = r || { at: t, answer: null, pending: null };
323
+ r.at = t;
324
+ r.pending = Promise.resolve(fetchJson(url)).then(
325
+ (a) => {
326
+ r.pending = null;
327
+ const before = JSON.stringify(r.answer && r.answer.jobs);
328
+ const ok = a && !a.error && Array.isArray(a.traces);
329
+ if (ok) r.answer = a;
330
+ if (ok && (before !== JSON.stringify(a.jobs) || (r.answer && r.answer.traces.length))) onChange();
331
+ },
332
+ () => {
333
+ r.pending = null;
334
+ },
335
+ );
336
+ runs.set(url, r);
337
+ // Old runs age off.
338
+ for (const [k, v] of runs) if (t - v.at > 10 * TRACE_POLL_MS) runs.delete(k);
339
+ }
340
+ return r.answer;
341
+ };
342
+ const of = (repo, run, job) => {
343
+ const a = read(repo, run);
344
+ return a ? a.traces.filter((t) => t.job === job) : [];
345
+ };
346
+ return {
347
+ folds,
348
+ has: (repo, run, job) => of(repo, run, job).length > 0,
349
+ traces: of,
350
+ all: (repo, run) => (read(repo, run) || { traces: [] }).traces,
351
+ draw(host, { repo, run, job, pickJob = null, doc = document }) {
352
+ return renderTrace(host, { traces: of(repo, run, job), run: this.all(repo, run), job }, { doc, pickJob, open: folds.open, shut: folds.shut, toggle: (id, depth) => { folds.toggle(id, depth); onChange(); } });
353
+ },
354
+ };
355
+ }
356
+
357
+ /**
358
+ * One job's waterfall as a component: it reads the run's traces, draws the
359
+ * job's, and keeps the viewer's folds across its own redraws. `update` points
360
+ * it at another job; `stop` ends its reads. With no trace for the job it
361
+ * draws nothing.
362
+ */
363
+ export function mountTrace(host, { project, run, job, fetchJson = defaultFetch, doc = document, setTimer = setInterval, clearTimer = clearInterval, pickJob = null } = {}) {
364
+ let target = { project, run, job };
365
+ const draw = () => {
366
+ host.replaceChildren();
367
+ if (!source.has(target.project, target.run, target.job)) return;
368
+ source.draw(host, { repo: target.project, run: target.run, job: target.job, pickJob, doc });
369
+ };
370
+ const source = traceSource({ fetchJson, onChange: draw });
371
+ draw();
372
+ const timer = setTimer(draw, TRACE_POLL_MS);
373
+ return {
374
+ update(next) {
375
+ target = { ...target, ...next };
376
+ draw();
377
+ },
378
+ stop() {
379
+ clearTimer(timer);
380
+ },
381
+ };
382
+ }
383
+
384
+ async function defaultFetch(url) {
385
+ try {
386
+ const r = await fetch(url, { headers: { accept: "application/json" } });
387
+ if (!r.ok) return { error: `${url} answered ${r.status}` };
388
+ return await r.json();
389
+ } catch (e) {
390
+ return { error: String(e) };
391
+ }
392
+ }
@@ -0,0 +1,129 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { OPEN_DEPTH, TRACE_POLL_MS, criticalPath, foldState, msWords, runStrip, spanWords, traceSource, traceUrl, waterfallRows } from "./kiosk-trace.js";
3
+
4
+ const T = 1_792_166_000_000;
5
+ const sp = (id, parent, name, from, to, attrs = {}, service = "terragucci") => ({ id, parent, name, service, start: T + from, ms: to - from, attrs });
6
+
7
+ /** A wave's job: two roots planning at once (b ends last), a gate held, then the applies one after the other. */
8
+ const SPANS = [
9
+ sp("s", null, "terragucci tf-apply", 0, 1000, { "terragucci.stage": "tf-apply", "terragucci.wave": 1, "terragucci.result": "applied" }),
10
+ sp("p", "s", "plan", 100, 400, { "terragucci.phase": "plan" }),
11
+ sp("ra", "p", "root a", 110, 300, { "terragucci.root": "a" }),
12
+ sp("rb", "p", "root b", 110, 390, { "terragucci.root": "b" }),
13
+ sp("pb", "rb", "tofu plan", 120, 380),
14
+ sp("ob", "pb", "tofu", 130, 370, {}, "OpenTofu CLI"),
15
+ sp("rib", "ob", "Plan resource instance changes", 200, 300, { "opentofu.resource_instance.address": "terraform_data.release" }, "OpenTofu CLI"),
16
+ sp("g", "s", "gate", 400, 800, { "terragucci.phase": "gate", "terragucci.gate.status": "approved", "terragucci.gate.held_seconds": 40 }),
17
+ sp("a", "s", "apply", 800, 950, { "terragucci.phase": "apply" }),
18
+ sp("aa", "a", "root a", 800, 860, { "terragucci.root": "a" }),
19
+ sp("ab", "a", "root b", 860, 950, { "terragucci.root": "b" }),
20
+ ];
21
+
22
+ describe("the trace view's reads", () => {
23
+ it("names a run by its repo and id, or by a commit, and nothing else", () => {
24
+ expect(traceUrl({ repo: "terragucci-admin/demo", run: 4184 })).toBe("/api/traces?project=terragucci-admin%2Fdemo&run=4184");
25
+ expect(traceUrl({ repo: "terragucci-admin/demo", run: null, commit: "abc1234" })).toBe("/api/traces?project=terragucci-admin%2Fdemo&commit=abc1234");
26
+ expect(traceUrl({ repo: null, run: 4184 })).toBeNull();
27
+ expect(traceUrl({ repo: "terragucci-admin/demo", run: "1 or 2" })).toBeNull();
28
+ });
29
+
30
+ it("reads a run once per poll, shared by its jobs, and says when it lands", async () => {
31
+ let t = 0;
32
+ const asked = [];
33
+ let changed = 0;
34
+ const answer = { traces: [{ job: "apply-wave-1", start: T, ms: 1000, spans: SPANS }], jobs: ["apply-wave-1"] };
35
+ const src = traceSource({ fetchJson: async (u) => (asked.push(u), answer), onChange: () => changed++, now: () => t });
36
+ expect(src.has("terragucci-admin/demo", 4184, "apply-wave-1")).toBe(false);
37
+ expect(src.has("terragucci-admin/demo", 4184, "apply-wave-2")).toBe(false);
38
+ await new Promise((r) => setTimeout(r, 0));
39
+ expect(asked).toHaveLength(1);
40
+ expect(changed).toBe(1);
41
+ expect(src.has("terragucci-admin/demo", 4184, "apply-wave-1")).toBe(true);
42
+ expect(src.has("terragucci-admin/demo", 4184, "check")).toBe(false);
43
+ t += TRACE_POLL_MS;
44
+ src.has("terragucci-admin/demo", 4184, "apply-wave-1");
45
+ expect(asked).toHaveLength(2);
46
+ });
47
+
48
+ it("keeps the last answer when a read fails", async () => {
49
+ let t = 0;
50
+ let fail = false;
51
+ const src = traceSource({ fetchJson: async () => (fail ? { error: "Tempo is down" } : { traces: [{ job: "plan", start: T, ms: 1, spans: [] }], jobs: ["plan"] }), now: () => t });
52
+ src.has("o/r", 1, "plan");
53
+ await new Promise((r) => setTimeout(r, 0));
54
+ fail = true;
55
+ t += TRACE_POLL_MS;
56
+ src.has("o/r", 1, "plan");
57
+ await new Promise((r) => setTimeout(r, 0));
58
+ expect(src.has("o/r", 1, "plan")).toBe(true);
59
+ });
60
+ });
61
+
62
+ describe("the waterfall", () => {
63
+ it("lights the critical path: the root that planned last, the gate, the applies in turn", () => {
64
+ const on = criticalPath(SPANS);
65
+ expect([...on].sort()).toEqual(["a", "aa", "ab", "g", "ob", "p", "pb", "rb", "rib", "s"].sort());
66
+ expect(on.has("ra")).toBe(false);
67
+ // A root that started first and finished first, while the other still planned, is off it too.
68
+ const early = criticalPath([sp("p", null, "plan", 0, 100), sp("x", "p", "root x", 0, 60), sp("y", "p", "root y", 10, 100)]);
69
+ expect([...early].sort()).toEqual(["p", "y"]);
70
+ });
71
+
72
+ it("shows the stage, its phases, the roots and their commands, and folds the binary's spans", () => {
73
+ const rows = waterfallRows({ spans: SPANS });
74
+ expect(rows.map((r) => `${" ".repeat(r.depth)}${r.label}`)).toEqual([
75
+ "tf-apply, wave 1",
76
+ " plan",
77
+ " root a",
78
+ " root b",
79
+ " tofu plan",
80
+ " gate",
81
+ " apply",
82
+ " root a",
83
+ " root b",
84
+ ]);
85
+ const cmd = rows.find((r) => r.label === "tofu plan");
86
+ expect(cmd).toMatchObject({ depth: OPEN_DEPTH, kids: 1, open: false, critical: true });
87
+ const gate = rows.find((r) => r.label === "gate");
88
+ expect(gate).toMatchObject({ wait: true, critical: true, sub: "approved after 40 s held", at: 0.4, width: 0.4 });
89
+ expect(rows[0]).toMatchObject({ at: 0, width: 1, sub: "applied" });
90
+ });
91
+
92
+ it("opens a folded row on a click and folds an open one", () => {
93
+ const folds = foldState();
94
+ folds.toggle("pb", OPEN_DEPTH);
95
+ folds.toggle("ob", OPEN_DEPTH + 1);
96
+ let rows = waterfallRows({ spans: SPANS }, folds);
97
+ expect(rows.find((r) => r.label === "OpenTofu")).toMatchObject({ depth: 4, service: "OpenTofu CLI", open: true });
98
+ expect(rows.find((r) => r.label === "terraform_data.release")).toMatchObject({ sub: "plan", depth: 5 });
99
+ folds.toggle("p", 1);
100
+ rows = waterfallRows({ spans: SPANS }, folds);
101
+ expect(rows.some((r) => r.label === "root a" && r.depth === 2 && r.at < 0.5)).toBe(false);
102
+ });
103
+
104
+ it("names OpenTofu's spans by what they act on", () => {
105
+ expect(spanWords(sp("x", null, "Apply resource instance changes", 0, 1, { "opentofu.resource_instance.address": "terraform_data.x" }, "OpenTofu CLI"))).toEqual({ label: "terraform_data.x", sub: "apply" });
106
+ expect(spanWords(sp("x", null, "Configure provider", 0, 1, { "opentofu.provider.source": "registry.opentofu.org/hashicorp/aws" }, "OpenTofu CLI"))).toEqual({ label: "Configure provider", sub: "hashicorp/aws" });
107
+ expect(spanWords(sp("x", null, "gate", 0, 1, { "terragucci.phase": "gate", "terragucci.gate.status": "not-required" })).sub).toBe("no approval needed");
108
+ expect(spanWords(sp("x", null, "State lock wait", 0, 1, {}, "choudoufu")).label).toBe("State lock wait");
109
+ });
110
+
111
+ it("lays the run's jobs on one time line, each job's newest attempt", () => {
112
+ const strip = runStrip([
113
+ { job: "apply-wave-1", start: T, ms: 1000, result: "waiting" },
114
+ { job: "apply-wave-1", start: T + 2000, ms: 1000, result: "applied" },
115
+ { job: "apply-wave-2", start: T + 3000, ms: 1000, result: "applied" },
116
+ ]);
117
+ expect(strip).toEqual([
118
+ { job: "apply-wave-1", wave: undefined, result: "applied", ms: 1000, at: 0, width: 0.5 },
119
+ { job: "apply-wave-2", wave: undefined, result: "applied", ms: 1000, at: 0.5, width: 0.5 },
120
+ ]);
121
+ });
122
+
123
+ it("says a span's time in ms below a second", () => {
124
+ expect(msWords(0.4)).toBe("<1 ms");
125
+ expect(msWords(70)).toBe("70 ms");
126
+ expect(msWords(6400)).toBe("6.4 s");
127
+ expect(msWords(125_000)).toBe("2 min 5 s");
128
+ });
129
+ });
package/web/kiosk.html CHANGED
@@ -3,7 +3,7 @@
3
3
  <head>
4
4
  <meta charset="utf-8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1" />
6
- <title>behold kiosk</title>
6
+ <title>behold · live demo</title>
7
7
  <link
8
8
  rel="icon"
9
9
  href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='6' fill='none' stroke='%23a6adc8' stroke-width='1.6'/%3E%3Ccircle cx='8' cy='8' r='2.2' fill='%23a6adc8'/%3E%3C/svg%3E"
package/web/kiosk.js CHANGED
@@ -895,7 +895,7 @@ export function startKiosk({ bar, frame, side, main, views, read = null, tools =
895
895
  s.replay = null;
896
896
  s.repo = null;
897
897
  s.live = null;
898
- if (vendor && typeof document !== "undefined") document.title = `${vendor.name} · terragucci demo`;
898
+ if (vendor && typeof document !== "undefined") document.title = `behold · ${vendor.name}`;
899
899
  /** The time the page shows: the replay's, while it replays. */
900
900
  const shownNow = () => (s.mode === "replay" && s.replay && s.replay.at ? s.replay.at : now());
901
901
  /** behold#571: the frame and the plan's facts are the served repo's, so a tool's page shows them only for its own repo. */
package/web/share.png ADDED
Binary file