@nestjs/observe 0.1.10 → 0.2.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.
@@ -0,0 +1,216 @@
1
+ /**
2
+ * Tag under which a collapsed node records how many calls it stands for.
3
+ *
4
+ * A tag rather than a field of its own so the wire format does not change:
5
+ * `tags` is already on every span and already declared by the collector's
6
+ * contract, so an agent emitting this needs no matching collector release. A
7
+ * collector that does not know the tag stores it like any other and
8
+ * attributes the node as one call; one that does reads the true count here.
9
+ * Namespaced so it reads as the agent's in a span's tag list, and safe from
10
+ * collision: the node it sits on never exists at runtime, so no user code can
11
+ * set tags on it, and the tags of the calls it replaces are dropped.
12
+ *
13
+ * Absent on an ordinary span, which stands for exactly one call. On a node
14
+ * that carries it, `duration` is the *sum* of the replaced calls' durations,
15
+ * `startOffset` and `spanId` are the earliest call's, and `children` holds
16
+ * every child the replaced calls had - which is what keeps the parent's self
17
+ * time and the subtree's class attribution exactly what they were. Ordering
18
+ * among the replaced calls is lost. The node is one event on the wire and is
19
+ * metered as one.
20
+ */
21
+ export const SPAN_COLLAPSED_TAG = "observe.collapsed";
22
+ /**
23
+ * Twenty is above what a hand-written method produces under one parent - a
24
+ * handler calling a repository a dozen times in a loop is still shipped
25
+ * whole - and far below the hundreds a framework hook like `ValidationPipe`
26
+ * produces per GraphQL list query. Three kept instances is enough to show the
27
+ * spread between the slowest calls without the tail of identical ones behind
28
+ * them.
29
+ */
30
+ export const DEFAULT_SPAN_COLLAPSE = {
31
+ threshold: 20,
32
+ keepSlowest: 3,
33
+ };
34
+ /**
35
+ * Turns the user-facing option into settings the registry can apply, or
36
+ * `undefined` when collapsing is switched off. Unusable values - a negative
37
+ * count, a fraction, `NaN` - fall back to the default for that field rather
38
+ * than disabling the feature: an option typo should not silently reopen the
39
+ * span flood this exists to stop.
40
+ */
41
+ export function resolveSpanCollapseSettings(option) {
42
+ if (option === false) {
43
+ return undefined;
44
+ }
45
+ return {
46
+ threshold: toInteger(option?.threshold, 1, DEFAULT_SPAN_COLLAPSE.threshold),
47
+ keepSlowest: toInteger(option?.keepSlowest, 0, DEFAULT_SPAN_COLLAPSE.keepSlowest),
48
+ };
49
+ }
50
+ function toInteger(value, min, fallback) {
51
+ return typeof value === "number" && Number.isInteger(value) && value >= min
52
+ ? value
53
+ : fallback;
54
+ }
55
+ /**
56
+ * Collapses repeated siblings throughout a completed span tree, in place.
57
+ *
58
+ * Within one list of siblings, auto spans are grouped by `className` and
59
+ * `methodKey`. A group larger than `threshold` keeps its `keepSlowest`
60
+ * longest-running members and every member that errored as ordinary spans;
61
+ * the rest are replaced by one node that records how many calls it stands
62
+ * for (`SPAN_COLLAPSED_TAG`) and the sum of their durations. Manual spans are never collapsed - a
63
+ * user named each of them deliberately - and ongoing nodes, which a shipped
64
+ * tree should not contain, are left alone.
65
+ *
66
+ * Summing the durations, rather than taking the wall-clock envelope, is what
67
+ * keeps the collector's self-time partition exact: a parent's self time is its
68
+ * duration minus the durations of its children, and the sum over the surviving
69
+ * children is the same as it was over the originals. The collapsed calls'
70
+ * own children are carried across onto the collapsed node for the same reason
71
+ * one level down, and then collapsed among themselves in turn - a repeated
72
+ * frame that always calls the same repeated frame collapses at both levels.
73
+ *
74
+ * Siblings are matched wherever they sit in the list, not only when adjacent:
75
+ * a pipe run once per argument interleaves with the resolver calls it
76
+ * validates for. The collapsed node takes the position of the earliest call
77
+ * it replaces, so ordering relative to the *other* siblings is kept; ordering
78
+ * among the collapsed calls themselves is lost.
79
+ *
80
+ * Returns the new sibling list for the level passed in. Descendant lists are
81
+ * rewritten through their parents' `children`.
82
+ */
83
+ export function collapseRepeatedSpans(siblings, settings) {
84
+ const collapsed = collapseSiblings(siblings, settings);
85
+ for (const node of collapsed) {
86
+ if (Array.isArray(node.children) && node.children.length > 0) {
87
+ const children = collapseRepeatedSpans(node.children, settings);
88
+ if (children.length > 0) {
89
+ node.children = children;
90
+ }
91
+ else {
92
+ // Same shape a leaf has when the registry completes it.
93
+ delete node.children;
94
+ }
95
+ }
96
+ }
97
+ return collapsed;
98
+ }
99
+ function collapseSiblings(siblings, settings) {
100
+ if (siblings.length <= settings.threshold) {
101
+ return siblings;
102
+ }
103
+ const groups = new Map();
104
+ for (const node of siblings) {
105
+ if (!isCollapsible(node)) {
106
+ continue;
107
+ }
108
+ // A separator no identifier contains, so `A.b` + `c` and `A` + `b.c`
109
+ // cannot share a key.
110
+ const key = `${node.className}\0${node.methodKey}`;
111
+ const group = groups.get(key);
112
+ if (group) {
113
+ group.push(node);
114
+ }
115
+ else {
116
+ groups.set(key, [node]);
117
+ }
118
+ }
119
+ // Which node each collapsed call is replaced by: the earliest call maps to
120
+ // the collapsed node, the others to nothing.
121
+ const replacements = new Map();
122
+ const removed = new Set();
123
+ for (const group of groups.values()) {
124
+ if (group.length <= settings.threshold) {
125
+ continue;
126
+ }
127
+ const candidates = group
128
+ .filter((node) => !node.error)
129
+ .sort((a, b) => b.duration - a.duration);
130
+ const surplus = candidates.slice(settings.keepSlowest);
131
+ // A node standing for a single call would be a relabelled span, not an
132
+ // aggregate.
133
+ if (surplus.length < 2) {
134
+ continue;
135
+ }
136
+ const earliest = surplus.reduce((first, node) => compareStart(node, first, siblings) < 0 ? node : first);
137
+ replacements.set(earliest, toCollapsedNode(surplus, earliest));
138
+ for (const node of surplus) {
139
+ if (node !== earliest) {
140
+ removed.add(node);
141
+ }
142
+ }
143
+ }
144
+ if (replacements.size === 0) {
145
+ return siblings;
146
+ }
147
+ const result = [];
148
+ for (const node of siblings) {
149
+ if (removed.has(node)) {
150
+ continue;
151
+ }
152
+ result.push(replacements.get(node) ?? node);
153
+ }
154
+ return result;
155
+ }
156
+ /**
157
+ * Earlier of two calls. `startOffset` is the trace clock and decides; nodes
158
+ * with no offset (an older snapshot, or a span opened after its trace ended)
159
+ * fall back to their position in the sibling list, which is insertion order
160
+ * and therefore start order as well.
161
+ */
162
+ function compareStart(a, b, siblings) {
163
+ if (typeof a.startOffset === "number" && typeof b.startOffset === "number") {
164
+ return a.startOffset - b.startOffset;
165
+ }
166
+ return siblings.indexOf(a) - siblings.indexOf(b);
167
+ }
168
+ function toCollapsedNode(surplus, earliest) {
169
+ let duration = 0;
170
+ let startOffset;
171
+ const children = [];
172
+ for (const node of surplus) {
173
+ duration += node.duration;
174
+ if (typeof node.startOffset === "number" &&
175
+ (startOffset === undefined || node.startOffset < startOffset)) {
176
+ startOffset = node.startOffset;
177
+ }
178
+ if (Array.isArray(node.children)) {
179
+ children.push(...node.children);
180
+ }
181
+ }
182
+ const collapsed = {
183
+ origin: "auto",
184
+ className: earliest.className,
185
+ methodKey: earliest.methodKey,
186
+ // Reads as an aggregate in a waterfall rather than as one more call.
187
+ name: `${earliest.className}.${earliest.methodKey} ×${surplus.length}`,
188
+ tags: { [SPAN_COLLAPSED_TAG]: surplus.length },
189
+ duration,
190
+ children,
191
+ };
192
+ if (startOffset !== undefined) {
193
+ collapsed.startOffset = startOffset;
194
+ }
195
+ if (earliest.spanId !== undefined) {
196
+ // A log line written inside the earliest call still resolves to a node.
197
+ // Lines written inside the other collapsed calls resolve to nothing, as
198
+ // they would for any span that was not shipped.
199
+ collapsed.spanId = earliest.spanId;
200
+ }
201
+ if (children.length === 0) {
202
+ delete collapsed.children;
203
+ }
204
+ return collapsed;
205
+ }
206
+ /**
207
+ * Only completed auto spans collapse. `type` is what marks a node as still
208
+ * ongoing; the registry deletes it on completion.
209
+ */
210
+ function isCollapsible(node) {
211
+ return (!("type" in node) &&
212
+ node.origin === "auto" &&
213
+ typeof node.className === "string" &&
214
+ typeof node.methodKey === "string" &&
215
+ typeof node.duration === "number");
216
+ }
@@ -1 +1,2 @@
1
1
  export * from "./tracer.service.js";
