@intentius/behold 0.29.28 → 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/dist/cli.js CHANGED
@@ -471,9 +471,9 @@ function renderConflictReport(report) {
471
471
  }
472
472
  const grouped = /* @__PURE__ */ new Map();
473
473
  for (const conflict of conflicts) {
474
- const list3 = grouped.get(conflict.manager) ?? [];
475
- if (!list3.includes(conflict.field)) list3.push(conflict.field);
476
- grouped.set(conflict.manager, list3);
474
+ const list4 = grouped.get(conflict.manager) ?? [];
475
+ if (!list4.includes(conflict.field)) list4.push(conflict.field);
476
+ grouped.set(conflict.manager, list4);
477
477
  }
478
478
  const count = new Set(conflicts.map((c) => c.field)).size;
479
479
  const lines2 = [
@@ -1034,9 +1034,9 @@ async function createK8sClient(options2 = {}) {
1034
1034
  };
1035
1035
  }
1036
1036
  async function resolveByGvk(apiVersion, kind, signal) {
1037
- const list4 = await apiResourceList(apiVersion, signal);
1038
- if (!list4) return void 0;
1039
- const entry = (list4.resources ?? []).find((r) => r.kind === kind && !(r.name ?? "").includes("/"));
1037
+ const list5 = await apiResourceList(apiVersion, signal);
1038
+ if (!list5) return void 0;
1039
+ const entry = (list5.resources ?? []).find((r) => r.kind === kind && !(r.name ?? "").includes("/"));
1040
1040
  return entry ? toInfo(apiVersion, entry) : void 0;
1041
1041
  }
