@nestjs/observe 0.0.1 → 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/README.md +16 -0
- package/dist/.tsbuildinfo +1 -1
- package/dist/agent/detached-observe-worker.js +98 -1
- package/dist/agent/observe-agent.shared-buffer.d.ts +82 -0
- package/dist/agent/observe-agent.shared-buffer.js +94 -3
- package/dist/agent/observe-agent.worker.d.ts +28 -0
- package/dist/agent/observe-agent.worker.js +59 -5
- package/dist/custom-metrics/counter.d.ts +124 -0
- package/dist/custom-metrics/counter.js +93 -0
- package/dist/custom-metrics/gauge.d.ts +116 -0
- package/dist/custom-metrics/gauge.js +55 -0
- package/dist/custom-metrics/summary.d.ts +102 -0
- package/dist/custom-metrics/summary.js +100 -0
- package/dist/encoders/custom-metrics.encoder.js +18 -0
- package/dist/encoders/remap-keys.util.d.ts +11 -0
- package/dist/encoders/remap-keys.util.js +15 -0
- package/dist/encoders/trace.encoder.d.ts +7 -0
- package/dist/encoders/trace.encoder.js +12 -0
- package/dist/instrument/create-instance-decorator.instrument.d.ts +8 -0
- package/dist/instrument/create-instance-decorator.instrument.js +67 -0
- package/dist/interfaces/custom-metric.interface.d.ts +74 -0
- package/dist/interfaces/graphql.interfaces.d.ts +16 -0
- package/dist/interfaces/job-snapshot.interface.d.ts +70 -0
- package/dist/interfaces/node-runtime-metrics.interface.d.ts +5 -0
- package/dist/interfaces/observe-options.interface.d.ts +358 -0
- package/dist/interfaces/request-snapshot.interface.d.ts +62 -0
- package/dist/interfaces/trace-events.interfaces.d.ts +51 -0
- package/dist/interfaces/trace-span.interface.d.ts +29 -0
- package/dist/observe.module.js +29 -0
- package/dist/profiling/cpu-profiler.service.d.ts +65 -0
- package/dist/profiling/cpu-profiler.service.js +80 -0
- package/dist/profiling/fold-profile.util.d.ts +20 -0
- package/dist/profiling/fold-profile.util.js +0 -0
- package/dist/profiling/profile-uploader.d.ts +26 -0
- package/dist/profiling/profile-uploader.js +52 -0
- package/dist/profiling/span-slice-recorder.d.ts +51 -0
- package/dist/profiling/span-slice-recorder.js +77 -0
- package/dist/protocols/graphql-observe-agent.service.d.ts +128 -0
- package/dist/protocols/graphql-observe-agent.service.js +166 -0
- package/dist/protocols/graphql-operation-parser.d.ts +26 -0
- package/dist/protocols/graphql-operation-parser.js +66 -0
- package/dist/protocols/http-observe-agent.service.d.ts +19 -0
- package/dist/protocols/http-observe-agent.service.js +34 -0
- package/dist/protocols/queue-observe-agent.service.d.ts +8 -0
- package/dist/protocols/queue-observe-agent.service.js +32 -0
- package/dist/protocols/rpc-observe-agent.service.d.ts +7 -0
- package/dist/protocols/rpc-observe-agent.service.js +12 -0
- package/dist/services/logger-patcher.service.d.ts +4 -0
- package/dist/services/logger-patcher.service.js +13 -1
- package/dist/services/node-runtime-metrics.service.js +24 -8
- package/dist/services/operation-trace.registry.d.ts +56 -1
- package/dist/services/operation-trace.registry.js +145 -6
- package/dist/services/stdout-forwarder.service.d.ts +19 -0
- package/dist/services/stdout-forwarder.service.js +62 -0
- package/dist/services/trace-sampler.service.d.ts +6 -0
- package/dist/services/trace-sampler.service.js +3 -3
- package/dist/services/tracer.service.d.ts +91 -0
- package/dist/services/tracer.service.js +56 -1
- package/dist/trace-span.delegate.d.ts +11 -0
- package/dist/trace-span.delegate.js +11 -0
- package/dist/types/path-value.type.d.ts +4 -0
- package/dist/utils/default-trace-id-generator.util.js +11 -0
- package/dist/utils/log-line.parser.d.ts +14 -0
- package/dist/utils/log-line.parser.js +37 -0
- package/dist/utils/log-redactor.js +65 -0
- package/dist/utils/redact-url-query.d.ts +17 -0
- package/dist/utils/redact-url-query.js +38 -0
- package/dist/utils/source-context.util.d.ts +22 -0
- package/dist/utils/source-context.util.js +60 -0
- package/dist/utils/source-map-resolver.util.d.ts +13 -0
- package/dist/utils/source-map-resolver.util.js +26 -28
- package/package.json +1 -1
|
@@ -1,4 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Windows held while uploads are failing.
|
|
3
|
+
*
|
|
4
|
+
* Small on purpose. A profile window is diagnostic data with a short shelf
|
|
5
|
+
* life, and the backend caps retention at fourteen days anyway - queueing
|
|
6
|
+
* hours of them through an outage would spend the customer's memory on stacks
|
|
7
|
+
* nobody will look at. Two windows covers a restart of the collector; beyond
|
|
8
|
+
* that the oldest is dropped.
|
|
9
|
+
*/
|
|
1
10
|
const MAX_PENDING_WINDOWS = 2;
|
|
11
|
+
/**
|
|
12
|
+
* Ships one folded-stack window per upload.
|
|
13
|
+
*
|
|
14
|
+
* Deliberately not routed through the agent's shared buffer. That buffer exists
|
|
15
|
+
* to batch high-frequency telemetry into one flush every few seconds; profiles
|
|
16
|
+
* are one request a minute against a different endpoint, and squeezing them
|
|
17
|
+
* through it would couple the profile cadence to the telemetry flush and put a
|
|
18
|
+
* megabyte of stacks into a ring sized for spans.
|
|
19
|
+
*/
|
|
2
20
|
export class ProfileUploader {
|
|
3
21
|
options;
|
|
4
22
|
pending = [];
|
|
@@ -16,6 +34,13 @@ export class ProfileUploader {
|
|
|
16
34
|
this.pending.push({ window, sampleRateHz });
|
|
17
35
|
void this.drain();
|
|
18
36
|
}
|
|
37
|
+
/**
|
|
38
|
+
* Sends everything queued, oldest first.
|
|
39
|
+
*
|
|
40
|
+
* Serialised: two windows in flight at once would interleave against a
|
|
41
|
+
* backend that keys rows on window start, and the second would arrive as a
|
|
42
|
+
* duplicate rather than an addition.
|
|
43
|
+
*/
|
|
19
44
|
async drain() {
|
|
20
45
|
if (this.inFlight) {
|
|
21
46
|
return;
|
|
@@ -26,6 +51,9 @@ export class ProfileUploader {
|
|
|
26
51
|
const next = this.pending[0];
|
|
27
52
|
const sent = await this.send(next.window, next.sampleRateHz);
|
|
28
53
|
if (!sent) {
|
|
54
|
+
// Left at the head to be retried by the next window's drain. Failing
|
|
55
|
+
// uploads must not spin: there is no timer here, only the natural
|
|
56
|
+
// once-a-minute cadence.
|
|
29
57
|
break;
|
|
30
58
|
}
|
|
31
59
|
this.pending.shift();
|
|
@@ -39,6 +67,8 @@ export class ProfileUploader {
|
|
|
39
67
|
const headers = {
|
|
40
68
|
"Content-Type": "application/json",
|
|
41
69
|
};
|
|
70
|
+
// Omitted rather than sent empty when unconfigured, so a collector running
|
|
71
|
+
// in placeholder mode still accepts the upload.
|
|
42
72
|
if (this.options.appKey && this.options.appSecret) {
|
|
43
73
|
headers["x-api-key"] = this.options.appKey;
|
|
44
74
|
headers["x-api-secret"] = this.options.appSecret;
|
|
@@ -49,16 +79,26 @@ export class ProfileUploader {
|
|
|
49
79
|
headers,
|
|
50
80
|
body: JSON.stringify({
|
|
51
81
|
serviceNode: this.options.serviceNode,
|
|
82
|
+
// The rate actually used, not the nominal one: a throttled agent
|
|
83
|
+
// sampling slower would otherwise have every duration on the page
|
|
84
|
+
// overstated.
|
|
52
85
|
sampleRateHz,
|
|
53
86
|
windows: [window],
|
|
54
87
|
}),
|
|
55
88
|
});
|
|
56
89
|
if (response.status === 403 &&
|
|
57
90
|
(await this.isEntitlementError(response))) {
|
|
91
|
+
// The plan does not include profiling. Dropped rather than retried -
|
|
92
|
+
// the answer will not change on the next attempt, and the profiler is
|
|
93
|
+
// stopped by the caller that owns the entitlement.
|
|
58
94
|
this.options.onError?.("profiling is not included in this plan; discarding the window");
|
|
59
95
|
return true;
|
|
60
96
|
}
|
|
61
97
|
if (response.status === 401 || response.status === 403) {
|
|
98
|
+
// A credential problem, not an entitlement one. Reported specifically
|
|
99
|
+
// and not discarded: it is a misconfiguration the operator can fix,
|
|
100
|
+
// and treating it as "not in your plan" would throw the window away
|
|
101
|
+
// and describe the cause wrongly.
|
|
62
102
|
this.options.onError?.(`profile upload rejected (${response.status}); check that appKey and appSecret are valid - the application is taken from the key`);
|
|
63
103
|
return false;
|
|
64
104
|
}
|
|
@@ -69,10 +109,22 @@ export class ProfileUploader {
|
|
|
69
109
|
return true;
|
|
70
110
|
}
|
|
71
111
|
catch (err) {
|
|
112
|
+
// Network failures are expected and must never surface into the
|
|
113
|
+
// application: an agent that throws into a customer's request path over
|
|
114
|
+
// its own telemetry is worse than one that loses a window.
|
|
72
115
|
this.options.onError?.(`profile upload failed: ${String(err)}`);
|
|
73
116
|
return false;
|
|
74
117
|
}
|
|
75
118
|
}
|
|
119
|
+
/**
|
|
120
|
+
* Whether a 403 is "your plan does not include profiling" rather than "your
|
|
121
|
+
* key may not write here".
|
|
122
|
+
*
|
|
123
|
+
* Keyed on the machine-readable `code` the collector sends for exactly this
|
|
124
|
+
* purpose, not on the message. A body that cannot be read or does not carry
|
|
125
|
+
* the code is treated as a credential failure - the safe way round, since
|
|
126
|
+
* that path retries and the entitlement path discards.
|
|
127
|
+
*/
|
|
76
128
|
async isEntitlementError(response) {
|
|
77
129
|
try {
|
|
78
130
|
const body = (await response.clone().json());
|
|
@@ -1,15 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A stretch of time during which one span's code was the innermost
|
|
3
|
+
* instrumented thing running on this thread.
|
|
4
|
+
*
|
|
5
|
+
* Times are `performance.now()` milliseconds - the same clock profile samples
|
|
6
|
+
* are mapped onto.
|
|
7
|
+
*/
|
|
1
8
|
export interface SpanSlice {
|
|
2
9
|
spanId: string;
|
|
3
10
|
traceId: string;
|
|
4
11
|
from: number;
|
|
5
12
|
to: number;
|
|
6
13
|
}
|
|
14
|
+
/**
|
|
15
|
+
* Records which span was executing when, so profile samples can be labelled
|
|
16
|
+
* after the fact.
|
|
17
|
+
*
|
|
18
|
+
* This exists because a JS-only profiler cannot label a sample at the moment it
|
|
19
|
+
* fires. V8 samples on its own thread and hands back a batch afterwards; there
|
|
20
|
+
* is no JS callback to read `AsyncLocalStorage` from. Datadog's profiler solves
|
|
21
|
+
* this with a native addon that writes a thread-local at sample time. Without
|
|
22
|
+
* one, the equivalent is to record the timeline in JS and join it to the
|
|
23
|
+
* samples' timestamps once the batch arrives.
|
|
24
|
+
*
|
|
25
|
+
* The join is only sound because Node runs JS on one thread: at any instant
|
|
26
|
+
* exactly one span's synchronous code is on the stack, so a sample's timestamp
|
|
27
|
+
* identifies it unambiguously. That is a different claim from the time-window
|
|
28
|
+
* overlap the API's honesty rule rejects - overlapping *span durations* say
|
|
29
|
+
* nothing on a concurrent server, because a span's duration includes the awaits
|
|
30
|
+
* during which other requests ran. These are execution slices, not durations.
|
|
31
|
+
*
|
|
32
|
+
* Known limitation, and the reason unattributed samples stay unlabelled rather
|
|
33
|
+
* than being guessed at: while a span awaits, uninstrumented code may run. No
|
|
34
|
+
* slice covers it, so its samples carry no span - which is correct, since that
|
|
35
|
+
* code is in no span - but a sample landing in an outer span's slice while an
|
|
36
|
+
* uninstrumented callback runs is attributed to the outer span. Instrumented
|
|
37
|
+
* work always opens its own slice and is attributed exactly.
|
|
38
|
+
*/
|
|
7
39
|
export declare class SpanSliceRecorder {
|
|
8
40
|
private readonly slices;
|
|
41
|
+
/** Innermost-first stack of spans currently open on this thread. */
|
|
9
42
|
private readonly stack;
|
|
43
|
+
/**
|
|
44
|
+
* Records that a span began executing.
|
|
45
|
+
*
|
|
46
|
+
* Closes the enclosing span's slice first: from here until this span ends,
|
|
47
|
+
* the innermost thing running is this one, and attributing the interval to
|
|
48
|
+
* both would double-count it.
|
|
49
|
+
*/
|
|
10
50
|
enter(traceId: string, spanId: string, at?: number): void;
|
|
51
|
+
/**
|
|
52
|
+
* Records that a span stopped executing, and resumes the enclosing one.
|
|
53
|
+
*
|
|
54
|
+
* Accepts an absent id because a step whose caller could not be resolved was
|
|
55
|
+
* never entered either: the lookup below simply misses and nothing unwinds.
|
|
56
|
+
*/
|
|
11
57
|
exit(spanId: string | undefined, at?: number): void;
|
|
58
|
+
/**
|
|
59
|
+
* Every slice recorded so far, oldest first, with the still-open spans
|
|
60
|
+
* closed at `until` so a window flush does not lose the work in flight.
|
|
61
|
+
*/
|
|
12
62
|
drain(until?: number): SpanSlice[];
|
|
63
|
+
/** Discards everything, for shutdown and for tests. */
|
|
13
64
|
reset(): void;
|
|
14
65
|
private closeTop;
|
|
15
66
|
private push;
|
|
@@ -1,16 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Slices kept before the oldest are dropped.
|
|
3
|
+
*
|
|
4
|
+
* A window is 60 seconds and a busy service opens thousands of spans in that
|
|
5
|
+
* time, so this is a ring rather than a list that grows until the next flush.
|
|
6
|
+
* Sized well above one window's worth: dropping a slice only costs the label
|
|
7
|
+
* on the samples inside it, which degrades to the "window" correlation the API
|
|
8
|
+
* already models, but dropping them wholesale would make exact correlation
|
|
9
|
+
* quietly stop working under load - the one condition anyone profiles in.
|
|
10
|
+
*/
|
|
1
11
|
const MAX_SLICES = 20_000;
|
|
12
|
+
/**
|
|
13
|
+
* Records which span was executing when, so profile samples can be labelled
|
|
14
|
+
* after the fact.
|
|
15
|
+
*
|
|
16
|
+
* This exists because a JS-only profiler cannot label a sample at the moment it
|
|
17
|
+
* fires. V8 samples on its own thread and hands back a batch afterwards; there
|
|
18
|
+
* is no JS callback to read `AsyncLocalStorage` from. Datadog's profiler solves
|
|
19
|
+
* this with a native addon that writes a thread-local at sample time. Without
|
|
20
|
+
* one, the equivalent is to record the timeline in JS and join it to the
|
|
21
|
+
* samples' timestamps once the batch arrives.
|
|
22
|
+
*
|
|
23
|
+
* The join is only sound because Node runs JS on one thread: at any instant
|
|
24
|
+
* exactly one span's synchronous code is on the stack, so a sample's timestamp
|
|
25
|
+
* identifies it unambiguously. That is a different claim from the time-window
|
|
26
|
+
* overlap the API's honesty rule rejects - overlapping *span durations* say
|
|
27
|
+
* nothing on a concurrent server, because a span's duration includes the awaits
|
|
28
|
+
* during which other requests ran. These are execution slices, not durations.
|
|
29
|
+
*
|
|
30
|
+
* Known limitation, and the reason unattributed samples stay unlabelled rather
|
|
31
|
+
* than being guessed at: while a span awaits, uninstrumented code may run. No
|
|
32
|
+
* slice covers it, so its samples carry no span - which is correct, since that
|
|
33
|
+
* code is in no span - but a sample landing in an outer span's slice while an
|
|
34
|
+
* uninstrumented callback runs is attributed to the outer span. Instrumented
|
|
35
|
+
* work always opens its own slice and is attributed exactly.
|
|
36
|
+
*/
|
|
2
37
|
export class SpanSliceRecorder {
|
|
3
38
|
slices = [];
|
|
39
|
+
/** Innermost-first stack of spans currently open on this thread. */
|
|
4
40
|
stack = [];
|
|
41
|
+
/**
|
|
42
|
+
* Records that a span began executing.
|
|
43
|
+
*
|
|
44
|
+
* Closes the enclosing span's slice first: from here until this span ends,
|
|
45
|
+
* the innermost thing running is this one, and attributing the interval to
|
|
46
|
+
* both would double-count it.
|
|
47
|
+
*/
|
|
5
48
|
enter(traceId, spanId, at = performance.now()) {
|
|
6
49
|
this.closeTop(at);
|
|
7
50
|
this.stack.push({ spanId, traceId, since: at });
|
|
8
51
|
}
|
|
52
|
+
/**
|
|
53
|
+
* Records that a span stopped executing, and resumes the enclosing one.
|
|
54
|
+
*
|
|
55
|
+
* Accepts an absent id because a step whose caller could not be resolved was
|
|
56
|
+
* never entered either: the lookup below simply misses and nothing unwinds.
|
|
57
|
+
*/
|
|
9
58
|
exit(spanId, at = performance.now()) {
|
|
10
59
|
const index = this.stack.findIndex((entry) => entry.spanId === spanId);
|
|
11
60
|
if (index === -1) {
|
|
12
61
|
return;
|
|
13
62
|
}
|
|
63
|
+
// Everything above it goes too. A span ending while its children are still
|
|
64
|
+
// open means the children were never awaited - the registry warns about
|
|
65
|
+
// exactly this - and leaving them on the stack would attribute the rest of
|
|
66
|
+
// the process's work to a span that has finished.
|
|
67
|
+
//
|
|
68
|
+
// Unwound innermost-first, advancing each enclosing span to `at` as its
|
|
69
|
+
// child is closed. Without that step the abandoned parent's `since` is
|
|
70
|
+
// still the moment its child started, so it would emit a slice spanning the
|
|
71
|
+
// child's entire execution - the same microseconds counted twice, under two
|
|
72
|
+
// different spans.
|
|
14
73
|
for (let depth = this.stack.length - 1; depth >= index; depth -= 1) {
|
|
15
74
|
const entry = this.stack[depth];
|
|
16
75
|
this.push({
|
|
@@ -26,6 +85,10 @@ export class SpanSliceRecorder {
|
|
|
26
85
|
}
|
|
27
86
|
}
|
|
28
87
|
}
|
|
88
|
+
/**
|
|
89
|
+
* Every slice recorded so far, oldest first, with the still-open spans
|
|
90
|
+
* closed at `until` so a window flush does not lose the work in flight.
|
|
91
|
+
*/
|
|
29
92
|
drain(until = performance.now()) {
|
|
30
93
|
const open = this.stack.map((entry) => ({
|
|
31
94
|
spanId: entry.spanId,
|
|
@@ -33,6 +96,8 @@ export class SpanSliceRecorder {
|
|
|
33
96
|
from: entry.since,
|
|
34
97
|
to: until,
|
|
35
98
|
}));
|
|
99
|
+
// The open spans keep running, so their next slice starts where this one
|
|
100
|
+
// ended rather than back at their original entry.
|
|
36
101
|
for (const entry of this.stack) {
|
|
37
102
|
entry.since = until;
|
|
38
103
|
}
|
|
@@ -40,6 +105,7 @@ export class SpanSliceRecorder {
|
|
|
40
105
|
this.slices.length = 0;
|
|
41
106
|
return drained;
|
|
42
107
|
}
|
|
108
|
+
/** Discards everything, for shutdown and for tests. */
|
|
43
109
|
reset() {
|
|
44
110
|
this.slices.length = 0;
|
|
45
111
|
this.stack.length = 0;
|
|
@@ -61,6 +127,9 @@ export class SpanSliceRecorder {
|
|
|
61
127
|
}
|
|
62
128
|
push(slice) {
|
|
63
129
|
if (slice.to <= slice.from) {
|
|
130
|
+
// A slice with no duration cannot contain a sample, and keeping them
|
|
131
|
+
// would fill the ring with the zero-width entries that decorator-heavy
|
|
132
|
+
// code produces on every call.
|
|
64
133
|
return;
|
|
65
134
|
}
|
|
66
135
|
if (this.slices.length >= MAX_SLICES) {
|
|
@@ -69,6 +138,14 @@ export class SpanSliceRecorder {
|
|
|
69
138
|
this.slices.push(slice);
|
|
70
139
|
}
|
|
71
140
|
}
|
|
141
|
+
/**
|
|
142
|
+
* The recorder the instrumentation writes to, or null when profiling is off.
|
|
143
|
+
*
|
|
144
|
+
* A module-level handle rather than an injected dependency because the writers
|
|
145
|
+
* are on the hot path - every instrumented method entry and exit - and the
|
|
146
|
+
* overwhelmingly common case is profiling being disabled. That case has to cost
|
|
147
|
+
* one null check, not a resolved provider and a virtual call.
|
|
148
|
+
*/
|
|
72
149
|
let activeRecorder = null;
|
|
73
150
|
export function activeSliceRecorder() {
|
|
74
151
|
return activeRecorder;
|
|
@@ -13,22 +13,62 @@ interface GqlRequestStartContext {
|
|
|
13
13
|
context?: Record<string, unknown>;
|
|
14
14
|
}
|
|
15
15
|
interface GqlRequestEndContext extends GqlRequestStartContext {
|
|
16
|
+
/** `GraphQLError`s, structurally: the `graphql` package is an optional peer. */
|
|
16
17
|
errors?: readonly {
|
|
17
18
|
message?: string;
|
|
18
19
|
originalError?: unknown;
|
|
19
20
|
}[];
|
|
20
21
|
state?: unknown;
|
|
21
22
|
}
|
|
23
|
+
/**
|
|
24
|
+
* What the start hook hands the end hook. Everything needed to close the
|
|
25
|
+
* operation travels in here rather than in a map keyed by trace id, because an
|
|
26
|
+
* unmatched start must not leave anything behind - see the Mercurius note on
|
|
27
|
+
* `onRequestEnd`.
|
|
28
|
+
*/
|
|
22
29
|
interface OperationState {
|
|
23
30
|
traceId: string;
|
|
24
31
|
spanId: string;
|
|
25
32
|
className: string;
|
|
26
33
|
methodKey: string;
|
|
34
|
+
/** The caller this operation displaced, restored once it ends. */
|
|
27
35
|
previousCallerId: string | undefined;
|
|
28
36
|
store: Map<string, unknown> | undefined;
|
|
37
|
+
/** Whether this service opened the trace, and therefore has to ship it. */
|
|
29
38
|
ownsTrace: boolean;
|
|
30
39
|
context: unknown;
|
|
31
40
|
}
|
|
41
|
+
/**
|
|
42
|
+
* GraphQL operation instrumentation.
|
|
43
|
+
*
|
|
44
|
+
* Nest serves GraphQL as raw middleware mounted on a single path, so from
|
|
45
|
+
* HTTP's point of view every operation a service handles is one `POST /graphql`
|
|
46
|
+
* with no route handler behind it. That is a problem in both directions: the
|
|
47
|
+
* trace has no spans, so `OperationTraceRegistry.endTrace` discards it as a
|
|
48
|
+
* request that never reached a handler, and even if it survived, every query
|
|
49
|
+
* and mutation in the schema would aggregate into a single row.
|
|
50
|
+
*
|
|
51
|
+
* `@nestjs/graphql` exposes `ResolverDecoratorHost`, whose request-lifecycle
|
|
52
|
+
* hooks bracket a single operation: `setOnRequestStartHook` fires before the
|
|
53
|
+
* document is processed, `setOnRequestEndHook` once it has been, right before
|
|
54
|
+
* the response goes out. Whatever the start hook returns is handed back as
|
|
55
|
+
* `state`, which is what lets one span be opened in the first and closed in the
|
|
56
|
+
* second. This service claims both and gives each operation a span.
|
|
57
|
+
*
|
|
58
|
+
* The span goes into the trace the HTTP agent already opened whenever there is
|
|
59
|
+
* one, which keeps the shape a reader expects: one snapshot per HTTP request,
|
|
60
|
+
* with `Query.orders` as the operation id and the operation - plus every
|
|
61
|
+
* instrumented provider it reached - as the trace tree underneath. Only when no
|
|
62
|
+
* such trace exists does this service open one of its own.
|
|
63
|
+
*
|
|
64
|
+
* Measuring the operation rather than each root field is the point of using
|
|
65
|
+
* these hooks over the resolver decorator they replace. A span now covers
|
|
66
|
+
* parsing, validation and execution together, which is the number a client
|
|
67
|
+
* actually waited for; a document selecting several root fields is one span
|
|
68
|
+
* instead of several competing to name the trace; and a resolver that calls
|
|
69
|
+
* nothing instrumented still produces a trace rather than being discarded for
|
|
70
|
+
* having recorded no spans.
|
|
71
|
+
*/
|
|
32
72
|
export declare class GraphQLObserveAgentService<Store extends Record<string, unknown>> implements OnModuleInit {
|
|
33
73
|
private readonly asyncLocalStorage;
|
|
34
74
|
private readonly options;
|
|
@@ -40,18 +80,106 @@ export declare class GraphQLObserveAgentService<Store extends Record<string, unk
|
|
|
40
80
|
private readonly metadataScanner;
|
|
41
81
|
private readonly logger;
|
|
42
82
|
private isPatched;
|
|
83
|
+
/**
|
|
84
|
+
* `Query.orders` -> the resolver class and method that registered it. Built
|
|
85
|
+
* lazily on the first operation, by which point every provider exists.
|
|
86
|
+
* `undefined` until then; never rebuilt, because resolvers cannot be added
|
|
87
|
+
* after the schema is built.
|
|
88
|
+
*/
|
|
43
89
|
private resolverIndex;
|
|
44
90
|
constructor(asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>, options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, observeAgentSharedBuffer: ObserveAgentSharedBuffer, traceSamplerService: TraceSamplerService, moduleRef: ModuleRef, discoveryService: DiscoveryService, metadataScanner: MetadataScanner);
|
|
45
91
|
onModuleInit(): Promise<void>;
|
|
46
92
|
registerRequestHooksIfPossible(): Promise<void>;
|
|
93
|
+
/**
|
|
94
|
+
* Opens a span for the operation about to be processed.
|
|
95
|
+
*
|
|
96
|
+
* Returns the state the end hook needs, or `undefined` for an operation this
|
|
97
|
+
* does not measure - one that was ignored, sampled out, or whose document
|
|
98
|
+
* nothing could be learned from. `undefined` is the end hook's signal to do
|
|
99
|
+
* nothing, so the two stay paired without a second flag.
|
|
100
|
+
*
|
|
101
|
+
* Hook exceptions are not swallowed by the driver, so nothing in here may
|
|
102
|
+
* throw on a caller's behalf: a failure to label a trace must not turn into a
|
|
103
|
+
* failed GraphQL request.
|
|
104
|
+
*/
|
|
47
105
|
onRequestStart(ctx: GqlRequestStartContext): OperationState | undefined;
|
|
106
|
+
/**
|
|
107
|
+
* Closes the span, and - when this service opened the trace - ends and ships
|
|
108
|
+
* it.
|
|
109
|
+
*
|
|
110
|
+
* Not guaranteed to run for every start. Mercurius resolves an operation
|
|
111
|
+
* through `onResolution`, which never fires for a document that failed
|
|
112
|
+
* parsing or validation, so a start hook there can go unmatched. Nothing is
|
|
113
|
+
* leaked when it does: the state lives in the hook's return value rather than
|
|
114
|
+
* in this service, and the registry drops a trace whose spans never closed.
|
|
115
|
+
* The one visible consequence is that a malformed document collects nothing
|
|
116
|
+
* on Mercurius, which is what it collected before any of this existed.
|
|
117
|
+
*/
|
|
48
118
|
onRequestEnd(ctx: GqlRequestEndContext): void;
|
|
119
|
+
/**
|
|
120
|
+
* The common case: the operation arrived over an HTTP request the HTTP agent
|
|
121
|
+
* already opened a trace for. The operation becomes a root span in that trace
|
|
122
|
+
* and lends it its operation id; the HTTP response hook still owns ending and
|
|
123
|
+
* shipping the snapshot.
|
|
124
|
+
*/
|
|
49
125
|
private startWithinRequest;
|
|
126
|
+
/**
|
|
127
|
+
* No enclosing trace - any transport with no agent of its own in front of it.
|
|
128
|
+
* The operation is the whole trace here, so this opens it, samples it, and
|
|
129
|
+
* ships the snapshot itself.
|
|
130
|
+
*
|
|
131
|
+
* The store is installed with `enterWith` rather than `run`, because a hook
|
|
132
|
+
* that returns cannot wrap the work that follows it. That makes this a
|
|
133
|
+
* best-effort path, and the way it can be wrong is worth naming: `enterWith`
|
|
134
|
+
* binds the store to the driver's *current* execution context and everything
|
|
135
|
+
* continuing from it, so where that context is shared between operations -
|
|
136
|
+
* rather than created per request, as an HTTP transport does - one
|
|
137
|
+
* operation's spans can be recorded against another's trace. In a service
|
|
138
|
+
* handling several tenants' operations that is telemetry attributed to the
|
|
139
|
+
* wrong one, not merely a trace with the wrong shape.
|
|
140
|
+
*
|
|
141
|
+
* There is no fix available at this layer, and pretending otherwise would be
|
|
142
|
+
* worse than the risk: the caller has already established that no enclosing
|
|
143
|
+
* trace exists, so there is nothing here to defend against, and the leak is
|
|
144
|
+
* outward rather than inward. Closing it needs the GraphQL driver to offer a
|
|
145
|
+
* hook that *wraps* execution - which `run` could then scope exactly - rather
|
|
146
|
+
* than one that returns into it. Until then, a deployment that cares should
|
|
147
|
+
* put a transport agent in front: the HTTP path never takes this branch.
|
|
148
|
+
*/
|
|
50
149
|
private startAsOperation;
|
|
150
|
+
/**
|
|
151
|
+
* Opens the span and registers it as the caller in the async store, which is
|
|
152
|
+
* what makes everything the operation reaches - instrumented providers,
|
|
153
|
+
* manual spans, forwarded log lines - hang underneath this node rather than
|
|
154
|
+
* beside it.
|
|
155
|
+
*/
|
|
51
156
|
private openSpan;
|
|
157
|
+
/**
|
|
158
|
+
* Ends and ships a trace this service opened itself.
|
|
159
|
+
*
|
|
160
|
+
* No status code is passed: GraphQL has none. An operation that errored is
|
|
161
|
+
* classified from its root span instead, which is what keeps a failing
|
|
162
|
+
* operation out of the success bucket.
|
|
163
|
+
*/
|
|
52
164
|
private endOperationTrace;
|
|
165
|
+
/**
|
|
166
|
+
* Picks the error a failed operation is recorded with.
|
|
167
|
+
*
|
|
168
|
+
* The first one wins - a span carries one error, and a document with several
|
|
169
|
+
* failing fields has to pick. `originalError` is preferred over the
|
|
170
|
+
* `GraphQLError` wrapping it, because that is the error the registry
|
|
171
|
+
* classifies: an `IntrinsicException` a handler raised on purpose reads as
|
|
172
|
+
* handled, and it stops being recognisable once GraphQL has wrapped it.
|
|
173
|
+
*/
|
|
53
174
|
private toSpanError;
|
|
54
175
|
private lookupResolverHandler;
|
|
176
|
+
/**
|
|
177
|
+
* Walks every provider for methods `@Query`/`@Mutation`/`@Subscription`
|
|
178
|
+
* decorated, and records which class hosts each root field. Read from the
|
|
179
|
+
* prototypes' decorator metadata rather than the schema, because the schema
|
|
180
|
+
* only knows the field - the class that registered it is exactly what it
|
|
181
|
+
* erases, and what the services page wants back.
|
|
182
|
+
*/
|
|
55
183
|
private buildResolverIndex;
|
|
56
184
|
private applyAttributes;
|
|
57
185
|
}
|