2
+ export { SPAN_COLLAPSED_TAG } from "./collapse-repeated-spans.util.js";
@@ -1 +1,2 @@
1
1
  export * from "./tracer.service.js";
2
+ export { SPAN_COLLAPSED_TAG } from "./collapse-repeated-spans.util.js";
@@ -7,6 +7,7 @@ import { OngoingTraceEventNode } from "../interfaces/trace-events.interfaces.js"
7
7
  import { TraceSpanDelegate } from "../trace-span.delegate.js";
8
8
  import { KeyOf } from "../types/key-of.type.js";
9
9
  import { CALLER_METADATA_KEY } from "../observe.constants.js";
10
+ import { SpanCollapseSettings } from "./collapse-repeated-spans.util.js";
10
11
  type TraceId = string;
11
12
  export declare class OperationTraceRegistry {
12
13
  private readonly als;
@@ -20,9 +21,22 @@ export declare class OperationTraceRegistry {
20
21
  * would bury everything else in the log. Full text once, one line after.
21
22
  */
22
23
  private hasReportedMissingInstrumentation;
24
+ /**
25
+ * Applied to every tree as it is plucked. Defaults are live from
26
+ * construction rather than waiting for `configureSpanCollapse`, so a
27
+ * registry the module has not (yet) configured still bounds what it ships.
28
+ */
29
+ private spanCollapse;
23
30
  constructor(als: AsyncLocalStorage<Map<KeyOf<{
24
31
  [CALLER_METADATA_KEY]: string;
25
32
  }>, unknown>>, sourceContext?: CreateObserveModuleOptions["sourceContext"]);
33
+ /**
34
+ * Sets how repeated siblings are collapsed on the way out, or switches it
35
+ * off with `undefined`. Called by the module once `ObserveOptions` have
36
+ * resolved, which is after this instance exists: the registry is built
37
+ * before the DI container so the instrumentation hook can hold it.
38
+ */
39
+ configureSpanCollapse(settings: SpanCollapseSettings | undefined): void;
26
40
  /**
27
41
  * Builds the error payload attached to a span or snapshot, including the source
28
42
  * around each in-app frame when source context is enabled.
@@ -4,6 +4,7 @@ import { uuidv7 } from "../utils/uuid-v7.util.js";
4
4
  import { TraceSpanDelegate } from "../trace-span.delegate.js";
5
5
  import { collectCodeFrames } from "../utils/source-context.util.js";
6
6
  import { CALLER_METADATA_KEY } from "../observe.constants.js";
7
+ import { collapseRepeatedSpans, DEFAULT_SPAN_COLLAPSE, } from "./collapse-repeated-spans.util.js";
7
8
  const SNAPSHOT_COMPLETION_TIMEOUT_MS = 1000;
8
9
  /**
9
10
  * An error the business logic did not model. `IntrinsicException` is what Nest
@@ -30,10 +31,25 @@ export class OperationTraceRegistry {
30
31
  * would bury everything else in the log. Full text once, one line after.
31
32
  */
32
33
  hasReportedMissingInstrumentation = false;
34
+ /**
35
+ * Applied to every tree as it is plucked. Defaults are live from
36
+ * construction rather than waiting for `configureSpanCollapse`, so a
37
+ * registry the module has not (yet) configured still bounds what it ships.
38
+ */
39
+ spanCollapse = DEFAULT_SPAN_COLLAPSE;
33
40
  constructor(als, sourceContext = true) {
34
41
  this.als = als;
35
42
  this.sourceContext = sourceContext;
36
43
  }
44
+ /**
45
+ * Sets how repeated siblings are collapsed on the way out, or switches it
46
+ * off with `undefined`. Called by the module once `ObserveOptions` have
47
+ * resolved, which is after this instance exists: the registry is built
48
+ * before the DI container so the instrumentation hook can hold it.
49
+ */
50
+ configureSpanCollapse(settings) {
51
+ this.spanCollapse = settings;
52
+ }
37
53
  /**
38
54
  * Builds the error payload attached to a span or snapshot, including the source
39
55
  * around each in-app frame when source context is enabled.
@@ -432,6 +448,13 @@ export class OperationTraceRegistry {
432
448
  delete bookkeeping.refsCounter;
433
449
  delete bookkeeping.refsMarkedAsComplete;
434
450
  delete bookkeeping.errorStatusCode;
451
+ // Last, on the finished tree: every span has closed by now, so a group
452
+ // is judged on its complete membership and durations, and nothing that
453
+ // reads the tree afterwards - the encoder, the buffer - sees the
454
+ // uncollapsed one.
455
+ if (this.spanCollapse) {
456
+ snapshot.traces = collapseRepeatedSpans(snapshot.traces, this.spanCollapse);
457
+ }
435
458
  return snapshot;
436
459
  }
437
460
  return undefined;
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@nestjs/observe",
3
- "version": "0.1.10",
3
+ "version": "0.2.1",
4
4
  "description": "Observability and APM agent for NestJS - traces, runtime metrics, custom metrics and CPU profiles",
5
5
  "author": "Kamil Mysliwiec",
6
- "homepage": "https://nestjs.com",
6
+ "homepage": "https://observe.nestjs.com",
7
7
  "repository": {
8
8
  "type": "git",
9
9
  "url": "git+https://github.com/nestjs/observe.git"
@@ -20,7 +20,13 @@
20
20
  "telemetry",
21
21
  "metrics",
22
22
  "profiling",
23
- "instrumentation"
23
+ "instrumentation",
24
+ "monitoring",
25
+ "opentelemetry",
26
+ "distributed-tracing",
27
+ "error-tracking",
28
+ "logging",
29
+ "performance"
24
30
  ],
25
31
  "main": "./dist/index.js",
26
32
  "types": "./dist/index.d.ts",