1042
1042
  async function resolveByResourceString(resource, group, signal) {
@@ -1059,8 +1059,8 @@ async function createK8sClient(options2 = {}) {
1059
1059
  (r) => (r.shortNames ?? []).some((s) => s.toLowerCase() === needle)
1060
1060
  ];
1061
1061
  for (const matches of matchers) {
1062
- for (const { gv, list: list4 } of lists) {
1063
- const entry = (list4?.resources ?? []).find((r) => !(r.name ?? "").includes("/") && matches(r));
1062
+ for (const { gv, list: list5 } of lists) {
1063
+ const entry = (list5?.resources ?? []).find((r) => !(r.name ?? "").includes("/") && matches(r));
1064
1064
  if (entry) return toInfo(gv, entry);
1065
1065
  }
1066
1066
  }
@@ -1101,7 +1101,7 @@ async function createK8sClient(options2 = {}) {
1101
1101
  throw err;
1102
1102
  }
1103
1103
  }
1104
- async function list3(selector, opts = {}) {
1104
+ async function list4(selector, opts = {}) {
1105
1105
  const info = await resolveOrThrow(selector, opts.signal);
1106
1106
  const items = [];
1107
1107
  let cont;
@@ -1339,9 +1339,9 @@ async function createK8sClient(options2 = {}) {
1339
1339
  return void 0;
1340
1340
  }
1341
1341
  async function resourcesOf(apiVersion, signal) {
1342
- const list4 = await apiResourceList(apiVersion, signal);
1343
- if (!list4) return [];
1344
- return (list4.resources ?? []).filter((r) => !(r.name ?? "").includes("/")).map((entry) => toInfo(apiVersion, entry));
1342
+ const list5 = await apiResourceList(apiVersion, signal);
1343
+ if (!list5) return [];
1344
+ return (list5.resources ?? []).filter((r) => !(r.name ?? "").includes("/")).map((entry) => toInfo(apiVersion, entry));
1345
1345
  }
1346
1346
  return {
1347
1347
  provenance,
@@ -1350,7 +1350,7 @@ async function createK8sClient(options2 = {}) {
1350
1350
  read,
1351
1351
  pathFor,
1352
1352
  readIfPresent,
1353
- list: list3,
1353
+ list: list4,
1354
1354
  readLog,
1355
1355
  watch: watch2,
1356
1356
  apply,
@@ -1430,9 +1430,9 @@ function fieldOwners(object, options2 = {}) {
1430
1430
  for (const set of fieldSetsOf(object)) {
1431
1431
  if (set.subresource !== void 0 && options2.includeSubresources !== true) continue;
1432
1432
  for (const path of set.fields) {
1433
- const list3 = owners.get(path) ?? [];
1434
- if (!list3.includes(set.manager)) list3.push(set.manager);
1435
- owners.set(path, list3);
1433
+ const list4 = owners.get(path) ?? [];
1434
+ if (!list4.includes(set.manager)) list4.push(set.manager);
1435
+ owners.set(path, list4);
1436
1436
  }
1437
1437
  }
1438
1438
  return owners;
@@ -1898,8 +1898,8 @@ function tfTypeOf(address, kind) {
1898
1898
  function boundaryEdgesOf(r) {
1899
1899
  const b = r.boundary;
1900
1900
  if (!b) return [];
1901
- const list3 = Array.isArray(b) ? b : [...b.inbound ?? [], ...b.outbound ?? []];
1902
- return list3.filter((e) => isRecord2(e) && typeof e.survivor === "string" && typeof e.carved === "string");
1901
+ const list4 = Array.isArray(b) ? b : [...b.inbound ?? [], ...b.outbound ?? []];
1902
+ return list4.filter((e) => isRecord2(e) && typeof e.survivor === "string" && typeof e.carved === "string");
1903
1903
  }
1904
1904
  function scoreArithmetic(r) {
1905
1905
  const b = r.breakdown;
@@ -2910,8 +2910,8 @@ function indexRoster(addresses) {
2910
2910
  for (let depth = 1; depth < segments.length; depth++) {
2911
2911
  const callPath = segments.slice(0, depth).join("/");
2912
2912
  const written2 = { address, scope: scopeAbove(instance.scope, depth - 1), key: "" };
2913
- const list3 = calls.get(callPath);
2914
- if (list3) list3.push(written2);
2913
+ const list4 = calls.get(callPath);
2914
+ if (list4) list4.push(written2);
2915
2915
  else calls.set(callPath, [written2]);
2916
2916
  }
2917
2917
  }
@@ -5386,11 +5386,11 @@ function applyCommandFor(state, labels = {}) {
5386
5386
  return `chant carve apply --from ${from} --output ${out} --env ${env} --stack ${stack} --write-source`;
5387
5387
  }
5388
5388
  function carveStatePayload(states, total, labels = () => ({})) {
5389
- const list3 = [...states.values()].sort((a, b) => a.target.localeCompare(b.target));
5389
+ const list4 = [...states.values()].sort((a, b) => a.target.localeCompare(b.target));
5390
5390
  return {
5391
- manifests: list3.length,
5392
- progress: carveProgress(list3, total),
5393
- states: list3.map((s) => ({ ...s, note: carveStageNote(s), applyCommand: applyCommandFor(s, labels(s)) })),
5391
+ manifests: list4.length,
5392
+ progress: carveProgress(list4, total),
5393
+ states: list4.map((s) => ({ ...s, note: carveStageNote(s), applyCommand: applyCommandFor(s, labels(s)) })),
5394
5394
  apply: { human: true, note: APPLY_IS_HUMAN }
5395
5395
  };
5396
5396
  }
@@ -6104,10 +6104,10 @@ function verifySshSignatureWith(armored, message2, namespace, keys) {
6104
6104
  return { ok: false, reason: err instanceof Error ? err.message : String(err) };
6105
6105
  }
6106
6106
  }
6107
- function namespaceAllowed(list3, namespace) {
6108
- if (list3 === void 0) return true;
6107
+ function namespaceAllowed(list4, namespace) {
6108
+ if (list4 === void 0) return true;
6109
6109
  let allowed = false;
6110
- for (const raw of list3.split(",")) {
6110
+ for (const raw of list4.split(",")) {
6111
6111
  const negated = raw.startsWith("!");
6112
6112
  const pattern = negated ? raw.slice(1) : raw;
6113
6113
  const re = new RegExp(`^${pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".")}$`);
@@ -10757,8 +10757,8 @@ function writeScopeOf(raw, members, at2) {
10757
10757
  const out = {};
10758
10758
  for (const [cls, entry] of Object.entries(block)) {
10759
10759
  const pointer = `/writeScope/${cls}`;
10760
- const list3 = entry.members === void 0 || entry.members === "*" ? null : [...entry.members];
10761
- for (const [i, name] of (list3 ?? []).entries()) {
10760
+ const list4 = entry.members === void 0 || entry.members === "*" ? null : [...entry.members];
10761
+ for (const [i, name] of (list4 ?? []).entries()) {
10762
10762
  if (!members.some((m) => m.name === name)) {
10763
10763
  throw new WorkspaceReadError2(
10764
10764
  "declaration-invalid",
@@ -10769,7 +10769,7 @@ function writeScopeOf(raw, members, at2) {
10769
10769
  }
10770
10770
  const records = entry.records === void 0 ? null : Object.fromEntries(Object.entries(entry.records).map(([k, v]) => [k, [...v]]));
10771
10771
  const guarded = (entry.protected ?? []).map((p) => typeof p === "string" ? { path: p, except: [] } : { path: p.path, except: [...p.except ?? []] });
10772
- out[cls] = { members: list3, records, protected: guarded, pointer };
10772
+ out[cls] = { members: list4, records, protected: guarded, pointer };
10773
10773
  }
10774
10774
  return out;
10775
10775
  }
@@ -13856,8 +13856,8 @@ function applyHelmRenderDrift(ir, reports) {
13856
13856
  if (reports.length === 0) return { charts: 0, drifted: 0 };
13857
13857
  const byChart = /* @__PURE__ */ new Map();
13858
13858
  for (const r of reports) {
13859
- const list3 = byChart.get(r.chart);
13860
- if (list3) list3.push(r);
13859
+ const list4 = byChart.get(r.chart);
13860
+ if (list4) list4.push(r);
13861
13861
  else byChart.set(r.chart, [r]);
13862
13862
  }
13863
13863
  let charts = 0;
@@ -14722,9 +14722,9 @@ function enrichedRefs(ir, aws, byId) {
14722
14722
  const producersByName = /* @__PURE__ */ new Map();
14723
14723
  for (const ex of ir.exports ?? []) {
14724
14724
  if (!ex.node || !byId.has(ex.node)) continue;
14725
- const list3 = producersByName.get(ex.name) ?? producersByName.set(ex.name, []).get(ex.name);
14726
- if (isExample(byId.get(ex.node))) list3.push(ex.node);
14727
- else list3.unshift(ex.node);
14725
+ const list4 = producersByName.get(ex.name) ?? producersByName.set(ex.name, []).get(ex.name);
14726
+ if (isExample(byId.get(ex.node))) list4.push(ex.node);
14727
+ else list4.unshift(ex.node);
14728
14728
  }
14729
14729
  const exportNames = [...producersByName.keys()].sort((a, b) => b.length - a.length);
14730
14730
  const bridge = (paramId, producers) => {
@@ -16730,8 +16730,8 @@ async function terragucciOverriders(show) {
16730
16730
  if (text2 === void 0 || name.endsWith(".ts")) continue;
16731
16731
  try {
16732
16732
  const doc = name.endsWith(".json") ? JSON.parse(text2) : parseYAML(text2);
16733
- const list3 = doc?.policy?.override;
16734
- return { principals: Array.isArray(list3) ? list3.filter((x) => typeof x === "string") : [], path: "policy.override" };
16733
+ const list4 = doc?.policy?.override;
16734
+ return { principals: Array.isArray(list4) ? list4.filter((x) => typeof x === "string") : [], path: "policy.override" };
16735
16735
  } catch {
16736
16736
  return { principals: [], path: "policy.override" };
16737
16737
  }
@@ -18904,9 +18904,9 @@ function joinStepEntities(ir, estate) {
18904
18904
  for (const n of estate?.nodes ?? []) {
18905
18905
  byId.set(n.id, n);
18906
18906
  for (const leaf of stringLeaves(n.attrs)) {
18907
- const list3 = byLeaf.get(leaf.value);
18908
- if (list3) {
18909
- if (!list3.includes(n)) list3.push(n);
18907
+ const list4 = byLeaf.get(leaf.value);
18908
+ if (list4) {
18909
+ if (!list4.includes(n)) list4.push(n);
18910
18910
  } else byLeaf.set(leaf.value, [n]);
18911
18911
  }
18912
18912
  }
@@ -19474,23 +19474,23 @@ function routeEdges(svg) {
19474
19474
  ];
19475
19475
  for (const e of pair) {
19476
19476
  const key2 = `${e.card}\0${e.side}`;
19477
- const list3 = sides.get(key2) ?? [];
19478
- list3.push(e);
19479
- sides.set(key2, list3);
19477
+ const list4 = sides.get(key2) ?? [];
19478
+ list4.push(e);
19479
+ sides.set(key2, list4);
19480
19480
  }
19481
19481
  return pair;
19482
19482
  });
19483
- for (const list3 of sides.values()) {
19484
- const card = geo.cards.get(list3[0].card);
19485
- const side = list3[0].side;
19483
+ for (const list4 of sides.values()) {
19484
+ const card = geo.cards.get(list4[0].card);
19485
+ const side = list4[0].side;
19486
19486
  const len = side === "top" || side === "bottom" ? card.w : card.h;
19487
- if (list3.length > 1) {
19488
- const gap = Math.min(PORT_GAP, len * 0.7 / (list3.length - 1));
19489
- list3.sort((p, q) => p.toward - q.toward || p.edge - q.edge);
19490
- list3.forEach((e, k2) => e.offset = (k2 - (list3.length - 1) / 2) * gap);
19487
+ if (list4.length > 1) {
19488
+ const gap = Math.min(PORT_GAP, len * 0.7 / (list4.length - 1));
19489
+ list4.sort((p, q) => p.toward - q.toward || p.edge - q.edge);
19490
+ list4.forEach((e, k2) => e.offset = (k2 - (list4.length - 1) / 2) * gap);
19491
19491
  }
19492
- const shift = clearOfLabels(card, side, list3.map((e) => e.offset), geo.labels);
19493
- if (shift) list3.forEach((e) => e.offset += shift);
19492
+ const shift = clearOfLabels(card, side, list4.map((e) => e.offset), geo.labels);
19493
+ if (shift) list4.forEach((e) => e.offset += shift);
19494
19494
  }
19495
19495
  const cardRects = [...geo.cards.entries()];
19496
19496
  const chips = [];
@@ -20261,15 +20261,15 @@ function packBoxComponents(layout, ir, boxes, bandOf, subgroups) {
20261
20261
  let shelfH = 0;
20262
20262
  const bands = [];
20263
20263
  for (const band of order) {
20264
- const list3 = banded.get(band);
20265
- if (!list3?.length) continue;
20264
+ const list4 = banded.get(band);
20265
+ if (!list4?.length) continue;
20266
20266
  if (shelfH > 0) {
20267
20267
  shelfX = 0;
20268
20268
  shelfY += shelfH + COMPONENT_GAP;
20269
20269
  shelfH = 0;
20270
20270
  }
20271
20271
  const ids2 = [];
20272
- for (const c of list3) {
20272
+ for (const c of list4) {
20273
20273
  if (shelfX > 0 && shelfX + c.w > targetW) {
20274
20274
  shelfX = 0;
20275
20275
  shelfY += shelfH + COMPONENT_GAP;
@@ -21236,9 +21236,9 @@ function joinRun(op, records, gate) {
21236
21236
  const indexOf = new Map(placed.map((p, i) => [p.id, i]));
21237
21237
  for (const record of records) {
21238
21238
  const key2 = `${record.phase}\0${record.fn}`;
21239
- const list3 = byKey.get(key2);
21239
+ const list4 = byKey.get(key2);
21240
21240
  const i = cursor.get(key2) ?? 0;
21241
- const slot = list3?.[i];
21241
+ const slot = list4?.[i];
21242
21242
  if (!slot) {
21243
21243
  unplaced.push(record);
21244
21244
  continue;
@@ -26390,6 +26390,239 @@ function metricsRoute(app, opts) {
26390
26390
  });
26391
26391
  }
26392
26392
 
26393
+ // src/tempo-traces.ts
26394
+ var SEARCH_TTL_MS = 1e4;
26395
+ var TRACE_TTL_MS = 6e4;
26396
+ var TRACE_CACHE_MAX = 200;
26397
+ var SEARCH_LIMIT = 40;
26398
+ var SEARCH_WINDOW_S = 48 * 3600;
26399
+ var MAX_SPANS = 1500;
26400
+ var RUN = /^[1-9][0-9]{0,15}$/;
26401
+ var JOB = /^[A-Za-z0-9][A-Za-z0-9 ._()-]{0,99}$/;
26402
+ var validRun = (v) => !!v && RUN.test(v);
26403
+ var validJob = (v) => !!v && JOB.test(v);
26404
+ function searchQuery(by) {
26405
+ if ("run" in by) {
26406
+ if (!validRun(by.run)) throw new Error("a run id is digits");
26407
+ return `{ resource.service.name = "terragucci" && resource."cicd.pipeline.run.id" = "${by.run}" }`;
26408
+ }
26409
+ if (!validCommit(by.commit)) throw new Error("a commit is hex");
26410
+ return by.commit.length === 40 || by.commit.length === 64 ? `{ resource.service.name = "terragucci" && resource."vcs.ref.head.revision" = "${by.commit}" }` : `{ resource.service.name = "terragucci" && resource."vcs.ref.head.revision" =~ "${by.commit}.*" }`;
26411
+ }
26412
+ var KEPT_ATTRIBUTES = [
26413
+ "terragucci.stage",
26414
+ "terragucci.phase",
26415
+ "terragucci.wave",
26416
+ "terragucci.root",
26417
+ "terragucci.result",
26418
+ "terragucci.status",
26419
+ "terragucci.gate.status",
26420
+ "terragucci.gate.held_seconds",
26421
+ "terragucci.gate.waiting_since",
26422
+ "terragucci.gate.approved_at",
26423
+ "process.exit.code",
26424
+ "opentofu.resource_instance.address",
26425
+ "opentofu.resource_instance.action",
26426
+ "opentofu.resource.address",
26427
+ "opentofu.resource.type",
26428
+ "opentofu.provider.address",
26429
+ "opentofu.provider.source",
26430
+ "opentofu.state.backend",
26431
+ "rpc.method"
26432
+ ];
26433
+ var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
26434
+ var list3 = (v) => Array.isArray(v) ? v : [];
26435
+ function scalar(v) {
26436
+ if (!isObj(v)) return void 0;
26437
+ if (typeof v.stringValue === "string") return v.stringValue;
26438
+ if (typeof v.boolValue === "boolean") return v.boolValue;
26439
+ if (typeof v.intValue === "string" || typeof v.intValue === "number") return Number(v.intValue);
26440
+ if (typeof v.doubleValue === "number") return v.doubleValue;
26441
+ return void 0;
26442
+ }
26443
+ function attrsOf(v) {
26444
+ const out = {};
26445
+ for (const kv of list3(v)) {
26446
+ if (!isObj(kv) || typeof kv.key !== "string") continue;
26447
+ const s = scalar(kv.value);
26448
+ if (s !== void 0) out[kv.key] = s;
26449
+ }
26450
+ return out;
26451
+ }
26452
+ function idHex(v) {
26453
+ if (typeof v !== "string" || v === "") return null;
26454
+ if (/^[0-9a-f]{16}$|^[0-9a-f]{32}$/i.test(v)) return v.toLowerCase();
26455
+ try {
26456
+ const hex = Buffer.from(v, "base64").toString("hex");
26457
+ return hex.length === 16 || hex.length === 32 ? hex : null;
26458
+ } catch {
26459
+ return null;
26460
+ }
26461
+ }
26462
+ var nanosToMs = (v) => {
26463
+ if (typeof v !== "string" && typeof v !== "number") return void 0;
26464
+ try {
26465
+ const n = BigInt(v);
26466
+ return Number(n / 1000n) / 1e3;
26467
+ } catch {
26468
+ return void 0;
26469
+ }
26470
+ };
26471
+ function trimTrace(traceId, body, repo, maxSpans = MAX_SPANS) {
26472
+ const doc = isObj(body) && isObj(body.trace) ? body.trace : body;
26473
+ const batches = isObj(doc) ? list3(doc.resourceSpans ?? doc.batches) : [];
26474
+ const spans = [];
26475
+ let own;
26476
+ for (const rs of batches) {
26477
+ if (!isObj(rs)) continue;
26478
+ const resource = attrsOf(isObj(rs.resource) ? rs.resource.attributes : void 0);
26479
+ const service = typeof resource["service.name"] === "string" ? resource["service.name"] : "unknown";
26480
+ if (service === "terragucci" && typeof resource["terragucci.project"] === "string") own ??= resource;
26481
+ for (const ss of list3(rs.scopeSpans ?? rs.instrumentationLibrarySpans)) {
26482
+ if (!isObj(ss)) continue;
26483
+ for (const s of list3(ss.spans)) {
26484
+ if (!isObj(s) || typeof s.name !== "string") continue;
26485
+ const id = idHex(s.spanId);
26486
+ const start2 = nanosToMs(s.startTimeUnixNano);
26487
+ const end2 = nanosToMs(s.endTimeUnixNano);
26488
+ if (!id || start2 === void 0 || end2 === void 0) continue;
26489
+ const all = attrsOf(s.attributes);
26490
+ const attrs = {};
26491
+ for (const k of KEPT_ATTRIBUTES) if (all[k] !== void 0) attrs[k] = all[k];
26492
+ const status2 = isObj(s.status) ? s.status : {};
26493
+ const failed = status2.code === 2 || status2.code === "STATUS_CODE_ERROR";
26494
+ spans.push({
26495
+ id,
26496
+ parent: idHex(s.parentSpanId),
26497
+ name: s.name.slice(0, 200),
26498
+ service,
26499
+ start: start2,
26500
+ ms: Math.max(0, Math.round((end2 - start2) * 1e3) / 1e3),
26501
+ ...failed ? { error: typeof status2.message === "string" && status2.message ? status2.message.slice(0, 200) : "error" } : {},
26502
+ attrs
26503
+ });
26504
+ }
26505
+ }
26506
+ }
26507
+ if (!own || !projectIs(String(own["terragucci.project"]), repo) || spans.length === 0) return null;
26508
+ spans.sort((a, b) => a.start - b.start);
26509
+ const stage = spans.find((s) => s.parent === null && typeof s.attrs["terragucci.stage"] === "string") ?? spans.find((s) => s.parent === null) ?? spans[0];
26510
+ const start = Math.min(...spans.map((s) => s.start));
26511
+ const end = Math.max(...spans.map((s) => s.start + s.ms));
26512
+ let kept = spans;
26513
+ if (spans.length > maxSpans) {
26514
+ const byId = new Map(spans.map((s) => [s.id, s]));
26515
+ const depth = (s) => {
26516
+ let d = 0;
26517
+ for (let p = s.parent ? byId.get(s.parent) : void 0; p && d < 64; p = p.parent ? byId.get(p.parent) : void 0) d++;
26518
+ return d;
26519
+ };
26520
+ const order = spans.map((s) => ({ s, d: depth(s) })).sort((a, b) => a.d - b.d || a.s.start - b.s.start);
26521
+ const keep = new Set(order.slice(0, maxSpans).map((x) => x.s));
26522
+ kept = spans.filter((s) => keep.has(s));
26523
+ }
26524
+ const str17 = (v) => typeof v === "string" && v ? v : null;
26525
+ const wave = Number(stage.attrs["terragucci.wave"]);
26526
+ return {
26527
+ trace_id: traceId,
26528
+ project: String(own["terragucci.project"]),
26529
+ job: str17(own["cicd.pipeline.task.name"]),
26530
+ stage: str17(stage.attrs["terragucci.stage"]),
26531
+ wave: Number.isInteger(wave) && wave > 0 ? wave : null,
26532
+ result: str17(stage.attrs["terragucci.result"]),
26533
+ commit: str17(own["vcs.ref.head.revision"]),
26534
+ start,
26535
+ ms: Math.round((end - start) * 1e3) / 1e3,
26536
+ spans: kept,
26537
+ left_out: spans.length - kept.length
26538
+ };
26539
+ }
26540
+ function searchIds(body) {
26541
+ const traces = isObj(body) ? list3(body.traces) : [];
26542
+ return traces.filter(isObj).map((t2) => ({ id: typeof t2.traceID === "string" && /^[0-9a-f]{1,32}$/i.test(t2.traceID) ? t2.traceID.toLowerCase().padStart(32, "0") : null, at: nanosToMs(t2.startTimeUnixNano) ?? 0 })).filter((t2) => t2.id !== null).sort((a, b) => a.at - b.at).map((t2) => t2.id);
26543
+ }
26544
+ function tempoAddress(v) {
26545
+ if (!v) return void 0;
26546
+ try {
26547
+ const u = new URL(v);
26548
+ if (u.protocol !== "http:" && u.protocol !== "https:" || u.search || u.hash) return void 0;
26549
+ return u.toString().replace(/\/+$/, "");
26550
+ } catch {
26551
+ return void 0;
26552
+ }
26553
+ }
26554
+ var Shared = class {
26555
+ constructor(ttl, max) {
26556
+ this.ttl = ttl;
26557
+ this.max = max;
26558
+ }
26559
+ ttl;
26560
+ max;
26561
+ map = /* @__PURE__ */ new Map();
26562
+ get(key2, read) {
26563
+ const t2 = Date.now();
26564
+ const hit = this.map.get(key2);
26565
+ if (hit && t2 - hit.at < this.ttl) return hit.read;
26566
+ for (const [k, v] of this.map) if (t2 - v.at >= this.ttl) this.map.delete(k);
26567
+ while (this.map.size >= this.max) this.map.delete(this.map.keys().next().value);
26568
+ const p = read();
26569
+ this.map.set(key2, { at: t2, read: p });
26570
+ p.catch(() => {
26571
+ if (this.map.get(key2)?.read === p) this.map.delete(key2);
26572
+ });
26573
+ return p;
26574
+ }
26575
+ };
26576
+ function tracesRoute(app, opts) {
26577
+ const fetchFn = opts.fetch ?? fetch;
26578
+ const searches = new Shared(SEARCH_TTL_MS, 100);
26579
+ const traces = new Shared(TRACE_TTL_MS, TRACE_CACHE_MAX);
26580
+ const search = (q) => searches.get(q, async () => {
26581
+ const end = Math.floor(Date.now() / 1e3) + 60;
26582
+ const u = `${opts.tempo}/api/search?${new URLSearchParams({ q, limit: String(SEARCH_LIMIT), start: String(end - SEARCH_WINDOW_S), end: String(end) })}`;
26583
+ const res = await fetchFn(u, { signal: AbortSignal.timeout(8e3), headers: { accept: "application/json" } });
26584
+ if (!res.ok) throw new Error(`Tempo answered ${res.status} to the search`);
26585
+ return searchIds(await res.json());
26586
+ });
26587
+ const trace = (id) => traces.get(id, async () => {
26588
+ const res = await fetchFn(`${opts.tempo}/api/v2/traces/${id}`, { signal: AbortSignal.timeout(8e3), headers: { accept: "application/json" } });
26589
+ if (res.status === 404) return null;
26590
+ if (!res.ok) throw new Error(`Tempo answered ${res.status} to trace ${id}`);
26591
+ return res.json();
26592
+ });
26593
+ app.get("/api/traces", async (c) => {
26594
+ if (!opts.tempo) return c.json({ error: "behold reads no Tempo: start it with --tempo <url>", code: "traces-off" }, 404);
26595
+ const repo = c.req.query("project");
26596
+ if (!validRepo(repo)) return c.json({ error: "project must be a forge repo's <owner>/<name>", code: "traces-project" }, 400);
26597
+ const run3 = c.req.query("run");
26598
+ const commit = c.req.query("commit");
26599
+ const job = c.req.query("job");
26600
+ if (run3 !== void 0 && !validRun(run3)) return c.json({ error: "run must be a pipeline run's id", code: "traces-run" }, 400);
26601
+ if (commit !== void 0 && !validCommit(commit)) return c.json({ error: "commit must be a commit's hex id", code: "traces-commit" }, 400);
26602
+ if (run3 === void 0 && commit === void 0) return c.json({ error: "name a run or a commit", code: "traces-run" }, 400);
26603
+ if (job !== void 0 && !validJob(job)) return c.json({ error: "job must be a job's name", code: "traces-job" }, 400);
26604
+ let found;
26605
+ try {
26606
+ const ids = await search(searchQuery(run3 !== void 0 ? { run: run3 } : { commit }));
26607
+ const bodies = await Promise.all(ids.map((id) => trace(id)));
26608
+ found = ids.map((id, i) => bodies[i] ? trimTrace(id, bodies[i], repo) : null).filter((t2) => t2 !== null);
26609
+ } catch (e) {
26610
+ return c.json({ error: `behold could not read Tempo: ${e instanceof Error ? e.message : String(e)}`, code: "traces-read" }, 502, { "cache-control": "no-store" });
26611
+ }
26612
+ found.sort((a, b) => a.start - b.start);
26613
+ const body = {
26614
+ read: (opts.now ? opts.now() : /* @__PURE__ */ new Date()).toISOString(),
26615
+ repo,
26616
+ project: found[0]?.project ?? null,
26617
+ run: run3 ?? null,
26618
+ commit: commit ?? found[0]?.commit ?? null,
26619
+ jobs: [...new Set(found.map((t2) => t2.job).filter((j) => j !== null))].sort((x, y) => x.localeCompare(y, "en", { numeric: true })),
26620
+ traces: job !== void 0 ? found.filter((t2) => t2.job === job) : found
26621
+ };
26622
+ return c.json(body, 200, { "cache-control": "no-store" });
26623
+ });
26624
+ }
26625
+
26393
26626
  // src/view-repos.ts
26394
26627
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
26395
26628
  import { existsSync as existsSync26, readdirSync as readdirSync16, readFileSync as readFileSync33 } from "node:fs";
@@ -27906,10 +28139,10 @@ function readCatalog(file, catalog) {
27906
28139
  } catch {
27907
28140
  return [];
27908
28141
  }
27909
- const list3 = raw?.demos;
27910
- if (!Array.isArray(list3)) return [];
28142
+ const list4 = raw?.demos;
28143
+ if (!Array.isArray(list4)) return [];
27911
28144
  const catalogDir = dirname17(resolve31(file));
27912
- return list3.filter((e) => validEntry(e)).map((e) => ({ ...e, catalog, catalogDir }));
28145
+ return list4.filter((e) => validEntry(e)).map((e) => ({ ...e, catalog, catalogDir }));
27913
28146
  }
27914
28147
  function validEntry(e) {
27915
28148
  const d = e;
@@ -28491,6 +28724,7 @@ function createApp(cfg, broadcaster = new Broadcaster(), frames = new FrameBuffe
28491
28724
  shareImageRoute(app, webRoot);
28492
28725
  const doraSource = cfg.terragucci && cfg.prometheus ? terragucciSource(cfg.terragucci.source, { ...cfg.terragucci.aws ? { aws: cfg.terragucci.aws } : {}, ...cfg.terragucci.fetch ? { fetch: cfg.terragucci.fetch } : {} }) : void 0;
28493
28726
  metricsRoute(app, { ...cfg.prometheus ? { prometheus: cfg.prometheus } : {}, ...doraSource ? { doraFile: () => doraSource.read("dora.json") } : {} });
28727
+ tracesRoute(app, cfg.tempo ? { tempo: cfg.tempo } : {});
28494
28728
  vendorRoutes(app, webRoot, !!cfg.terragucci, guard.allowedHosts);
28495
28729
  app.get("/api/frames", (c) => c.json({ frames: frames.summaries() }));
28496
28730
  app.get("/lanes", (c) => {
@@ -30965,6 +31199,12 @@ Options:
30965
31199
  and apply seconds, its time at the gate and its changes,
30966
31200
  and the DORA metrics. /api/metrics?project=<owner>/<name>
30967
31201
  answers them, and the kiosk shows them (behold#571).
31202
+ --tempo <url> serve only: the Tempo behold reads a pipeline run's
31203
+ traces from (BEHOLD_TEMPO_URL too), with fixed queries:
31204
+ a search by run id or commit, and a trace by its id.
31205
+ /api/traces?project=<owner>/<name>&run=<id> answers
31206
+ each job's span tree, and the kiosk's job pane draws it
31207
+ as a Trace view (behold#571).
30968
31208
  --terragucci <src> serve/export: paint a terragucci estate from its reports
30969
31209
  (#490). <src> is a report directory (a synced bucket
30970
31210
  prefix, or <prefix>/<project>), s3://bucket/prefix (read
@@ -31110,6 +31350,7 @@ ${USAGE}`);
31110
31350
  let host;
31111
31351
  let hudArg = process.env.BEHOLD_HUD_URL || void 0;
31112
31352
  let prometheusArg = process.env.BEHOLD_PROMETHEUS_URL || void 0;
31353
+ let tempoArg = process.env.BEHOLD_TEMPO_URL || void 0;
31113
31354
  let terragucci;
31114
31355
  let terragucciProject;
31115
31356
  let terragucciPoll;
@@ -31125,6 +31366,7 @@ ${USAGE}`);
31125
31366
  else if (a === "--allow-host") allowHosts.push(...(rest[++i] ?? "").split(","));
31126
31367
  else if (a === "--hud") hudArg = rest[++i];
31127
31368
  else if (a === "--prometheus") prometheusArg = rest[++i];
31369
+ else if (a === "--tempo") tempoArg = rest[++i];
31128
31370
  else if (a === "--terragucci") terragucci = rest[++i];
31129
31371
  else if (a === "--terragucci-project") terragucciProject = rest[++i];
31130
31372
  else if (a === "--terragucci-poll") terragucciPoll = Number(rest[++i]);
@@ -31176,6 +31418,12 @@ ${USAGE}`);
31176
31418
  const prometheus = prometheusAddress(prometheusArg);
31177
31419
  if (prometheusArg && !prometheus) {
31178
31420
  process.stderr.write(`behold serve: --prometheus must be an http or https address with no query, not ${JSON.stringify(prometheusArg)}
31421
+ `);
31422
+ process.exit(2);
31423
+ }
31424
+ const tempo = tempoAddress(tempoArg);
31425
+ if (tempoArg && !tempo) {
31426
+ process.stderr.write(`behold serve: --tempo must be an http or https address with no query, not ${JSON.stringify(tempoArg)}
31179
31427
  `);
31180
31428
  process.exit(2);
31181
31429
  }
@@ -31249,6 +31497,7 @@ ${USAGE}`);
31249
31497
  ...isPublic ? { public: true, layoutWrites: false } : {},
31250
31498
  ...target.workspace && hud ? { hud } : {},
31251
31499
  ...prometheus ? { prometheus } : {},
31500
+ ...tempo ? { tempo } : {},
31252
31501
  ...yodelReport ? { yodelReport: resolve35(yodelReport) } : {},
31253
31502
  ...terragucci ? { terragucci: { source: terragucci, ...terragucciProject ? { project: terragucciProject } : {}, ...terragucciPoll !== void 0 ? { pollSecs: terragucciPoll } : {}, ...terragucciRuns ? { runsSource: terragucciRuns } : {} } } : {}
31254
31503
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intentius/behold",
3
- "version": "0.29.28",
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
+ });