@nestjs/observe 0.1.9 → 0.2.0

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.
@@ -1,2 +1,3 @@
1
1
  import type { createTelemetrySanitizer } from "./telemetry-wire-contract.js";
2
- export declare const detachedObserveWorker: (createSanitizer?: typeof createTelemetrySanitizer) => void;
2
+ import type { describeIngestRefusal } from "../utils/ingest-refusal.util.js";
3
+ export declare const detachedObserveWorker: (createSanitizer?: typeof createTelemetrySanitizer, describeRefusal?: typeof describeIngestRefusal) => void;
@@ -3,7 +3,11 @@ export const detachedObserveWorker = (
3
3
  // is assembled (see `ObserveAgentWorker.initializeWorker`) - a stringified
4
4
  // function cannot import it. Type-only import above; a value import would
5
5
  // compile and then throw inside the worker.
6
- createSanitizer) => {
6
+ createSanitizer,
7
+ // Same arrangement: the helper that turns a 429 body into a sentence
8
+ // travels as source. Optional so a worker assembled without it still
9
+ // reports the refusal, just without the reason.
10
+ describeRefusal) => {
7
11
  // This function body is stringified via .toString() and executed as a
8
12
  // standalone worker script, so it can't use static ES imports and must
9
13
  // require() its dependencies at runtime instead.
@@ -254,10 +258,19 @@ createSanitizer) => {
254
258
  if (response.status === 429) {
255
259
  const pauseMs = rateLimitPauseMs(response);
256
260
  rateLimitedUntil = Date.now() + pauseMs;
261
+ // The body says which refusal this is - a quota, a quota frozen by
262
+ // a declined payment, or a rate cap - and each needs a different
263
+ // fix from the operator. Parsed defensively: a rate-cap body is
264
+ // not the quota shape and an older collector sends none at all,
265
+ // and neither may turn a refusal into an "unreachable" report.
266
+ const body = await response.json().catch(() => undefined);
267
+ const why = typeof describeRefusal === "function"
268
+ ? describeRefusal(body)
269
+ : "the account may be out of credits or over budget";
257
270
  // One line per pause window, so a long depletion reads as one line
258
271
  // every few minutes rather than one per flush. The batch is dropped
259
272
  // - `finally` clears the buffer - same as every other failure here.
260
- parentPort.postMessage(`Error: Telemetry rate-limited (429) - the account may be out of credits or over budget. ` +
273
+ parentPort.postMessage(`Error: Telemetry rate-limited (429) - ${why}. ` +
261
274
  `Pausing sends for ${Math.round(pauseMs / 60000)} minute(s); batches in the meantime are dropped.`);
262
275
  return true;
263
276
  }
@@ -19,6 +19,7 @@ import { CpuProfilerService } from "../profiling/cpu-profiler.service.js";
19
19
  import { ProfileUploader } from "../profiling/profile-uploader.js";
20
20
  import { setActiveSliceRecorder, SpanSliceRecorder, } from "../profiling/span-slice-recorder.js";
21
21
  import { NodeRuntimeMetricsService } from "../services/node-runtime-metrics.service.js";
22
+ import { describeIngestRefusal } from "../utils/ingest-refusal.util.js";
22
23
  import { detachedObserveWorker } from "./detached-observe-worker.js";
23
24
  import { ObserveAgentSharedBuffer } from "./observe-agent.shared-buffer.js";
24
25
  import { createTelemetrySanitizer, SECTION_SHAPES, } from "./telemetry-wire-contract.js";
@@ -188,11 +189,12 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
188
189
  }
189
190
  initializeWorker() {
190
191
  this.warnIfCredentialsSentInClear();
191
- // The sanitizer factory is inlined as the worker function's argument: the
192
- // worker is eval'd source with no module scope, so code it needs has to
193
- // travel as source, and data (the wire shapes are plain JSON) as
194
- // `workerData`. The factory is written self-contained for exactly this.
195
- this.worker = new Worker(`(${detachedObserveWorker.toString()})(${createTelemetrySanitizer.toString()})`, {
192
+ // The sanitizer factory and the refusal describer are inlined as the
193
+ // worker function's arguments: the worker is eval'd source with no module
194
+ // scope, so code it needs has to travel as source, and data (the wire
195
+ // shapes are plain JSON) as `workerData`. Both are written self-contained
196
+ // for exactly this.
197
+ this.worker = new Worker(`(${detachedObserveWorker.toString()})(${createTelemetrySanitizer.toString()}, ${describeIngestRefusal.toString()})`, {
196
198
  eval: true,
197
199
  workerData: {
198
200
  sharedBuffer: this.observeAgentSharedBuffer.sharedBuffer,
@@ -218,6 +218,50 @@ export interface ObserveOptions {
218
218
  * @default 1000
219
219
  */
220
220
  maxTracesPerBatch?: number;
221
+ /**
222
+ * Collapses repeated sibling spans before a trace is shipped.
223
+ *
224
+ * A provider the framework calls in a loop - the canonical case is a
225
+ * `ValidationPipe` registered through `APP_PIPE`, which runs once per
226
+ * argument of every GraphQL field resolver - produces thousands of
227
+ * near-identical spans under one parent for a single list query. Every one
228
+ * of them is a metered event, and together they say nothing a count would
229
+ * not.
230
+ *
231
+ * When more than `threshold` siblings under the same parent share a class
232
+ * and method, the slowest `keepSlowest` of them and any that errored stay
233
+ * as ordinary spans, and the rest are replaced by a single node carrying
234
+ * their count (as the `observe.collapsed` tag) and their *summed*
235
+ * duration. That sum is what keeps the parent's self time exact, and the
236
+ * children of the collapsed calls are carried across so class attribution
237
+ * beneath them survives too. The collapsed node is metered as one event.
238
+ *
239
+ * Nothing is skipped and no duration threshold is involved, deliberately:
240
+ * what validation costs is application-specific, and the outliers that
241
+ * explain a slow request are exactly the instances kept whole. What is lost
242
+ * is the relative ordering of the collapsed calls among themselves - the
243
+ * node takes the earliest call's `startOffset` - which is acceptable for
244
+ * calls that are identical by construction.
245
+ *
246
+ * On by default. Set to `false` to ship every span.
247
+ *
248
+ * @default { threshold: 20, keepSlowest: 3 }
249
+ */
250
+ spanCollapse?: false | {
251
+ /**
252
+ * Number of siblings sharing a class and method that a parent may
253
+ * hold before the surplus is collapsed. Collapsing starts at
254
+ * `threshold + 1`.
255
+ * @default 20
256
+ */
257
+ threshold?: number;
258
+ /**
259
+ * How many of the slowest instances to keep as individual spans when
260
+ * a group collapses. Errored instances are kept in addition to these.
261
+ * @default 3
262
+ */
263
+ keepSlowest?: number;
264
+ };
221
265
  /**
222
266
  * Whether to forward logs to the Observe APM.
223
267
  * If true, logs will be forwarded to the Agent for correlation with traces.
@@ -24,6 +24,7 @@ import { RpcObserveAgentService } from "./protocols/rpc-observe-agent.service.js
24
24
  import { ScheduleObserveAgentService } from "./protocols/schedule-observe-agent.service.js";
25
25
  import { LoggerPatcherService } from "./services/logger-patcher.service.js";
26
26
  import { NodeRuntimeMetricsService } from "./services/node-runtime-metrics.service.js";
27
+ import { resolveSpanCollapseSettings } from "./services/collapse-repeated-spans.util.js";
27
28
  import { OperationTraceRegistry } from "./services/operation-trace.registry.js";
28
29
  import { StdoutForwarderService } from "./services/stdout-forwarder.service.js";
29
30
  import { TraceSamplerService } from "./services/trace-sampler.service.js";
@@ -140,7 +141,15 @@ export function createObserveModule(options = {}) {
140
141
  },
141
142
  {
142
143
  provide: OperationTraceRegistry,
143
- useValue: operationTraceRegistry,
144
+ // The instance already exists (the instrumentation hook below holds
145
+ // it), so this is the one moment the resolved `ObserveOptions` and the
146
+ // registry meet: `spanCollapse` is applied here. Optional because
147
+ // `ASSERT_MODULE_OPTIONS` owns the missing-options error.
148
+ useFactory: (observeOptions) => {
149
+ operationTraceRegistry.configureSpanCollapse(resolveSpanCollapseSettings(observeOptions?.spanCollapse));
150
+ return operationTraceRegistry;
151
+ },
152
+ inject: [{ token: OBSERVE_OPTIONS, optional: true }],
144
153
  },
145
154
  TracerService,
146
155
  LoggerPatcherService,
@@ -1,3 +1,4 @@
1
+ import { describeIngestRefusal } from "../utils/ingest-refusal.util.js";
1
2
  /**
2
3
  * Windows held while uploads are failing.
3
4
  *
@@ -117,7 +118,10 @@ export class ProfileUploader {
117
118
  // carries the freshest profiles the two-window cap kept.
118
119
  const pauseMs = this.rateLimitPauseMs(response);
119
120
  this.rateLimitedUntil = Date.now() + pauseMs;
120
- this.options.onError?.(`profile upload rate-limited (429) - the account may be out of credits or over budget; ` +
121
+ // Same reading of the body as the telemetry worker, so the two halves
122
+ // of the agent describe one account state in one way.
123
+ const body = await response.json().catch(() => undefined);
124
+ this.options.onError?.(`profile upload rate-limited (429) - ${describeIngestRefusal(body)}; ` +
121
125
  `pausing uploads for ${Math.round(pauseMs / 60000)} minute(s)`);
122
126
  return false;
123
127
  }
@@ -0,0 +1,76 @@
1
+ import { ObserveOptions } from "../interfaces/observe-options.interface.js";
2
+ import { CompleteTraceEventNode, OngoingTraceEventNode } from "../interfaces/trace-events.interfaces.js";
3
+ /**
4
+ * Tag under which a collapsed node records how many calls it stands for.
5
+ *
6
+ * A tag rather than a field of its own so the wire format does not change:
7
+ * `tags` is already on every span and already declared by the collector's
8
+ * contract, so an agent emitting this needs no matching collector release. A
9
+ * collector that does not know the tag stores it like any other and
10
+ * attributes the node as one call; one that does reads the true count here.
11
+ * Namespaced so it reads as the agent's in a span's tag list, and safe from
12
+ * collision: the node it sits on never exists at runtime, so no user code can
13
+ * set tags on it, and the tags of the calls it replaces are dropped.
14
+ *
15
+ * Absent on an ordinary span, which stands for exactly one call. On a node
16
+ * that carries it, `duration` is the *sum* of the replaced calls' durations,
17
+ * `startOffset` and `spanId` are the earliest call's, and `children` holds
18
+ * every child the replaced calls had - which is what keeps the parent's self
19
+ * time and the subtree's class attribution exactly what they were. Ordering
20
+ * among the replaced calls is lost. The node is one event on the wire and is
21
+ * metered as one.
22
+ */
23
+ export declare const SPAN_COLLAPSED_TAG = "observe.collapsed";
24
+ /** Resolved form of `ObserveOptions.spanCollapse`. */
25
+ export interface SpanCollapseSettings {
26
+ /** Siblings sharing a frame that may stand before the surplus collapses. */
27
+ threshold: number;
28
+ /** Slowest instances kept whole once a group collapses. */
29
+ keepSlowest: number;
30
+ }
31
+ /**
32
+ * Twenty is above what a hand-written method produces under one parent - a
33
+ * handler calling a repository a dozen times in a loop is still shipped
34
+ * whole - and far below the hundreds a framework hook like `ValidationPipe`
35
+ * produces per GraphQL list query. Three kept instances is enough to show the
36
+ * spread between the slowest calls without the tail of identical ones behind
37
+ * them.
38
+ */
39
+ export declare const DEFAULT_SPAN_COLLAPSE: SpanCollapseSettings;
40
+ /**
41
+ * Turns the user-facing option into settings the registry can apply, or
42
+ * `undefined` when collapsing is switched off. Unusable values - a negative
43
+ * count, a fraction, `NaN` - fall back to the default for that field rather
44
+ * than disabling the feature: an option typo should not silently reopen the
45
+ * span flood this exists to stop.
46
+ */
47
+ export declare function resolveSpanCollapseSettings(option: ObserveOptions["spanCollapse"]): SpanCollapseSettings | undefined;
48
+ /**
49
+ * Collapses repeated siblings throughout a completed span tree, in place.
50
+ *
51
+ * Within one list of siblings, auto spans are grouped by `className` and
52
+ * `methodKey`. A group larger than `threshold` keeps its `keepSlowest`
53
+ * longest-running members and every member that errored as ordinary spans;
54
+ * the rest are replaced by one node that records how many calls it stands
55
+ * for (`SPAN_COLLAPSED_TAG`) and the sum of their durations. Manual spans are never collapsed - a
56
+ * user named each of them deliberately - and ongoing nodes, which a shipped
57
+ * tree should not contain, are left alone.
58
+ *
59
+ * Summing the durations, rather than taking the wall-clock envelope, is what
60
+ * keeps the collector's self-time partition exact: a parent's self time is its
61
+ * duration minus the durations of its children, and the sum over the surviving
62
+ * children is the same as it was over the originals. The collapsed calls'
63
+ * own children are carried across onto the collapsed node for the same reason
64
+ * one level down, and then collapsed among themselves in turn - a repeated
65
+ * frame that always calls the same repeated frame collapses at both levels.
66
+ *
67
+ * Siblings are matched wherever they sit in the list, not only when adjacent:
68
+ * a pipe run once per argument interleaves with the resolver calls it
69
+ * validates for. The collapsed node takes the position of the earliest call
70
+ * it replaces, so ordering relative to the *other* siblings is kept; ordering
71
+ * among the collapsed calls themselves is lost.
72
+ *
73
+ * Returns the new sibling list for the level passed in. Descendant lists are
74
+ * rewritten through their parents' `children`.
75
+ */
76
+ export declare function collapseRepeatedSpans(siblings: Array<CompleteTraceEventNode | OngoingTraceEventNode>, settings: SpanCollapseSettings): Array<CompleteTraceEventNode | OngoingTraceEventNode>;
@@ -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;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Explains a 429 from the collector in the operator's terms.
3
+ *
4
+ * The collector refuses ingest for three different reasons, and until this
5
+ * existed the agent reported all of them as "the account may be out of
6
+ * credits or over budget" - which sent an operator whose card had been
7
+ * declined to the pricing page, and one whose rate cap had engaged to their
8
+ * invoices. The body tells them apart: a quota refusal carries
9
+ * `code: "USAGE_LIMIT_REACHED"` with the plan and the counts, and a quota
10
+ * refusal caused by a declined payment adds `reason: "payment_failed"`. A
11
+ * rate cap, and any older collector, sends neither and gets the old sentence.
12
+ *
13
+ * Written self-contained on purpose - no imports, no module-scope constants -
14
+ * because the telemetry worker is a stringified function and this travels
15
+ * into it as source (see `ObserveAgentWorker.initializeWorker`). Anything it
16
+ * referenced from this module's scope would be undefined there.
17
+ *
18
+ * @param body the parsed JSON body of the 429, or anything else - a text
19
+ * body, `undefined` from a failed parse - which reads as "no detail".
20
+ */
21
+ export declare const describeIngestRefusal: (body: unknown) => string;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Explains a 429 from the collector in the operator's terms.
3
+ *
4
+ * The collector refuses ingest for three different reasons, and until this
5
+ * existed the agent reported all of them as "the account may be out of
6
+ * credits or over budget" - which sent an operator whose card had been
7
+ * declined to the pricing page, and one whose rate cap had engaged to their
8
+ * invoices. The body tells them apart: a quota refusal carries
9
+ * `code: "USAGE_LIMIT_REACHED"` with the plan and the counts, and a quota
10
+ * refusal caused by a declined payment adds `reason: "payment_failed"`. A
11
+ * rate cap, and any older collector, sends neither and gets the old sentence.
12
+ *
13
+ * Written self-contained on purpose - no imports, no module-scope constants -
14
+ * because the telemetry worker is a stringified function and this travels
15
+ * into it as source (see `ObserveAgentWorker.initializeWorker`). Anything it
16
+ * referenced from this module's scope would be undefined there.
17
+ *
18
+ * @param body the parsed JSON body of the 429, or anything else - a text
19
+ * body, `undefined` from a failed parse - which reads as "no detail".
20
+ */
21
+ export const describeIngestRefusal = (body) => {
22
+ const detail = body !== null && typeof body === "object"
23
+ ? body
24
+ : {};
25
+ if (detail.code !== "USAGE_LIMIT_REACHED") {
26
+ return "the account may be out of credits or over budget";
27
+ }
28
+ const plan = typeof detail.plan === "string" ? detail.plan : undefined;
29
+ const counts = typeof detail.used === "number" && typeof detail.included === "number"
30
+ ? `${detail.used.toLocaleString("en-US")} of ${detail.included.toLocaleString("en-US")} included events used` +
31
+ (plan ? ` on the ${plan} plan` : "")
32
+ : undefined;
33
+ if (detail.reason === "payment_failed") {
34
+ // The plan has overage; it is switched off because the last payment was
35
+ // declined. The fix is a card, not an upgrade, so say so - and say that
36
+ // it lifts on payment, since the operator will otherwise wait for the
37
+ // period to reset.
38
+ return ("a payment on the account was declined, so events past the included volume are refused until the outstanding invoice is paid" +
39
+ (counts ? ` (${counts})` : "") +
40
+ "; update the payment method in the dashboard to resume");
41
+ }
42
+ return ("the account has used its included events for this period" +
43
+ (counts ? ` (${counts})` : "") +
44
+ "; upgrade the plan or wait for the period to reset");
45
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nestjs/observe",
3
- "version": "0.1.9",
3
+ "version": "0.2.0",
4
4
  "description": "Observability and APM agent for NestJS - traces, runtime metrics, custom metrics and CPU profiles",
5
5
  "author": "Kamil Mysliwiec",
6
6
  "homepage": "https://nestjs.com",