@reqray/waterfall 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ruslan Kryklyvyi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,44 @@
1
- # Temporary Holding Version
1
+ # @reqray/waterfall
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The waterfall model of Reqray, shared by every client that draws one: which
4
+ spans collapse into a run, where the uninstrumented time is, how deep each bar
5
+ sits. It decides structure and never draws.
6
+
7
+ Part of [Reqray](https://github.com/reqray/reqray) — a dev panel and request inspector for Node.js. It
8
+ instruments HTTP, SQL, outgoing calls and cache on its own, shows every
9
+ request as a waterfall, and finds N+1 down to the file and the line.
10
+
11
+ The web panel and [`@reqray/cli`](https://www.npmjs.com/package/@reqray/cli)
12
+ both build their waterfalls with it, which is why they agree. Install it to
13
+ draw a Reqray request somewhere else.
14
+
15
+ ```bash
16
+ npm install @reqray/waterfall
17
+ ```
18
+
19
+ ```ts
20
+ import { buildWaterfall, uninstrumentedMs } from '@reqray/waterfall';
21
+
22
+ const bars = buildWaterfall(request); // spans, findings and durationMs of one request
23
+ console.log(`${uninstrumentedMs(bars)} ms no span accounts for`);
24
+ ```
25
+
26
+ | | |
27
+ |---|---|
28
+ | `buildWaterfall(request)` | The bars, in drawing order: 150 identical queries folded into one, gaps made explicit |
29
+ | `findGaps(request)` | Stretches of the request no span covers |
30
+ | `uninstrumentedMs(bars)` | Their total |
31
+ | `parallelSpans(spans)` | Which spans overlapped in time |
32
+ | `depthOf(span, byId)` | How deep a span is nested |
33
+
34
+ Types come from [`@reqray/protocol`](https://www.npmjs.com/package/@reqray/protocol).
35
+
36
+ ## More
37
+
38
+ Everything else — the detectors, security defaults, measured overhead and a
39
+ demo that runs with one command — is in the
40
+ [main README](https://github.com/reqray/reqray#readme).
41
+
42
+ ## License
43
+
44
+ [MIT](https://github.com/reqray/reqray/blob/main/LICENSE)
package/dist/index.cjs ADDED
@@ -0,0 +1,162 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ buildWaterfall: () => buildWaterfall,
24
+ depthOf: () => depthOf,
25
+ findGaps: () => findGaps,
26
+ isRunEvidence: () => isRunEvidence,
27
+ parallelSpans: () => parallelSpans,
28
+ uninstrumentedMs: () => uninstrumentedMs
29
+ });
30
+ module.exports = __toCommonJS(index_exports);
31
+ var GAP_MIN_MS = 20;
32
+ var GAP_MIN_SHARE = 0.1;
33
+ var MAX_DEPTH = 32;
34
+ function isRunEvidence(evidence) {
35
+ return evidence.kind === "n_plus_one" || evidence.kind === "sequential_http";
36
+ }
37
+ function depthOf(span, byId) {
38
+ let depth = 0;
39
+ let parentId = span.parentId;
40
+ while (parentId !== null && depth < MAX_DEPTH) {
41
+ const parent = byId.get(parentId);
42
+ if (!parent) break;
43
+ depth++;
44
+ parentId = parent.parentId;
45
+ }
46
+ return depth;
47
+ }
48
+ function findGaps(input) {
49
+ const total = input.durationMs;
50
+ const threshold = Math.max(GAP_MIN_MS, total * GAP_MIN_SHARE);
51
+ const intervals = input.spans.filter((span) => span.kind !== "handler" && span.kind !== "middleware").map((span) => ({
52
+ start: span.startedAt - (span.kind === "db" ? span.waitMs ?? 0 : 0),
53
+ end: span.startedAt + span.duration
54
+ })).sort((a, b) => a.start - b.start);
55
+ const gaps = [];
56
+ let cursor = 0;
57
+ for (const interval of intervals) {
58
+ if (interval.start - cursor >= threshold) gaps.push({ start: cursor, end: interval.start });
59
+ cursor = Math.max(cursor, interval.end);
60
+ }
61
+ if (total - cursor >= threshold) gaps.push({ start: cursor, end: total });
62
+ return gaps;
63
+ }
64
+ function buildWaterfall(input) {
65
+ const byId = new Map(input.spans.map((span) => [span.id, span]));
66
+ const grouped = /* @__PURE__ */ new Map();
67
+ const marked = /* @__PURE__ */ new Map();
68
+ for (const finding of input.findings) {
69
+ for (const id of finding.evidence.spanIds) {
70
+ if (isRunEvidence(finding.evidence)) grouped.set(id, finding);
71
+ else marked.set(id, [...marked.get(id) ?? [], finding.detector]);
72
+ }
73
+ }
74
+ const bars = [];
75
+ const emitted = /* @__PURE__ */ new Set();
76
+ for (const span of input.spans) {
77
+ const finding = grouped.get(span.id);
78
+ if (!finding) {
79
+ bars.push({
80
+ key: `s${span.id}`,
81
+ kind: span.kind,
82
+ depth: depthOf(span, byId),
83
+ startedAt: span.startedAt,
84
+ duration: span.duration,
85
+ span,
86
+ count: 1,
87
+ finding: null,
88
+ marks: marked.get(span.id) ?? [],
89
+ waitMs: span.kind === "db" ? span.waitMs ?? 0 : 0
90
+ });
91
+ continue;
92
+ }
93
+ if (emitted.has(finding)) continue;
94
+ emitted.add(finding);
95
+ const members = finding.evidence.spanIds.map((id) => byId.get(id)).filter((member) => member !== void 0);
96
+ if (members.length === 0) continue;
97
+ const start = Math.min(...members.map((member) => member.startedAt));
98
+ const end = Math.max(...members.map((member) => member.startedAt + member.duration));
99
+ const fingerprint = "fingerprint" in finding.evidence ? String(finding.evidence.fingerprint) : "";
100
+ bars.push({
101
+ key: `f${finding.detector}${fingerprint}`,
102
+ kind: span.kind,
103
+ depth: depthOf(span, byId),
104
+ startedAt: start,
105
+ duration: end - start,
106
+ // The first of the run: what the group is *of*, which is what a label
107
+ // needs. The count says how many there were.
108
+ span,
109
+ count: members.length,
110
+ finding: finding.detector,
111
+ marks: [],
112
+ waitMs: 0
113
+ });
114
+ }
115
+ for (const gap of findGaps(input)) {
116
+ bars.push({
117
+ key: `g${gap.start}`,
118
+ kind: "gap",
119
+ // One level in: a gap is not a root-level event, it is time inside the
120
+ // request that nothing claimed.
121
+ depth: 1,
122
+ startedAt: gap.start,
123
+ duration: gap.end - gap.start,
124
+ span: null,
125
+ count: 1,
126
+ finding: null,
127
+ marks: [],
128
+ waitMs: 0
129
+ });
130
+ }
131
+ return bars.sort((a, b) => a.startedAt - b.startedAt);
132
+ }
133
+ function uninstrumentedMs(bars) {
134
+ let total = 0;
135
+ for (const bar of bars) {
136
+ if (bar.kind === "gap") total += bar.duration;
137
+ }
138
+ return total;
139
+ }
140
+ function parallelSpans(spans) {
141
+ const children = /* @__PURE__ */ new Map();
142
+ for (const span of spans) {
143
+ if (span.parentId === null) continue;
144
+ const list = children.get(span.parentId) ?? [];
145
+ list.push({ start: span.startedAt, end: span.startedAt + span.duration });
146
+ children.set(span.parentId, list);
147
+ }
148
+ const parallel = /* @__PURE__ */ new Set();
149
+ for (const [parentId, intervals] of children) {
150
+ const sorted = [...intervals].sort((a, b) => a.start - b.start);
151
+ for (let index = 1; index < sorted.length; index++) {
152
+ const previous = sorted[index - 1];
153
+ const current = sorted[index];
154
+ if (previous && current && current.start < previous.end) {
155
+ parallel.add(parentId);
156
+ break;
157
+ }
158
+ }
159
+ }
160
+ return parallel;
161
+ }
162
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * `@reqray/waterfall` — the shape of a request, before anybody draws it.\n *\n * Which spans become one bar, where the uninstrumented stretches are, how deep\n * each bar sits. Shared by the panel and the terminal client, so one request\n * cannot show a different number of bars depending on where it is read.\n *\n * Nothing about drawing: labels, colour, glyphs and bar cells stay with each\n * client, because a terminal has twenty-eight columns for a label and a\n * browser has an ellipsis. That is a difference between screens, not between\n * answers.\n *\n * Types only from `@reqray/protocol`, so this is safe in a browser bundle.\n */\n\nimport type { Finding, FindingEvidence, RecordedRequest, Span } from '@reqray/protocol';\n\n/** What a client needs to draw a waterfall: the record, plus its wall time. */\nexport type WaterfallInput = Pick<RecordedRequest, 'spans' | 'findings' | 'durationMs'>;\n\n/** One bar. `gap` is time no instrumentation covers. */\nexport interface WaterfallBar {\n /** Stable across rebuilds of the same request — usable as a list key. */\n readonly key: string;\n readonly kind: Span['kind'] | 'gap';\n readonly depth: number;\n /** Milliseconds from the start of the request. */\n readonly startedAt: number;\n readonly duration: number;\n /**\n * The span this bar stands for, or `null` for a gap.\n *\n * Handed over rather than reduced to a string: labelling is the client's,\n * and a model that decided it would be deciding for a terminal and a browser\n * at once.\n */\n readonly span: Span | null;\n /** How many spans collapsed into this bar. `1` for an ordinary span. */\n readonly count: number;\n /** Detector id when the bar is a collapsed run, `null` otherwise. */\n readonly finding: string | null;\n /** Detector ids that merely mark this span — duplicates, for instance. */\n readonly marks: readonly string[];\n /**\n * Milliseconds this span queued for a connection before it ran.\n *\n * Belongs on the bar rather than on a row of its own: the waterfall's job is\n * to show where the time went, and doubling the rows to say \"and it waited\"\n * makes that harder, not easier.\n */\n readonly waitMs: number;\n}\n\n/** Gaps shorter than this are noise, not an answer to \"where did time go\". */\nconst GAP_MIN_MS = 20;\nconst GAP_MIN_SHARE = 0.1;\n\n/** Deeper than this a chain is malformed; the walk stops rather than loops. */\nconst MAX_DEPTH = 32;\n\n/**\n * The detectors whose findings are a *run* of spans, which collapses into one\n * bar.\n *\n * A duplicate is not a run — its two calls sit far apart, and one bar spanning\n * them would swallow everything in between and claim the time as its own.\n */\nexport function isRunEvidence(evidence: FindingEvidence): boolean {\n return evidence.kind === 'n_plus_one' || evidence.kind === 'sequential_http';\n}\n\n/** How far down the span tree a span sits. */\nexport function depthOf(span: Span, byId: ReadonlyMap<number, Span>): number {\n let depth = 0;\n let parentId = span.parentId;\n while (parentId !== null && depth < MAX_DEPTH) {\n const parent = byId.get(parentId);\n if (!parent) break;\n depth++;\n parentId = parent.parentId;\n }\n return depth;\n}\n\n/**\n * Stretches of the request not covered by any instrumented work.\n *\n * A 600 ms request with one 2 ms query would otherwise show a full bar and no\n * explanation — the honest answer is a visible uninstrumented stretch:\n * application code, a timer, something Reqray has no instrumentation for.\n * Handler and middleware spans are containers, not work, so they do not count\n * as coverage.\n */\nexport function findGaps(input: WaterfallInput): Array<{ start: number; end: number }> {\n const total = input.durationMs;\n const threshold = Math.max(GAP_MIN_MS, total * GAP_MIN_SHARE);\n\n const intervals = input.spans\n .filter((span) => span.kind !== 'handler' && span.kind !== 'middleware')\n // A query's wait is covered time, not a gap: it is the one stretch of an\n // idle-looking request that is fully accounted for, and calling it\n // uninstrumented would hide the answer behind the word for \"no answer\".\n .map((span) => ({\n start: span.startedAt - (span.kind === 'db' ? (span.waitMs ?? 0) : 0),\n end: span.startedAt + span.duration,\n }))\n .sort((a, b) => a.start - b.start);\n\n const gaps: Array<{ start: number; end: number }> = [];\n let cursor = 0;\n for (const interval of intervals) {\n if (interval.start - cursor >= threshold) gaps.push({ start: cursor, end: interval.start });\n cursor = Math.max(cursor, interval.end);\n }\n if (total - cursor >= threshold) gaps.push({ start: cursor, end: total });\n return gaps;\n}\n\n/**\n * Builds the bars, in the order they start.\n *\n * Spans belonging to one run collapse into a single bar spanning the whole\n * run: forty-seven identical rows would be honest and unreadable, and the\n * point of the screen is to show where the time went.\n */\nexport function buildWaterfall(input: WaterfallInput): WaterfallBar[] {\n const byId = new Map(input.spans.map((span) => [span.id, span]));\n\n // Runs collapse into one bar; everything else only badges the spans it\n // names, so a duplicate two seconds apart does not draw a bar over\n // everything between its two calls.\n const grouped = new Map<number, Finding>();\n const marked = new Map<number, string[]>();\n for (const finding of input.findings) {\n for (const id of finding.evidence.spanIds) {\n if (isRunEvidence(finding.evidence)) grouped.set(id, finding);\n else marked.set(id, [...(marked.get(id) ?? []), finding.detector]);\n }\n }\n\n const bars: WaterfallBar[] = [];\n const emitted = new Set<Finding>();\n\n for (const span of input.spans) {\n const finding = grouped.get(span.id);\n\n if (!finding) {\n bars.push({\n key: `s${span.id}`,\n kind: span.kind,\n depth: depthOf(span, byId),\n startedAt: span.startedAt,\n duration: span.duration,\n span,\n count: 1,\n finding: null,\n marks: marked.get(span.id) ?? [],\n waitMs: span.kind === 'db' ? (span.waitMs ?? 0) : 0,\n });\n continue;\n }\n\n if (emitted.has(finding)) continue;\n emitted.add(finding);\n\n const members = finding.evidence.spanIds\n .map((id) => byId.get(id))\n .filter((member): member is Span => member !== undefined);\n if (members.length === 0) continue;\n\n const start = Math.min(...members.map((member) => member.startedAt));\n const end = Math.max(...members.map((member) => member.startedAt + member.duration));\n const fingerprint =\n 'fingerprint' in finding.evidence ? String(finding.evidence.fingerprint) : '';\n\n bars.push({\n key: `f${finding.detector}${fingerprint}`,\n kind: span.kind,\n depth: depthOf(span, byId),\n startedAt: start,\n duration: end - start,\n // The first of the run: what the group is *of*, which is what a label\n // needs. The count says how many there were.\n span,\n count: members.length,\n finding: finding.detector,\n marks: [],\n waitMs: 0,\n });\n }\n\n for (const gap of findGaps(input)) {\n bars.push({\n key: `g${gap.start}`,\n kind: 'gap',\n // One level in: a gap is not a root-level event, it is time inside the\n // request that nothing claimed.\n depth: 1,\n startedAt: gap.start,\n duration: gap.end - gap.start,\n span: null,\n count: 1,\n finding: null,\n marks: [],\n waitMs: 0,\n });\n }\n\n return bars.sort((a, b) => a.startedAt - b.startedAt);\n}\n\n/** Total uninstrumented time — what a waterfall header reports. */\nexport function uninstrumentedMs(bars: readonly WaterfallBar[]): number {\n let total = 0;\n for (const bar of bars) {\n if (bar.kind === 'gap') total += bar.duration;\n }\n return total;\n}\n\n/**\n * Spans whose children ran at the same time as one another.\n *\n * Worth marking wherever self time is shown: a span of 100 ms with 60 ms of\n * self time and four 40 ms children underneath looks like an arithmetic error\n * until you know the four ran together. Touching is not overlapping — one\n * query ending where the next begins is a loop, and calling that concurrency\n * would contradict what the N+1 detector says about the same spans.\n */\nexport function parallelSpans(spans: readonly Span[]): Set<number> {\n const children = new Map<number, Array<{ start: number; end: number }>>();\n for (const span of spans) {\n if (span.parentId === null) continue;\n const list = children.get(span.parentId) ?? [];\n list.push({ start: span.startedAt, end: span.startedAt + span.duration });\n children.set(span.parentId, list);\n }\n\n const parallel = new Set<number>();\n for (const [parentId, intervals] of children) {\n const sorted = [...intervals].sort((a, b) => a.start - b.start);\n for (let index = 1; index < sorted.length; index++) {\n const previous = sorted[index - 1];\n const current = sorted[index];\n if (previous && current && current.start < previous.end) {\n parallel.add(parentId);\n break;\n }\n }\n }\n return parallel;\n}\n"],"mappings":";;;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QAAM,WAAW,oBAAI,IAAY;AACjC,aAAW,CAAC,UAAU,SAAS,KAAK,UAAU;AAC5C,UAAM,SAAS,CAAC,GAAG,SAAS,EAAE,KAAK,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,KAAK;AAC9D,aAAS,QAAQ,GAAG,QAAQ,OAAO,QAAQ,SAAS;AAClD,YAAM,WAAW,OAAO,QAAQ,CAAC;AACjC,YAAM,UAAU,OAAO,KAAK;AAC5B,UAAI,YAAY,WAAW,QAAQ,QAAQ,SAAS,KAAK;AACvD,iBAAS,IAAI,QAAQ;AACrB;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
@@ -0,0 +1,96 @@
1
+ import { Span, RecordedRequest, FindingEvidence } from '@reqray/protocol';
2
+
3
+ /**
4
+ * `@reqray/waterfall` — the shape of a request, before anybody draws it.
5
+ *
6
+ * Which spans become one bar, where the uninstrumented stretches are, how deep
7
+ * each bar sits. Shared by the panel and the terminal client, so one request
8
+ * cannot show a different number of bars depending on where it is read.
9
+ *
10
+ * Nothing about drawing: labels, colour, glyphs and bar cells stay with each
11
+ * client, because a terminal has twenty-eight columns for a label and a
12
+ * browser has an ellipsis. That is a difference between screens, not between
13
+ * answers.
14
+ *
15
+ * Types only from `@reqray/protocol`, so this is safe in a browser bundle.
16
+ */
17
+
18
+ /** What a client needs to draw a waterfall: the record, plus its wall time. */
19
+ type WaterfallInput = Pick<RecordedRequest, 'spans' | 'findings' | 'durationMs'>;
20
+ /** One bar. `gap` is time no instrumentation covers. */
21
+ interface WaterfallBar {
22
+ /** Stable across rebuilds of the same request — usable as a list key. */
23
+ readonly key: string;
24
+ readonly kind: Span['kind'] | 'gap';
25
+ readonly depth: number;
26
+ /** Milliseconds from the start of the request. */
27
+ readonly startedAt: number;
28
+ readonly duration: number;
29
+ /**
30
+ * The span this bar stands for, or `null` for a gap.
31
+ *
32
+ * Handed over rather than reduced to a string: labelling is the client's,
33
+ * and a model that decided it would be deciding for a terminal and a browser
34
+ * at once.
35
+ */
36
+ readonly span: Span | null;
37
+ /** How many spans collapsed into this bar. `1` for an ordinary span. */
38
+ readonly count: number;
39
+ /** Detector id when the bar is a collapsed run, `null` otherwise. */
40
+ readonly finding: string | null;
41
+ /** Detector ids that merely mark this span — duplicates, for instance. */
42
+ readonly marks: readonly string[];
43
+ /**
44
+ * Milliseconds this span queued for a connection before it ran.
45
+ *
46
+ * Belongs on the bar rather than on a row of its own: the waterfall's job is
47
+ * to show where the time went, and doubling the rows to say "and it waited"
48
+ * makes that harder, not easier.
49
+ */
50
+ readonly waitMs: number;
51
+ }
52
+ /**
53
+ * The detectors whose findings are a *run* of spans, which collapses into one
54
+ * bar.
55
+ *
56
+ * A duplicate is not a run — its two calls sit far apart, and one bar spanning
57
+ * them would swallow everything in between and claim the time as its own.
58
+ */
59
+ declare function isRunEvidence(evidence: FindingEvidence): boolean;
60
+ /** How far down the span tree a span sits. */
61
+ declare function depthOf(span: Span, byId: ReadonlyMap<number, Span>): number;
62
+ /**
63
+ * Stretches of the request not covered by any instrumented work.
64
+ *
65
+ * A 600 ms request with one 2 ms query would otherwise show a full bar and no
66
+ * explanation — the honest answer is a visible uninstrumented stretch:
67
+ * application code, a timer, something Reqray has no instrumentation for.
68
+ * Handler and middleware spans are containers, not work, so they do not count
69
+ * as coverage.
70
+ */
71
+ declare function findGaps(input: WaterfallInput): Array<{
72
+ start: number;
73
+ end: number;
74
+ }>;
75
+ /**
76
+ * Builds the bars, in the order they start.
77
+ *
78
+ * Spans belonging to one run collapse into a single bar spanning the whole
79
+ * run: forty-seven identical rows would be honest and unreadable, and the
80
+ * point of the screen is to show where the time went.
81
+ */
82
+ declare function buildWaterfall(input: WaterfallInput): WaterfallBar[];
83
+ /** Total uninstrumented time — what a waterfall header reports. */
84
+ declare function uninstrumentedMs(bars: readonly WaterfallBar[]): number;
85
+ /**
86
+ * Spans whose children ran at the same time as one another.
87
+ *
88
+ * Worth marking wherever self time is shown: a span of 100 ms with 60 ms of
89
+ * self time and four 40 ms children underneath looks like an arithmetic error
90
+ * until you know the four ran together. Touching is not overlapping — one
91
+ * query ending where the next begins is a loop, and calling that concurrency
92
+ * would contradict what the N+1 detector says about the same spans.
93
+ */
94
+ declare function parallelSpans(spans: readonly Span[]): Set<number>;
95
+
96
+ export { type WaterfallBar, type WaterfallInput, buildWaterfall, depthOf, findGaps, isRunEvidence, parallelSpans, uninstrumentedMs };
@@ -0,0 +1,96 @@
1
+ import { Span, RecordedRequest, FindingEvidence } from '@reqray/protocol';
2
+
3
+ /**
4
+ * `@reqray/waterfall` — the shape of a request, before anybody draws it.
5
+ *
6
+ * Which spans become one bar, where the uninstrumented stretches are, how deep
7
+ * each bar sits. Shared by the panel and the terminal client, so one request
8
+ * cannot show a different number of bars depending on where it is read.
9
+ *
10
+ * Nothing about drawing: labels, colour, glyphs and bar cells stay with each
11
+ * client, because a terminal has twenty-eight columns for a label and a
12
+ * browser has an ellipsis. That is a difference between screens, not between
13
+ * answers.
14
+ *
15
+ * Types only from `@reqray/protocol`, so this is safe in a browser bundle.
16
+ */
17
+
18
+ /** What a client needs to draw a waterfall: the record, plus its wall time. */
19
+ type WaterfallInput = Pick<RecordedRequest, 'spans' | 'findings' | 'durationMs'>;
20
+ /** One bar. `gap` is time no instrumentation covers. */
21
+ interface WaterfallBar {
22
+ /** Stable across rebuilds of the same request — usable as a list key. */
23
+ readonly key: string;
24
+ readonly kind: Span['kind'] | 'gap';
25
+ readonly depth: number;
26
+ /** Milliseconds from the start of the request. */
27
+ readonly startedAt: number;
28
+ readonly duration: number;
29
+ /**
30
+ * The span this bar stands for, or `null` for a gap.
31
+ *
32
+ * Handed over rather than reduced to a string: labelling is the client's,
33
+ * and a model that decided it would be deciding for a terminal and a browser
34
+ * at once.
35
+ */
36
+ readonly span: Span | null;
37
+ /** How many spans collapsed into this bar. `1` for an ordinary span. */
38
+ readonly count: number;
39
+ /** Detector id when the bar is a collapsed run, `null` otherwise. */
40
+ readonly finding: string | null;
41
+ /** Detector ids that merely mark this span — duplicates, for instance. */
42
+ readonly marks: readonly string[];
43
+ /**
44
+ * Milliseconds this span queued for a connection before it ran.
45
+ *
46
+ * Belongs on the bar rather than on a row of its own: the waterfall's job is
47
+ * to show where the time went, and doubling the rows to say "and it waited"
48
+ * makes that harder, not easier.
49
+ */
50
+ readonly waitMs: number;
51
+ }
52
+ /**
53
+ * The detectors whose findings are a *run* of spans, which collapses into one
54
+ * bar.
55
+ *
56
+ * A duplicate is not a run — its two calls sit far apart, and one bar spanning
57
+ * them would swallow everything in between and claim the time as its own.
58
+ */
59
+ declare function isRunEvidence(evidence: FindingEvidence): boolean;
60
+ /** How far down the span tree a span sits. */
61
+ declare function depthOf(span: Span, byId: ReadonlyMap<number, Span>): number;
62
+ /**
63
+ * Stretches of the request not covered by any instrumented work.
64
+ *
65
+ * A 600 ms request with one 2 ms query would otherwise show a full bar and no
66
+ * explanation — the honest answer is a visible uninstrumented stretch:
67
+ * application code, a timer, something Reqray has no instrumentation for.
68
+ * Handler and middleware spans are containers, not work, so they do not count
69
+ * as coverage.
70
+ */
71
+ declare function findGaps(input: WaterfallInput): Array<{
72
+ start: number;
73
+ end: number;
74
+ }>;
75
+ /**
76
+ * Builds the bars, in the order they start.
77
+ *
78
+ * Spans belonging to one run collapse into a single bar spanning the whole
79
+ * run: forty-seven identical rows would be honest and unreadable, and the
80
+ * point of the screen is to show where the time went.
81
+ */
82
+ declare function buildWaterfall(input: WaterfallInput): WaterfallBar[];
83
+ /** Total uninstrumented time — what a waterfall header reports. */
84
+ declare function uninstrumentedMs(bars: readonly WaterfallBar[]): number;
85
+ /**
86
+ * Spans whose children ran at the same time as one another.
87
+ *
88
+ * Worth marking wherever self time is shown: a span of 100 ms with 60 ms of
89
+ * self time and four 40 ms children underneath looks like an arithmetic error
90
+ * until you know the four ran together. Touching is not overlapping — one
91
+ * query ending where the next begins is a loop, and calling that concurrency
92
+ * would contradict what the N+1 detector says about the same spans.
93
+ */
94
+ declare function parallelSpans(spans: readonly Span[]): Set<number>;
95
+
96
+ export { type WaterfallBar, type WaterfallInput, buildWaterfall, depthOf, findGaps, isRunEvidence, parallelSpans, uninstrumentedMs };
package/dist/index.js ADDED
@@ -0,0 +1,141 @@
1
+ // src/index.ts
2
+ var GAP_MIN_MS = 20;
3
+ var GAP_MIN_SHARE = 0.1;
4
+ var MAX_DEPTH = 32;
5
+ function isRunEvidence(evidence) {
6
+ return evidence.kind === "n_plus_one" || evidence.kind === "sequential_http";
7
+ }
8
+ function depthOf(span, byId) {
9
+ let depth = 0;
10
+ let parentId = span.parentId;
11
+ while (parentId !== null && depth < MAX_DEPTH) {
12
+ const parent = byId.get(parentId);
13
+ if (!parent) break;
14
+ depth++;
15
+ parentId = parent.parentId;
16
+ }
17
+ return depth;
18
+ }
19
+ function findGaps(input) {
20
+ const total = input.durationMs;
21
+ const threshold = Math.max(GAP_MIN_MS, total * GAP_MIN_SHARE);
22
+ const intervals = input.spans.filter((span) => span.kind !== "handler" && span.kind !== "middleware").map((span) => ({
23
+ start: span.startedAt - (span.kind === "db" ? span.waitMs ?? 0 : 0),
24
+ end: span.startedAt + span.duration
25
+ })).sort((a, b) => a.start - b.start);
26
+ const gaps = [];
27
+ let cursor = 0;
28
+ for (const interval of intervals) {
29
+ if (interval.start - cursor >= threshold) gaps.push({ start: cursor, end: interval.start });
30
+ cursor = Math.max(cursor, interval.end);
31
+ }
32
+ if (total - cursor >= threshold) gaps.push({ start: cursor, end: total });
33
+ return gaps;
34
+ }
35
+ function buildWaterfall(input) {
36
+ const byId = new Map(input.spans.map((span) => [span.id, span]));
37
+ const grouped = /* @__PURE__ */ new Map();
38
+ const marked = /* @__PURE__ */ new Map();
39
+ for (const finding of input.findings) {
40
+ for (const id of finding.evidence.spanIds) {
41
+ if (isRunEvidence(finding.evidence)) grouped.set(id, finding);
42
+ else marked.set(id, [...marked.get(id) ?? [], finding.detector]);
43
+ }
44
+ }
45
+ const bars = [];
46
+ const emitted = /* @__PURE__ */ new Set();
47
+ for (const span of input.spans) {
48
+ const finding = grouped.get(span.id);
49
+ if (!finding) {
50
+ bars.push({
51
+ key: `s${span.id}`,
52
+ kind: span.kind,
53
+ depth: depthOf(span, byId),
54
+ startedAt: span.startedAt,
55
+ duration: span.duration,
56
+ span,
57
+ count: 1,
58
+ finding: null,
59
+ marks: marked.get(span.id) ?? [],
60
+ waitMs: span.kind === "db" ? span.waitMs ?? 0 : 0
61
+ });
62
+ continue;
63
+ }
64
+ if (emitted.has(finding)) continue;
65
+ emitted.add(finding);
66
+ const members = finding.evidence.spanIds.map((id) => byId.get(id)).filter((member) => member !== void 0);
67
+ if (members.length === 0) continue;
68
+ const start = Math.min(...members.map((member) => member.startedAt));
69
+ const end = Math.max(...members.map((member) => member.startedAt + member.duration));
70
+ const fingerprint = "fingerprint" in finding.evidence ? String(finding.evidence.fingerprint) : "";
71
+ bars.push({
72
+ key: `f${finding.detector}${fingerprint}`,
73
+ kind: span.kind,
74
+ depth: depthOf(span, byId),
75
+ startedAt: start,
76
+ duration: end - start,
77
+ // The first of the run: what the group is *of*, which is what a label
78
+ // needs. The count says how many there were.
79
+ span,
80
+ count: members.length,
81
+ finding: finding.detector,
82
+ marks: [],
83
+ waitMs: 0
84
+ });
85
+ }
86
+ for (const gap of findGaps(input)) {
87
+ bars.push({
88
+ key: `g${gap.start}`,
89
+ kind: "gap",
90
+ // One level in: a gap is not a root-level event, it is time inside the
91
+ // request that nothing claimed.
92
+ depth: 1,
93
+ startedAt: gap.start,
94
+ duration: gap.end - gap.start,
95
+ span: null,
96
+ count: 1,
97
+ finding: null,
98
+ marks: [],
99
+ waitMs: 0
100
+ });
101
+ }
102
+ return bars.sort((a, b) => a.startedAt - b.startedAt);
103
+ }
104
+ function uninstrumentedMs(bars) {
105
+ let total = 0;
106
+ for (const bar of bars) {
107
+ if (bar.kind === "gap") total += bar.duration;
108
+ }
109
+ return total;
110
+ }
111
+ function parallelSpans(spans) {
112
+ const children = /* @__PURE__ */ new Map();
113
+ for (const span of spans) {
114
+ if (span.parentId === null) continue;
115
+ const list = children.get(span.parentId) ?? [];
116
+ list.push({ start: span.startedAt, end: span.startedAt + span.duration });
117
+ children.set(span.parentId, list);
118
+ }
119
+ const parallel = /* @__PURE__ */ new Set();
120
+ for (const [parentId, intervals] of children) {
121
+ const sorted = [...intervals].sort((a, b) => a.start - b.start);
122
+ for (let index = 1; index < sorted.length; index++) {
123
+ const previous = sorted[index - 1];
124
+ const current = sorted[index];
125
+ if (previous && current && current.start < previous.end) {
126
+ parallel.add(parentId);
127
+ break;
128
+ }
129
+ }
130
+ }
131
+ return parallel;
132
+ }
133
+ export {
134
+ buildWaterfall,
135
+ depthOf,
136
+ findGaps,
137
+ isRunEvidence,
138
+ parallelSpans,
139
+ uninstrumentedMs
140
+ };
141
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * `@reqray/waterfall` — the shape of a request, before anybody draws it.\n *\n * Which spans become one bar, where the uninstrumented stretches are, how deep\n * each bar sits. Shared by the panel and the terminal client, so one request\n * cannot show a different number of bars depending on where it is read.\n *\n * Nothing about drawing: labels, colour, glyphs and bar cells stay with each\n * client, because a terminal has twenty-eight columns for a label and a\n * browser has an ellipsis. That is a difference between screens, not between\n * answers.\n *\n * Types only from `@reqray/protocol`, so this is safe in a browser bundle.\n */\n\nimport type { Finding, FindingEvidence, RecordedRequest, Span } from '@reqray/protocol';\n\n/** What a client needs to draw a waterfall: the record, plus its wall time. */\nexport type WaterfallInput = Pick<RecordedRequest, 'spans' | 'findings' | 'durationMs'>;\n\n/** One bar. `gap` is time no instrumentation covers. */\nexport interface WaterfallBar {\n /** Stable across rebuilds of the same request — usable as a list key. */\n readonly key: string;\n readonly kind: Span['kind'] | 'gap';\n readonly depth: number;\n /** Milliseconds from the start of the request. */\n readonly startedAt: number;\n readonly duration: number;\n /**\n * The span this bar stands for, or `null` for a gap.\n *\n * Handed over rather than reduced to a string: labelling is the client's,\n * and a model that decided it would be deciding for a terminal and a browser\n * at once.\n */\n readonly span: Span | null;\n /** How many spans collapsed into this bar. `1` for an ordinary span. */\n readonly count: number;\n /** Detector id when the bar is a collapsed run, `null` otherwise. */\n readonly finding: string | null;\n /** Detector ids that merely mark this span — duplicates, for instance. */\n readonly marks: readonly string[];\n /**\n * Milliseconds this span queued for a connection before it ran.\n *\n * Belongs on the bar rather than on a row of its own: the waterfall's job is\n * to show where the time went, and doubling the rows to say \"and it waited\"\n * makes that harder, not easier.\n */\n readonly waitMs: number;\n}\n\n/** Gaps shorter than this are noise, not an answer to \"where did time go\". */\nconst GAP_MIN_MS = 20;\nconst GAP_MIN_SHARE = 0.1;\n\n/** Deeper than this a chain is malformed; the walk stops rather than loops. */\nconst MAX_DEPTH = 32;\n\n/**\n * The detectors whose findings are a *run* of spans, which collapses into one\n * bar.\n *\n * A duplicate is not a run — its two calls sit far apart, and one bar spanning\n * them would swallow everything in between and claim the time as its own.\n */\nexport function isRunEvidence(evidence: FindingEvidence): boolean {\n return evidence.kind === 'n_plus_one' || evidence.kind === 'sequential_http';\n}\n\n/** How far down the span tree a span sits. */\nexport function depthOf(span: Span, byId: ReadonlyMap<number, Span>): number {\n let depth = 0;\n let parentId = span.parentId;\n while (parentId !== null && depth < MAX_DEPTH) {\n const parent = byId.get(parentId);\n if (!parent) break;\n depth++;\n parentId = parent.parentId;\n }\n return depth;\n}\n\n/**\n * Stretches of the request not covered by any instrumented work.\n *\n * A 600 ms request with one 2 ms query would otherwise show a full bar and no\n * explanation — the honest answer is a visible uninstrumented stretch:\n * application code, a timer, something Reqray has no instrumentation for.\n * Handler and middleware spans are containers, not work, so they do not count\n * as coverage.\n */\nexport function findGaps(input: WaterfallInput): Array<{ start: number; end: number }> {\n const total = input.durationMs;\n const threshold = Math.max(GAP_MIN_MS, total * GAP_MIN_SHARE);\n\n const intervals = input.spans\n .filter((span) => span.kind !== 'handler' && span.kind !== 'middleware')\n // A query's wait is covered time, not a gap: it is the one stretch of an\n // idle-looking request that is fully accounted for, and calling it\n // uninstrumented would hide the answer behind the word for \"no answer\".\n .map((span) => ({\n start: span.startedAt - (span.kind === 'db' ? (span.waitMs ?? 0) : 0),\n end: span.startedAt + span.duration,\n }))\n .sort((a, b) => a.start - b.start);\n\n const gaps: Array<{ start: number; end: number }> = [];\n let cursor = 0;\n for (const interval of intervals) {\n if (interval.start - cursor >= threshold) gaps.push({ start: cursor, end: interval.start });\n cursor = Math.max(cursor, interval.end);\n }\n if (total - cursor >= threshold) gaps.push({ start: cursor, end: total });\n return gaps;\n}\n\n/**\n * Builds the bars, in the order they start.\n *\n * Spans belonging to one run collapse into a single bar spanning the whole\n * run: forty-seven identical rows would be honest and unreadable, and the\n * point of the screen is to show where the time went.\n */\nexport function buildWaterfall(input: WaterfallInput): WaterfallBar[] {\n const byId = new Map(input.spans.map((span) => [span.id, span]));\n\n // Runs collapse into one bar; everything else only badges the spans it\n // names, so a duplicate two seconds apart does not draw a bar over\n // everything between its two calls.\n const grouped = new Map<number, Finding>();\n const marked = new Map<number, string[]>();\n for (const finding of input.findings) {\n for (const id of finding.evidence.spanIds) {\n if (isRunEvidence(finding.evidence)) grouped.set(id, finding);\n else marked.set(id, [...(marked.get(id) ?? []), finding.detector]);\n }\n }\n\n const bars: WaterfallBar[] = [];\n const emitted = new Set<Finding>();\n\n for (const span of input.spans) {\n const finding = grouped.get(span.id);\n\n if (!finding) {\n bars.push({\n key: `s${span.id}`,\n kind: span.kind,\n depth: depthOf(span, byId),\n startedAt: span.startedAt,\n duration: span.duration,\n span,\n count: 1,\n finding: null,\n marks: marked.get(span.id) ?? [],\n waitMs: span.kind === 'db' ? (span.waitMs ?? 0) : 0,\n });\n continue;\n }\n\n if (emitted.has(finding)) continue;\n emitted.add(finding);\n\n const members = finding.evidence.spanIds\n .map((id) => byId.get(id))\n .filter((member): member is Span => member !== undefined);\n if (members.length === 0) continue;\n\n const start = Math.min(...members.map((member) => member.startedAt));\n const end = Math.max(...members.map((member) => member.startedAt + member.duration));\n const fingerprint =\n 'fingerprint' in finding.evidence ? String(finding.evidence.fingerprint) : '';\n\n bars.push({\n key: `f${finding.detector}${fingerprint}`,\n kind: span.kind,\n depth: depthOf(span, byId),\n startedAt: start,\n duration: end - start,\n // The first of the run: what the group is *of*, which is what a label\n // needs. The count says how many there were.\n span,\n count: members.length,\n finding: finding.detector,\n marks: [],\n waitMs: 0,\n });\n }\n\n for (const gap of findGaps(input)) {\n bars.push({\n key: `g${gap.start}`,\n kind: 'gap',\n // One level in: a gap is not a root-level event, it is time inside the\n // request that nothing claimed.\n depth: 1,\n startedAt: gap.start,\n duration: gap.end - gap.start,\n span: null,\n count: 1,\n finding: null,\n marks: [],\n waitMs: 0,\n });\n }\n\n return bars.sort((a, b) => a.startedAt - b.startedAt);\n}\n\n/** Total uninstrumented time — what a waterfall header reports. */\nexport function uninstrumentedMs(bars: readonly WaterfallBar[]): number {\n let total = 0;\n for (const bar of bars) {\n if (bar.kind === 'gap') total += bar.duration;\n }\n return total;\n}\n\n/**\n * Spans whose children ran at the same time as one another.\n *\n * Worth marking wherever self time is shown: a span of 100 ms with 60 ms of\n * self time and four 40 ms children underneath looks like an arithmetic error\n * until you know the four ran together. Touching is not overlapping — one\n * query ending where the next begins is a loop, and calling that concurrency\n * would contradict what the N+1 detector says about the same spans.\n */\nexport function parallelSpans(spans: readonly Span[]): Set<number> {\n const children = new Map<number, Array<{ start: number; end: number }>>();\n for (const span of spans) {\n if (span.parentId === null) continue;\n const list = children.get(span.parentId) ?? [];\n list.push({ start: span.startedAt, end: span.startedAt + span.duration });\n children.set(span.parentId, list);\n }\n\n const parallel = new Set<number>();\n for (const [parentId, intervals] of children) {\n const sorted = [...intervals].sort((a, b) => a.start - b.start);\n for (let index = 1; index < sorted.length; index++) {\n const previous = sorted[index - 1];\n const current = sorted[index];\n if (previous && current && current.start < previous.end) {\n parallel.add(parentId);\n break;\n }\n }\n }\n return parallel;\n}\n"],"mappings":";AAsDA,IAAM,aAAa;AACnB,IAAM,g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AK,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,KAAK;AAC9D,aAAS,QAAQ,GAAG,QAAQ,OAAO,QAAQ,SAAS;AAClD,YAAM,WAAW,OAAO,QAAQ,CAAC;AACjC,YAAM,UAAU,OAAO,KAAK;AAC5B,UAAI,YAAY,WAAW,QAAQ,QAAQ,SAAS,KAAK;AACvD,iBAAS,IAAI,QAAQ;AACrB;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@reqray/waterfall",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "The waterfall model, shared by every client that draws one: which spans collapse, where the uninstrumented time is, how deep each bar sits.",
5
+ "license": "MIT",
6
+ "keywords": [
7
+ "nodejs",
8
+ "debugging",
9
+ "profiling",
10
+ "n+1",
11
+ "sql",
12
+ "observability",
13
+ "devtools",
14
+ "fastify",
15
+ "express",
16
+ "nestjs"
17
+ ],
18
+ "homepage": "https://github.com/reqray/reqray#readme",
19
+ "bugs": "https://github.com/reqray/reqray/issues",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/reqray/reqray.git",
23
+ "directory": "packages/waterfall"
24
+ },
25
+ "type": "module",
26
+ "engines": {
27
+ "node": ">=20"
28
+ },
29
+ "exports": {
30
+ ".": {
31
+ "import": {
32
+ "types": "./dist/index.d.ts",
33
+ "default": "./dist/index.js"
34
+ },
35
+ "require": {
36
+ "types": "./dist/index.d.cts",
37
+ "default": "./dist/index.cjs"
38
+ }
39
+ }
40
+ },
41
+ "main": "./dist/index.cjs",
42
+ "module": "./dist/index.js",
43
+ "types": "./dist/index.d.ts",
44
+ "files": [
45
+ "dist"
46
+ ],
47
+ "publishConfig": {
48
+ "access": "public"
49
+ },
50
+ "dependencies": {
51
+ "@reqray/protocol": "^0.1.1"
52
+ },
53
+ "devDependencies": {
54
+ "@types/node": "^26.2.0",
55
+ "tsup": "^8.5.1",
56
+ "typescript": "^6.0.3"
57
+ },
58
+ "scripts": {
59
+ "build": "tsup",
60
+ "typecheck": "tsc --noEmit"
61
+ }
6
62
  }