@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,23 +1,85 @@
|
|
|
1
1
|
import { CompleteTraceEventNode, OngoingTraceEventNode } from "./trace-events.interfaces.js";
|
|
2
2
|
export interface RequestSnapshot {
|
|
3
|
+
/**
|
|
4
|
+
* Represents when the request was executed.
|
|
5
|
+
* This is a human-readable timestamp, typically in ISO 8601 format.
|
|
6
|
+
*/
|
|
3
7
|
calledAt?: string;
|
|
8
|
+
/**
|
|
9
|
+
* Unique identifier for the trace associated
|
|
10
|
+
*/
|
|
4
11
|
traceId: string;
|
|
12
|
+
/**
|
|
13
|
+
* Timestamp when the request started.
|
|
14
|
+
* This is a high-resolution timestamp, typically in milliseconds.
|
|
15
|
+
*/
|
|
5
16
|
startTimestamp?: number;
|
|
17
|
+
/**
|
|
18
|
+
* The duration of the request in milliseconds.
|
|
19
|
+
*/
|
|
6
20
|
duration?: number;
|
|
21
|
+
/**
|
|
22
|
+
* HTTP, gRPC, Kafka, or other protocol used for the request.
|
|
23
|
+
* This field indicates the type of protocol used for the request.
|
|
24
|
+
*/
|
|
7
25
|
protocol: string;
|
|
26
|
+
/**
|
|
27
|
+
* Unique identifier for the operation being traced.
|
|
28
|
+
* This could be a URL path for HTTP requests, a method name for gRPC, etc.
|
|
29
|
+
*/
|
|
8
30
|
operationId?: string;
|
|
31
|
+
/**
|
|
32
|
+
* Array of trace events associated with the request.
|
|
33
|
+
* This array contains both ongoing and complete trace events.
|
|
34
|
+
* Ongoing events are those that have started but not yet ended.
|
|
35
|
+
*/
|
|
9
36
|
traces: Array<OngoingTraceEventNode | CompleteTraceEventNode>;
|
|
37
|
+
/**
|
|
38
|
+
* Tags associated with the request.
|
|
39
|
+
* Tags are key-value pairs that provide additional context about the request.
|
|
40
|
+
* This field is optional and can be used to capture additional metadata about the request.
|
|
41
|
+
* @example { 'environment': 'production', 'version': '1.0.0' }
|
|
42
|
+
* @default {}
|
|
43
|
+
*/
|
|
10
44
|
tags?: Record<string, string | number | boolean>;
|
|
45
|
+
/**
|
|
46
|
+
* Indicates whether an error occurred during the operation represented by the trace span.
|
|
47
|
+
* If undefined, it means no error occurred.
|
|
48
|
+
*/
|
|
11
49
|
error?: {
|
|
12
50
|
cls?: string;
|
|
13
51
|
message: string;
|
|
14
52
|
stack?: string;
|
|
15
53
|
tags?: Record<string, string | number | boolean>;
|
|
16
54
|
};
|
|
55
|
+
/**
|
|
56
|
+
* Optional user identifier associated with the request.
|
|
57
|
+
*/
|
|
17
58
|
userId?: string;
|
|
59
|
+
/**
|
|
60
|
+
* Protocol-specific attributes for the request.
|
|
61
|
+
* This field is optional and can be used to capture additional attributes specific to the protocol used
|
|
62
|
+
* (e.g., HTTP method, status code).
|
|
63
|
+
*/
|
|
18
64
|
attributes?: {
|
|
65
|
+
/**
|
|
66
|
+
* The HTTP method used for the request (e.g., GET, POST, PUT, DELETE).
|
|
67
|
+
* This field is optional and can be used to capture the HTTP method of the request.
|
|
68
|
+
*/
|
|
19
69
|
method?: string;
|
|
70
|
+
/**
|
|
71
|
+
* The status code of the HTTP response.
|
|
72
|
+
* This field is optional and can be used to capture the HTTP status code of the response.
|
|
73
|
+
*/
|
|
20
74
|
statusCode?: number;
|
|
75
|
+
/**
|
|
76
|
+
* Original URL of the request. For GraphQL operations this carries the
|
|
77
|
+
* sanitized document instead of the transport's URL: every operation
|
|
78
|
+
* shares one mount path, so the URL says nothing, while the document is
|
|
79
|
+
* what tells two requests to the same root field apart -
|
|
80
|
+
* `{ orders { id } }` and `{ orders { id name total } }` share an
|
|
81
|
+
* operation id but not a document.
|
|
82
|
+
*/
|
|
21
83
|
originalUrl?: string;
|
|
22
84
|
};
|
|
23
85
|
}
|
|
@@ -1,17 +1,68 @@
|
|
|
1
1
|
import { TraceSpan } from "./trace-span.interface.js";
|
|
2
2
|
export interface OngoingTraceEventNode extends TraceSpan {
|
|
3
3
|
type: "start";
|
|
4
|
+
/**
|
|
5
|
+
* Represents the host class name, which is the class where the method being traced is defined.
|
|
6
|
+
*/
|
|
4
7
|
className: string;
|
|
8
|
+
/**
|
|
9
|
+
* Represents the name of the method being traced.
|
|
10
|
+
*/
|
|
5
11
|
methodKey: string;
|
|
12
|
+
/**
|
|
13
|
+
* Timestamp when the trace event started.
|
|
14
|
+
* This is a high-resolution timestamp, typically in milliseconds.
|
|
15
|
+
*/
|
|
6
16
|
startTime: number;
|
|
17
|
+
/**
|
|
18
|
+
* Milliseconds between the start of the trace root and the start of this span.
|
|
19
|
+
*
|
|
20
|
+
* Captured when the span opens and carried through to the completed node, so
|
|
21
|
+
* it survives `startTime` being deleted on completion. Undefined when the
|
|
22
|
+
* parent snapshot has already been cleaned up.
|
|
23
|
+
*/
|
|
7
24
|
startOffset?: number;
|
|
25
|
+
/**
|
|
26
|
+
* Children trace events for ongoing trace events.
|
|
27
|
+
* This is an array of either `CompleteTraceEventNode` or `OngoingTraceEventNode`.
|
|
28
|
+
* It allows for nested trace events, where ongoing events can have children that are
|
|
29
|
+
* either complete or still ongoing.
|
|
30
|
+
*/
|
|
8
31
|
children: Array<CompleteTraceEventNode | OngoingTraceEventNode>;
|
|
32
|
+
/**
|
|
33
|
+
* Optional parent node for ongoing trace events.
|
|
34
|
+
* Undefined for root nodes.
|
|
35
|
+
*/
|
|
9
36
|
parent?: OngoingTraceEventNode;
|
|
10
37
|
}
|
|
11
38
|
export interface CompleteTraceEventNode extends TraceSpan {
|
|
39
|
+
/**
|
|
40
|
+
* Represents the host class name, which is the class where the method being traced is defined.
|
|
41
|
+
*/
|
|
12
42
|
className: string;
|
|
43
|
+
/**
|
|
44
|
+
* Represents the name of the method being traced.
|
|
45
|
+
*/
|
|
13
46
|
methodKey: string;
|
|
47
|
+
/**
|
|
48
|
+
* The duration of the trace event in milliseconds.
|
|
49
|
+
* This is calculated as the difference between the start time and end time.
|
|
50
|
+
*/
|
|
14
51
|
duration: number;
|
|
52
|
+
/**
|
|
53
|
+
* Milliseconds between the start of the trace root and the start of this span.
|
|
54
|
+
*
|
|
55
|
+
* Together with `duration` this places the span on the trace's shared clock,
|
|
56
|
+
* which is what makes a real waterfall possible: siblings that overlap can be
|
|
57
|
+
* drawn overlapping instead of being laid end to end. Without it a consumer can
|
|
58
|
+
* only render nesting and relative width.
|
|
59
|
+
*
|
|
60
|
+
* Optional: spans reported by agents older than this field carry no offset.
|
|
61
|
+
*/
|
|
15
62
|
startOffset?: number;
|
|
63
|
+
/**
|
|
64
|
+
* Children trace events for nested trace events.
|
|
65
|
+
* All children should be `CompleteTraceEventNode` instances, otherwise the parent node would not be complete.
|
|
66
|
+
*/
|
|
16
67
|
children: Array<CompleteTraceEventNode>;
|
|
17
68
|
}
|
|
@@ -1,8 +1,37 @@
|
|
|
1
1
|
export interface TraceSpan {
|
|
2
|
+
/**
|
|
3
|
+
* Unique identifier for the trace span.
|
|
4
|
+
* This is typically a UUID or a similar unique identifier.
|
|
5
|
+
* Undefined for automatically created spans.
|
|
6
|
+
*/
|
|
2
7
|
spanId?: string;
|
|
8
|
+
/**
|
|
9
|
+
* The name of the trace span.
|
|
10
|
+
* This is a human-readable name that describes the operation being traced.
|
|
11
|
+
* Only used for manual spans.
|
|
12
|
+
*/
|
|
3
13
|
name?: string;
|
|
14
|
+
/**
|
|
15
|
+
* The origin of the trace span.
|
|
16
|
+
* This indicates whether the span was created manually or automatically.
|
|
17
|
+
* - 'manual': The span was created manually by the user.
|
|
18
|
+
* - 'auto': The span was created automatically by the system.
|
|
19
|
+
*/
|
|
4
20
|
origin: "manual" | "auto";
|
|
21
|
+
/**
|
|
22
|
+
* Tags associated with the trace span.
|
|
23
|
+
* Tags are key-value pairs that provide additional context about the span.
|
|
24
|
+
*/
|
|
5
25
|
tags?: Record<string, string | number | boolean>;
|
|
26
|
+
/**
|
|
27
|
+
* Indicates whether an error occurred during the operation represented by the trace span.
|
|
28
|
+
* If undefined, it means no error occurred.
|
|
29
|
+
* If true, it indicates an error occurred, but the error was handled gracefully and not captured.
|
|
30
|
+
* If an object is provided, it contains details about the error, including:
|
|
31
|
+
* - `message`: A human-readable error message.
|
|
32
|
+
* - `stack`: An optional stack trace of the error.
|
|
33
|
+
* This field is useful for debugging and understanding the context of errors in the trace.
|
|
34
|
+
*/
|
|
6
35
|
error?: boolean | {
|
|
7
36
|
cls?: string;
|
|
8
37
|
message: string;
|
package/dist/observe.module.js
CHANGED
|
@@ -29,6 +29,11 @@ import { TraceSamplerService } from "./services/trace-sampler.service.js";
|
|
|
29
29
|
import { TracerService } from "./services/tracer.service.js";
|
|
30
30
|
import { assertModuleOptions } from "./utils/assert-module-options.util.js";
|
|
31
31
|
import { defaultTraceIdGenerator } from "./utils/default-trace-id-generator.util.js";
|
|
32
|
+
/**
|
|
33
|
+
* All three async providers are optional on the options type, but one of them
|
|
34
|
+
* has to be there. Stating that here beats the `undefined` token Nest would
|
|
35
|
+
* otherwise try to resolve, which fails much later with no mention of why.
|
|
36
|
+
*/
|
|
32
37
|
const MISSING_ASYNC_OPTIONS_PROVIDER = 'ObserveModule.forRootAsync() requires one of "useFactory", "useClass" or "useExisting".';
|
|
33
38
|
export function createObserveModule(options = {}) {
|
|
34
39
|
var ObserveModule_1;
|
|
@@ -139,11 +144,15 @@ export function createObserveModule(options = {}) {
|
|
|
139
144
|
LoggerPatcherService,
|
|
140
145
|
HttpObserveAgentService,
|
|
141
146
|
RpcObserveAgentService,
|
|
147
|
+
// A no-op unless @nestjs/graphql is installed and registered; it claims
|
|
148
|
+
// the request lifecycle hooks only when it finds them.
|
|
142
149
|
GraphQLObserveAgentService,
|
|
143
150
|
ObserveAgentWorker,
|
|
144
151
|
ObserveAgentSharedBuffer,
|
|
145
152
|
TraceSamplerService,
|
|
146
153
|
NodeRuntimeMetricsService,
|
|
154
|
+
// Registered unconditionally; the service itself is a no-op unless
|
|
155
|
+
// `forwardLogs` is enabled, and it redacts before anything is buffered.
|
|
147
156
|
StdoutForwarderService,
|
|
148
157
|
QueueObserveAgentService,
|
|
149
158
|
],
|
|
@@ -162,10 +171,24 @@ export function createObserveModule(options = {}) {
|
|
|
162
171
|
instance instanceof TraceSamplerService ||
|
|
163
172
|
instance instanceof TracerService ||
|
|
164
173
|
instance instanceof ObserveAgentSharedBuffer ||
|
|
174
|
+
// Its methods run *inside* the traces it opens, so instrumenting
|
|
175
|
+
// it would put a span for the agent itself at the root of every
|
|
176
|
+
// GraphQL operation it records.
|
|
165
177
|
instance instanceof GraphQLObserveAgentService ||
|
|
178
|
+
// Nest's discovery machinery, which the GraphQL agent walks to
|
|
179
|
+
// map root fields back to their resolver classes. It has to stay
|
|
180
|
+
// unproxied: ModulesContainer extends Map, and a Map method
|
|
181
|
+
// invoked with the instrumentation proxy as its receiver throws
|
|
182
|
+
// "called on incompatible receiver" - Map's internal slots live
|
|
183
|
+
// on the target, and a proxy does not forward them.
|
|
166
184
|
instance instanceof ModulesContainer ||
|
|
167
185
|
instance instanceof DiscoveryService ||
|
|
168
186
|
instance instanceof MetadataScanner ||
|
|
187
|
+
// `@nestjs/graphql`'s ResolverDecoratorHost, matched structurally
|
|
188
|
+
// because the package is an optional peer. Its `onRequestStart` /
|
|
189
|
+
// `onRequestEnd` methods invoke the hooks this module registers,
|
|
190
|
+
// so instrumenting it would wrap the agent's own bookkeeping in
|
|
191
|
+
// spans inside every operation it measures.
|
|
169
192
|
isResolverDecoratorHost(instance));
|
|
170
193
|
},
|
|
171
194
|
}),
|
|
@@ -173,6 +196,12 @@ export function createObserveModule(options = {}) {
|
|
|
173
196
|
ObserveModule,
|
|
174
197
|
};
|
|
175
198
|
}
|
|
199
|
+
/**
|
|
200
|
+
* Identifies `@nestjs/graphql`'s `ResolverDecoratorHost` without importing the
|
|
201
|
+
* package, which is an optional peer. `decorate`/`setDecorator` plus the
|
|
202
|
+
* request-hook accessors are its public surface and unlikely to appear together
|
|
203
|
+
* on anything else.
|
|
204
|
+
*/
|
|
176
205
|
function isResolverDecoratorHost(instance) {
|
|
177
206
|
const candidate = instance;
|
|
178
207
|
return (typeof candidate?.decorate === "function" &&
|
|
@@ -1,8 +1,34 @@
|
|
|
1
1
|
import { FoldedStack } from "./fold-profile.util.js";
|
|
2
2
|
import { SpanSliceRecorder } from "./span-slice-recorder.js";
|
|
3
|
+
/**
|
|
4
|
+
* Samples per second.
|
|
5
|
+
*
|
|
6
|
+
* 99 rather than 100 so the sampler does not fall into lockstep with the 10ms
|
|
7
|
+
* timers that `setInterval` and friends land on, systematically over- or
|
|
8
|
+
* under-counting whatever runs on them.
|
|
9
|
+
*/
|
|
3
10
|
export declare const DEFAULT_SAMPLE_RATE_HZ = 99;
|
|
11
|
+
/** How much wall clock one upload window covers. */
|
|
4
12
|
export declare const DEFAULT_WINDOW_MS = 60000;
|
|
13
|
+
/**
|
|
14
|
+
* How much of each window is actually sampled.
|
|
15
|
+
*
|
|
16
|
+
* Duty cycling is what keeps continuous profiling affordable: the sampler runs
|
|
17
|
+
* for this long, then stops until the next window. Ten seconds in sixty is a
|
|
18
|
+
* sixth of the overhead, and a flame graph aggregated over minutes is no less
|
|
19
|
+
* useful for it - the API stores the rate per window and reports coverage per
|
|
20
|
+
* window, so a sparsely sampled window is a first-class answer rather than a
|
|
21
|
+
* gap the client has to reason about.
|
|
22
|
+
*/
|
|
5
23
|
export declare const DEFAULT_DUTY_MS = 10000;
|
|
24
|
+
/**
|
|
25
|
+
* Share of one CPU the profiler may cost before it stops sampling.
|
|
26
|
+
*
|
|
27
|
+
* Measured across the sampling burst rather than the whole window, because
|
|
28
|
+
* that is when the cost is incurred. Exceeding it disables profiling for the
|
|
29
|
+
* process rather than degrading it quietly: an agent that silently eats a
|
|
30
|
+
* tenth of a customer's CPU is worse than one that says it gave up.
|
|
31
|
+
*/
|
|
6
32
|
export declare const DEFAULT_MAX_CPU_PERCENT = 3;
|
|
7
33
|
export interface ProfileWindow {
|
|
8
34
|
start: string;
|
|
@@ -16,6 +42,24 @@ export interface CpuProfilerOptions {
|
|
|
16
42
|
onWindow: (window: ProfileWindow, sampleRateHz: number) => void;
|
|
17
43
|
onDisabled?: (reason: string) => void;
|
|
18
44
|
}
|
|
45
|
+
/**
|
|
46
|
+
* A wall-clock sampling profiler built on `node:inspector`.
|
|
47
|
+
*
|
|
48
|
+
* Deliberately not a native addon. V8's sampling profiler is already reachable
|
|
49
|
+
* from the standard library through the inspector protocol, and a native
|
|
50
|
+
* dependency would land in the install of every service that uses this agent -
|
|
51
|
+
* including the overwhelming majority that will never switch profiling on.
|
|
52
|
+
* Prebuilt binaries, unusual platforms, bundlers and Docker bases are a
|
|
53
|
+
* permanent tax; the inspector session is none of those.
|
|
54
|
+
*
|
|
55
|
+
* The trade this makes is that samples arrive as a batch with timestamps rather
|
|
56
|
+
* than carrying labels, so span attribution is a join done afterwards - see
|
|
57
|
+
* `SpanSliceRecorder` for why that is sound on a single-threaded runtime.
|
|
58
|
+
*
|
|
59
|
+
* Sampling runs on the profiled thread by definition: V8 profiles the isolate
|
|
60
|
+
* the session is attached to, so this cannot be moved onto the agent's worker.
|
|
61
|
+
* Only the folding and upload are off the hot path.
|
|
62
|
+
*/
|
|
19
63
|
export declare class CpuProfilerService {
|
|
20
64
|
private readonly slices;
|
|
21
65
|
private readonly options;
|
|
@@ -29,8 +73,19 @@ export declare class CpuProfilerService {
|
|
|
29
73
|
private readonly dutyMs;
|
|
30
74
|
private readonly maxCpuPercent;
|
|
31
75
|
constructor(slices: SpanSliceRecorder, options: CpuProfilerOptions);
|
|
76
|
+
/**
|
|
77
|
+
* Begins duty-cycled profiling, resolving once the first burst is actually
|
|
78
|
+
* sampling. Safe to call twice.
|
|
79
|
+
*
|
|
80
|
+
* Awaitable because starting is not instantaneous: the inspector handshake -
|
|
81
|
+
* enable, set the interval, start - is several round trips through the
|
|
82
|
+
* session's message loop, and until they complete nothing is being sampled.
|
|
83
|
+
* A caller that fires this and immediately does work would profile none of
|
|
84
|
+
* it, and a fire-and-forget signature gives them no way to find out.
|
|
85
|
+
*/
|
|
32
86
|
start(): Promise<void>;
|
|
33
87
|
stop(): Promise<void>;
|
|
88
|
+
/** Whether the profiler has given up on itself; see `maxCpuPercent`. */
|
|
34
89
|
isDisabled(): boolean;
|
|
35
90
|
private runWindow;
|
|
36
91
|
private windowStartedAt;
|
|
@@ -38,6 +93,16 @@ export declare class CpuProfilerService {
|
|
|
38
93
|
private cpuAtStart;
|
|
39
94
|
private beginBurst;
|
|
40
95
|
private finish;
|
|
96
|
+
/**
|
|
97
|
+
* Stops profiling for good if the burst cost more CPU than the budget.
|
|
98
|
+
*
|
|
99
|
+
* `process.cpuUsage` covers the whole process, so this measures the profiler
|
|
100
|
+
* plus everything the application did during the burst - it cannot isolate
|
|
101
|
+
* the sampler's own cost from JS. What it can do is catch the case that
|
|
102
|
+
* matters: a process whose CPU is pinned while profiling is on. The threshold
|
|
103
|
+
* is therefore applied to the increase over the burst rather than treated as
|
|
104
|
+
* a precise attribution.
|
|
105
|
+
*/
|
|
41
106
|
private enforceBudget;
|
|
42
107
|
private disable;
|
|
43
108
|
private closeSession;
|
|
@@ -1,10 +1,54 @@
|
|
|
1
1
|
import { Session } from "node:inspector";
|
|
2
2
|
import { promisify } from "node:util";
|
|
3
3
|
import { foldProfile } from "./fold-profile.util.js";
|
|
4
|
+
/**
|
|
5
|
+
* Samples per second.
|
|
6
|
+
*
|
|
7
|
+
* 99 rather than 100 so the sampler does not fall into lockstep with the 10ms
|
|
8
|
+
* timers that `setInterval` and friends land on, systematically over- or
|
|
9
|
+
* under-counting whatever runs on them.
|
|
10
|
+
*/
|
|
4
11
|
export const DEFAULT_SAMPLE_RATE_HZ = 99;
|
|
12
|
+
/** How much wall clock one upload window covers. */
|
|
5
13
|
export const DEFAULT_WINDOW_MS = 60_000;
|
|
14
|
+
/**
|
|
15
|
+
* How much of each window is actually sampled.
|
|
16
|
+
*
|
|
17
|
+
* Duty cycling is what keeps continuous profiling affordable: the sampler runs
|
|
18
|
+
* for this long, then stops until the next window. Ten seconds in sixty is a
|
|
19
|
+
* sixth of the overhead, and a flame graph aggregated over minutes is no less
|
|
20
|
+
* useful for it - the API stores the rate per window and reports coverage per
|
|
21
|
+
* window, so a sparsely sampled window is a first-class answer rather than a
|
|
22
|
+
* gap the client has to reason about.
|
|
23
|
+
*/
|
|
6
24
|
export const DEFAULT_DUTY_MS = 10_000;
|
|
25
|
+
/**
|
|
26
|
+
* Share of one CPU the profiler may cost before it stops sampling.
|
|
27
|
+
*
|
|
28
|
+
* Measured across the sampling burst rather than the whole window, because
|
|
29
|
+
* that is when the cost is incurred. Exceeding it disables profiling for the
|
|
30
|
+
* process rather than degrading it quietly: an agent that silently eats a
|
|
31
|
+
* tenth of a customer's CPU is worse than one that says it gave up.
|
|
32
|
+
*/
|
|
7
33
|
export const DEFAULT_MAX_CPU_PERCENT = 3;
|
|
34
|
+
/**
|
|
35
|
+
* A wall-clock sampling profiler built on `node:inspector`.
|
|
36
|
+
*
|
|
37
|
+
* Deliberately not a native addon. V8's sampling profiler is already reachable
|
|
38
|
+
* from the standard library through the inspector protocol, and a native
|
|
39
|
+
* dependency would land in the install of every service that uses this agent -
|
|
40
|
+
* including the overwhelming majority that will never switch profiling on.
|
|
41
|
+
* Prebuilt binaries, unusual platforms, bundlers and Docker bases are a
|
|
42
|
+
* permanent tax; the inspector session is none of those.
|
|
43
|
+
*
|
|
44
|
+
* The trade this makes is that samples arrive as a batch with timestamps rather
|
|
45
|
+
* than carrying labels, so span attribution is a join done afterwards - see
|
|
46
|
+
* `SpanSliceRecorder` for why that is sound on a single-threaded runtime.
|
|
47
|
+
*
|
|
48
|
+
* Sampling runs on the profiled thread by definition: V8 profiles the isolate
|
|
49
|
+
* the session is attached to, so this cannot be moved onto the agent's worker.
|
|
50
|
+
* Only the folding and upload are off the hot path.
|
|
51
|
+
*/
|
|
8
52
|
export class CpuProfilerService {
|
|
9
53
|
slices;
|
|
10
54
|
options;
|
|
@@ -22,13 +66,27 @@ export class CpuProfilerService {
|
|
|
22
66
|
this.options = options;
|
|
23
67
|
this.sampleRateHz = options.sampleRateHz ?? DEFAULT_SAMPLE_RATE_HZ;
|
|
24
68
|
this.windowMs = options.windowMs ?? DEFAULT_WINDOW_MS;
|
|
69
|
+
// Clamped: a duty longer than the window would start the next burst before
|
|
70
|
+
// the last one finished, and the two sessions would fight over the isolate.
|
|
25
71
|
this.dutyMs = Math.min(options.dutyMs ?? DEFAULT_DUTY_MS, this.windowMs);
|
|
26
72
|
this.maxCpuPercent = options.maxCpuPercent ?? DEFAULT_MAX_CPU_PERCENT;
|
|
27
73
|
}
|
|
74
|
+
/**
|
|
75
|
+
* Begins duty-cycled profiling, resolving once the first burst is actually
|
|
76
|
+
* sampling. Safe to call twice.
|
|
77
|
+
*
|
|
78
|
+
* Awaitable because starting is not instantaneous: the inspector handshake -
|
|
79
|
+
* enable, set the interval, start - is several round trips through the
|
|
80
|
+
* session's message loop, and until they complete nothing is being sampled.
|
|
81
|
+
* A caller that fires this and immediately does work would profile none of
|
|
82
|
+
* it, and a fire-and-forget signature gives them no way to find out.
|
|
83
|
+
*/
|
|
28
84
|
async start() {
|
|
29
85
|
if (this.windowTimer || this.disabled) {
|
|
30
86
|
return;
|
|
31
87
|
}
|
|
88
|
+
// Unref'd so profiling never holds the process open. An agent that keeps a
|
|
89
|
+
// CLI alive for a minute after its work is done is a bug report.
|
|
32
90
|
this.windowTimer = setInterval(() => {
|
|
33
91
|
void this.runWindow();
|
|
34
92
|
}, this.windowMs);
|
|
@@ -45,11 +103,14 @@ export class CpuProfilerService {
|
|
|
45
103
|
this.dutyTimer = null;
|
|
46
104
|
}
|
|
47
105
|
if (this.running) {
|
|
106
|
+
// Collect what the burst has so far rather than discarding it: shutdown
|
|
107
|
+
// is exactly when the last window is most likely to explain something.
|
|
48
108
|
await this.finish().catch(() => undefined);
|
|
49
109
|
}
|
|
50
110
|
this.closeSession();
|
|
51
111
|
this.slices.reset();
|
|
52
112
|
}
|
|
113
|
+
/** Whether the profiler has given up on itself; see `maxCpuPercent`. */
|
|
53
114
|
isDisabled() {
|
|
54
115
|
return this.disabled;
|
|
55
116
|
}
|
|
@@ -78,6 +139,7 @@ export class CpuProfilerService {
|
|
|
78
139
|
const post = this.postTo(this.session);
|
|
79
140
|
await post("Profiler.enable");
|
|
80
141
|
await post("Profiler.setSamplingInterval", {
|
|
142
|
+
// Microseconds between samples, which is how V8 expresses the rate.
|
|
81
143
|
interval: Math.round(1_000_000 / this.sampleRateHz),
|
|
82
144
|
});
|
|
83
145
|
this.windowStartedAt = performance.now();
|
|
@@ -101,12 +163,24 @@ export class CpuProfilerService {
|
|
|
101
163
|
this.closeSession();
|
|
102
164
|
if (stacks.length > 0) {
|
|
103
165
|
this.options.onWindow({
|
|
166
|
+
// The window the samples belong to, not the moment the burst ended -
|
|
167
|
+
// coverage is expressed in windows and the backend keys rows on this.
|
|
104
168
|
start: new Date(this.windowStartedAtWallClock).toISOString(),
|
|
105
169
|
stacks,
|
|
106
170
|
}, this.sampleRateHz);
|
|
107
171
|
}
|
|
108
172
|
this.enforceBudget(burstMs);
|
|
109
173
|
}
|
|
174
|
+
/**
|
|
175
|
+
* Stops profiling for good if the burst cost more CPU than the budget.
|
|
176
|
+
*
|
|
177
|
+
* `process.cpuUsage` covers the whole process, so this measures the profiler
|
|
178
|
+
* plus everything the application did during the burst - it cannot isolate
|
|
179
|
+
* the sampler's own cost from JS. What it can do is catch the case that
|
|
180
|
+
* matters: a process whose CPU is pinned while profiling is on. The threshold
|
|
181
|
+
* is therefore applied to the increase over the burst rather than treated as
|
|
182
|
+
* a precise attribution.
|
|
183
|
+
*/
|
|
110
184
|
enforceBudget(burstMs) {
|
|
111
185
|
if (!this.cpuAtStart || burstMs <= 0) {
|
|
112
186
|
return;
|
|
@@ -114,6 +188,9 @@ export class CpuProfilerService {
|
|
|
114
188
|
const used = process.cpuUsage(this.cpuAtStart);
|
|
115
189
|
const usedMs = (used.user + used.system) / 1000;
|
|
116
190
|
const percent = (usedMs / burstMs) * 100;
|
|
191
|
+
// Compared against a whole core's worth on top of the budget: anything less
|
|
192
|
+
// is ordinary application load, which this cannot separate from the
|
|
193
|
+
// profiler and must not blame it for.
|
|
117
194
|
if (percent > 100 + this.maxCpuPercent) {
|
|
118
195
|
this.disable(`CPU use during the sampling burst was ${percent.toFixed(1)}% of one core`);
|
|
119
196
|
}
|
|
@@ -137,10 +214,13 @@ export class CpuProfilerService {
|
|
|
137
214
|
this.session?.disconnect();
|
|
138
215
|
}
|
|
139
216
|
catch {
|
|
217
|
+
// Disconnecting an already-dead session is not worth surfacing.
|
|
140
218
|
}
|
|
141
219
|
this.session = null;
|
|
142
220
|
}
|
|
143
221
|
postTo(session) {
|
|
222
|
+
// `Session.post` is callback-style with an optional params argument, and
|
|
223
|
+
// its overloads do not survive promisify's typing.
|
|
144
224
|
return promisify(session.post).bind(session);
|
|
145
225
|
}
|
|
146
226
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { SpanSlice } from "./span-slice-recorder.js";
|
|
2
|
+
/** The shape `Profiler.stop` returns over the inspector protocol. */
|
|
2
3
|
export interface V8ProfileNode {
|
|
3
4
|
id: number;
|
|
4
5
|
callFrame: {
|
|
@@ -11,9 +12,12 @@ export interface V8ProfileNode {
|
|
|
11
12
|
}
|
|
12
13
|
export interface V8Profile {
|
|
13
14
|
nodes: V8ProfileNode[];
|
|
15
|
+
/** Microseconds, on V8's monotonic clock. */
|
|
14
16
|
startTime: number;
|
|
15
17
|
endTime: number;
|
|
18
|
+
/** Node id per sample. */
|
|
16
19
|
samples?: number[];
|
|
20
|
+
/** Microseconds since the previous sample. */
|
|
17
21
|
timeDeltas?: number[];
|
|
18
22
|
}
|
|
19
23
|
export interface FoldedStack {
|
|
@@ -22,7 +26,23 @@ export interface FoldedStack {
|
|
|
22
26
|
spanId?: string;
|
|
23
27
|
traceId?: string;
|
|
24
28
|
}
|
|
29
|
+
/**
|
|
30
|
+
* Folds a V8 profile into per-stack sample counts, tagged with the span that
|
|
31
|
+
* was executing when each sample fired.
|
|
32
|
+
*
|
|
33
|
+
* The tagging is a join on time: `timeDeltas` gives every sample's offset from
|
|
34
|
+
* the profile's start, and `slices` says which span owned each interval. Both
|
|
35
|
+
* are mapped onto `performance.now()` milliseconds, using the profile's own
|
|
36
|
+
* start as the origin - V8 reports microseconds on a clock with no defined
|
|
37
|
+
* epoch, so only the offsets are meaningful and the caller supplies the wall
|
|
38
|
+
* time the profiler was started at.
|
|
39
|
+
*
|
|
40
|
+
* Samples that fall in no slice are emitted without a span. That is the honest
|
|
41
|
+
* outcome for code running outside any instrumented span, and it is what lets
|
|
42
|
+
* the API distinguish an exact tree from the window fallback.
|
|
43
|
+
*/
|
|
25
44
|
export declare function foldProfile(profile: V8Profile, options: {
|
|
45
|
+
/** `performance.now()` reading taken when `Profiler.start` was called. */
|
|
26
46
|
startedAt: number;
|
|
27
47
|
slices?: SpanSlice[];
|
|
28
48
|
}): FoldedStack[];
|
|
Binary file
|
|
@@ -2,18 +2,44 @@ import { ProfileWindow } from "./cpu-profiler.service.js";
|
|
|
2
2
|
export interface ProfileUploaderOptions {
|
|
3
3
|
endpoint: string;
|
|
4
4
|
serviceNode: string;
|
|
5
|
+
/** Ingest credentials, as sent by the telemetry half of the agent. */
|
|
5
6
|
appKey?: string;
|
|
6
7
|
appSecret?: string;
|
|
7
8
|
onError?: (message: string) => void;
|
|
8
9
|
}
|
|
10
|
+
/**
|
|
11
|
+
* Ships one folded-stack window per upload.
|
|
12
|
+
*
|
|
13
|
+
* Deliberately not routed through the agent's shared buffer. That buffer exists
|
|
14
|
+
* to batch high-frequency telemetry into one flush every few seconds; profiles
|
|
15
|
+
* are one request a minute against a different endpoint, and squeezing them
|
|
16
|
+
* through it would couple the profile cadence to the telemetry flush and put a
|
|
17
|
+
* megabyte of stacks into a ring sized for spans.
|
|
18
|
+
*/
|
|
9
19
|
export declare class ProfileUploader {
|
|
10
20
|
private readonly options;
|
|
11
21
|
private readonly pending;
|
|
12
22
|
private inFlight;
|
|
13
23
|
constructor(options: ProfileUploaderOptions);
|
|
14
24
|
enqueue(window: ProfileWindow, sampleRateHz: number): void;
|
|
25
|
+
/**
|
|
26
|
+
* Sends everything queued, oldest first.
|
|
27
|
+
*
|
|
28
|
+
* Serialised: two windows in flight at once would interleave against a
|
|
29
|
+
* backend that keys rows on window start, and the second would arrive as a
|
|
30
|
+
* duplicate rather than an addition.
|
|
31
|
+
*/
|
|
15
32
|
drain(): Promise<void>;
|
|
16
33
|
private send;
|
|
34
|
+
/**
|
|
35
|
+
* Whether a 403 is "your plan does not include profiling" rather than "your
|
|
36
|
+
* key may not write here".
|
|
37
|
+
*
|
|
38
|
+
* Keyed on the machine-readable `code` the collector sends for exactly this
|
|
39
|
+
* purpose, not on the message. A body that cannot be read or does not carry
|
|
40
|
+
* the code is treated as a credential failure - the safe way round, since
|
|
41
|
+
* that path retries and the entitlement path discards.
|
|
42
|
+
*/
|
|
17
43
|
private isEntitlementError;
|
|
18
44
|
pendingCount(): number;
|
|
19
45
|
}
|