@nestjs/observe 0.0.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.
Files changed (108) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +135 -0
  3. package/dist/.tsbuildinfo +1 -0
  4. package/dist/agent/detached-observe-worker.d.ts +1 -0
  5. package/dist/agent/detached-observe-worker.js +104 -0
  6. package/dist/agent/observe-agent.shared-buffer.d.ts +42 -0
  7. package/dist/agent/observe-agent.shared-buffer.js +211 -0
  8. package/dist/agent/observe-agent.worker.d.ts +25 -0
  9. package/dist/agent/observe-agent.worker.js +213 -0
  10. package/dist/custom-metrics/counter.d.ts +39 -0
  11. package/dist/custom-metrics/counter.js +128 -0
  12. package/dist/custom-metrics/gauge.d.ts +40 -0
  13. package/dist/custom-metrics/gauge.js +134 -0
  14. package/dist/custom-metrics/index.d.ts +3 -0
  15. package/dist/custom-metrics/index.js +3 -0
  16. package/dist/custom-metrics/summary.d.ts +38 -0
  17. package/dist/custom-metrics/summary.js +106 -0
  18. package/dist/encoders/custom-metrics.encoder.d.ts +25 -0
  19. package/dist/encoders/custom-metrics.encoder.js +50 -0
  20. package/dist/encoders/job-snapshot.encoder.d.ts +28 -0
  21. package/dist/encoders/job-snapshot.encoder.js +28 -0
  22. package/dist/encoders/remap-keys.util.d.ts +1 -0
  23. package/dist/encoders/remap-keys.util.js +10 -0
  24. package/dist/encoders/request-snapshot.encoder.d.ts +33 -0
  25. package/dist/encoders/request-snapshot.encoder.js +32 -0
  26. package/dist/encoders/runtime-metrics.encoder.d.ts +63 -0
  27. package/dist/encoders/runtime-metrics.encoder.js +55 -0
  28. package/dist/encoders/trace.encoder.d.ts +19 -0
  29. package/dist/encoders/trace.encoder.js +20 -0
  30. package/dist/index.d.ts +10 -0
  31. package/dist/index.js +10 -0
  32. package/dist/instrument/create-instance-decorator.instrument.d.ts +7 -0
  33. package/dist/instrument/create-instance-decorator.instrument.js +165 -0
  34. package/dist/interfaces/custom-metric.interface.d.ts +18 -0
  35. package/dist/interfaces/custom-metric.interface.js +1 -0
  36. package/dist/interfaces/graphql.interfaces.d.ts +12 -0
  37. package/dist/interfaces/graphql.interfaces.js +1 -0
  38. package/dist/interfaces/index.d.ts +7 -0
  39. package/dist/interfaces/index.js +7 -0
  40. package/dist/interfaces/job-snapshot.interface.d.ts +23 -0
  41. package/dist/interfaces/job-snapshot.interface.js +1 -0
  42. package/dist/interfaces/node-runtime-metrics.interface.d.ts +37 -0
  43. package/dist/interfaces/node-runtime-metrics.interface.js +1 -0
  44. package/dist/interfaces/observe-options.interface.d.ts +93 -0
  45. package/dist/interfaces/observe-options.interface.js +1 -0
  46. package/dist/interfaces/request-snapshot.interface.d.ts +23 -0
  47. package/dist/interfaces/request-snapshot.interface.js +1 -0
  48. package/dist/interfaces/trace-events.interfaces.d.ts +17 -0
  49. package/dist/interfaces/trace-events.interfaces.js +1 -0
  50. package/dist/interfaces/trace-span.interface.d.ts +12 -0
  51. package/dist/interfaces/trace-span.interface.js +1 -0
  52. package/dist/observe.constants.d.ts +2 -0
  53. package/dist/observe.constants.js +2 -0
  54. package/dist/observe.module.d.ts +20 -0
  55. package/dist/observe.module.js +181 -0
  56. package/dist/profiling/cpu-profiler.service.d.ts +45 -0
  57. package/dist/profiling/cpu-profiler.service.js +146 -0
  58. package/dist/profiling/fold-profile.util.d.ts +28 -0
  59. package/dist/profiling/fold-profile.util.js +0 -0
  60. package/dist/profiling/profile-uploader.d.ts +19 -0
  61. package/dist/profiling/profile-uploader.js +88 -0
  62. package/dist/profiling/span-slice-recorder.d.ts +18 -0
  63. package/dist/profiling/span-slice-recorder.js +78 -0
  64. package/dist/protocols/graphql-observe-agent.service.d.ts +58 -0
  65. package/dist/protocols/graphql-observe-agent.service.js +261 -0
  66. package/dist/protocols/graphql-operation-parser.d.ts +10 -0
  67. package/dist/protocols/graphql-operation-parser.js +174 -0
  68. package/dist/protocols/http-observe-agent.service.d.ts +31 -0
  69. package/dist/protocols/http-observe-agent.service.js +186 -0
  70. package/dist/protocols/queue-observe-agent.service.d.ts +15 -0
  71. package/dist/protocols/queue-observe-agent.service.js +132 -0
  72. package/dist/protocols/rpc-observe-agent.service.d.ts +33 -0
  73. package/dist/protocols/rpc-observe-agent.service.js +183 -0
  74. package/dist/services/index.d.ts +1 -0
  75. package/dist/services/index.js +1 -0
  76. package/dist/services/logger-patcher.service.d.ts +12 -0
  77. package/dist/services/logger-patcher.service.js +76 -0
  78. package/dist/services/node-runtime-metrics.service.d.ts +23 -0
  79. package/dist/services/node-runtime-metrics.service.js +156 -0
  80. package/dist/services/operation-trace.registry.d.ts +49 -0
  81. package/dist/services/operation-trace.registry.js +364 -0
  82. package/dist/services/stdout-forwarder.service.d.ts +21 -0
  83. package/dist/services/stdout-forwarder.service.js +128 -0
  84. package/dist/services/trace-sampler.service.d.ts +19 -0
  85. package/dist/services/trace-sampler.service.js +38 -0
  86. package/dist/services/tracer.service.d.ts +48 -0
  87. package/dist/services/tracer.service.js +186 -0
  88. package/dist/trace-span.delegate.d.ts +10 -0
  89. package/dist/trace-span.delegate.js +24 -0
  90. package/dist/types/key-of.type.d.ts +1 -0
  91. package/dist/types/key-of.type.js +1 -0
  92. package/dist/types/path-value.type.d.ts +6 -0
  93. package/dist/types/path-value.type.js +1 -0
  94. package/dist/utils/assert-module-options.util.d.ts +2 -0
  95. package/dist/utils/assert-module-options.util.js +8 -0
  96. package/dist/utils/default-trace-id-generator.util.d.ts +1 -0
  97. package/dist/utils/default-trace-id-generator.util.js +11 -0
  98. package/dist/utils/log-line.parser.d.ts +9 -0
  99. package/dist/utils/log-line.parser.js +59 -0
  100. package/dist/utils/log-redactor.d.ts +11 -0
  101. package/dist/utils/log-redactor.js +150 -0
  102. package/dist/utils/redact-url-query.d.ts +2 -0
  103. package/dist/utils/redact-url-query.js +51 -0
  104. package/dist/utils/source-context.util.d.ts +11 -0
  105. package/dist/utils/source-context.util.js +130 -0
  106. package/dist/utils/source-map-resolver.util.d.ts +7 -0
  107. package/dist/utils/source-map-resolver.util.js +107 -0
  108. package/package.json +129 -0
@@ -0,0 +1,20 @@
1
+ import { DynamicModule, Logger, NestApplicationOptions, Provider } from "@nestjs/common";
2
+ import { HttpAdapterHost } from "@nestjs/core";
3
+ import { AsyncLocalStorage } from "async_hooks";
4
+ import { CreateObserveModuleOptions, ObserveModuleAsyncOptions, ObserveModuleOptionsWithDefaults, ObserveOptions } from "./interfaces/observe-options.interface.js";
5
+ import { KeyOf } from "./types/key-of.type.js";
6
+ export declare function createObserveModule<Store extends Record<string, unknown>>(options?: CreateObserveModuleOptions): {
7
+ ObserveInstrument: NestApplicationOptions["instrument"];
8
+ ObserveModule: {
9
+ new (httpAdapterHost: HttpAdapterHost, asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>, options: ObserveModuleOptionsWithDefaults): {
10
+ readonly logger: Logger;
11
+ readonly httpAdapterHost: HttpAdapterHost;
12
+ readonly asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>;
13
+ readonly options: ObserveModuleOptionsWithDefaults;
14
+ };
15
+ forRoot(observeOpts: ObserveOptions): DynamicModule;
16
+ forRootAsync(options: ObserveModuleAsyncOptions): DynamicModule;
17
+ createAsyncProviders(asyncOptions: ObserveModuleAsyncOptions): Provider[];
18
+ createAsyncOptionsProvider(asyncOptions: ObserveModuleAsyncOptions): Provider;
19
+ };
20
+ };
@@ -0,0 +1,181 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
+ return function (target, key) { decorator(target, key, paramIndex); }
12
+ };
13
+ import { Inject, Logger, Module, } from "@nestjs/common";
14
+ import { DiscoveryModule, DiscoveryService, HttpAdapterHost, MetadataScanner, ModulesContainer, } from "@nestjs/core";
15
+ import { AsyncLocalStorage } from "async_hooks";
16
+ import { ObserveAgentSharedBuffer } from "./agent/observe-agent.shared-buffer.js";
17
+ import { ObserveAgentWorker } from "./agent/observe-agent.worker.js";
18
+ import { createInstanceDecorator } from "./instrument/create-instance-decorator.instrument.js";
19
+ import { CALLER_METADATA_KEY, OBSERVE_OPTIONS } from "./observe.constants.js";
20
+ import { GraphQLObserveAgentService } from "./protocols/graphql-observe-agent.service.js";
21
+ import { HttpObserveAgentService } from "./protocols/http-observe-agent.service.js";
22
+ import { QueueObserveAgentService } from "./protocols/queue-observe-agent.service.js";
23
+ import { RpcObserveAgentService } from "./protocols/rpc-observe-agent.service.js";
24
+ import { LoggerPatcherService } from "./services/logger-patcher.service.js";
25
+ import { NodeRuntimeMetricsService } from "./services/node-runtime-metrics.service.js";
26
+ import { OperationTraceRegistry } from "./services/operation-trace.registry.js";
27
+ import { StdoutForwarderService } from "./services/stdout-forwarder.service.js";
28
+ import { TraceSamplerService } from "./services/trace-sampler.service.js";
29
+ import { TracerService } from "./services/tracer.service.js";
30
+ import { assertModuleOptions } from "./utils/assert-module-options.util.js";
31
+ import { defaultTraceIdGenerator } from "./utils/default-trace-id-generator.util.js";
32
+ const MISSING_ASYNC_OPTIONS_PROVIDER = 'ObserveModule.forRootAsync() requires one of "useFactory", "useClass" or "useExisting".';
33
+ export function createObserveModule(options = {}) {
34
+ var ObserveModule_1;
35
+ options.traceIdKey ??= "traceId";
36
+ options.attachTraceIdToLogs ??= true;
37
+ options.traceIdGenerator ??= defaultTraceIdGenerator;
38
+ const asyncLocalStorage = new AsyncLocalStorage();
39
+ const operationTraceRegistry = new OperationTraceRegistry(asyncLocalStorage, options.sourceContext);
40
+ let ObserveModule = ObserveModule_1 = class ObserveModule {
41
+ httpAdapterHost;
42
+ asyncLocalStorage;
43
+ options;
44
+ logger = new Logger(ObserveModule_1.name);
45
+ constructor(httpAdapterHost, asyncLocalStorage, options) {
46
+ this.httpAdapterHost = httpAdapterHost;
47
+ this.asyncLocalStorage = asyncLocalStorage;
48
+ this.options = options;
49
+ }
50
+ static forRoot(observeOpts) {
51
+ return {
52
+ global: true,
53
+ module: ObserveModule_1,
54
+ providers: [
55
+ {
56
+ provide: OBSERVE_OPTIONS,
57
+ useValue: {
58
+ ...options,
59
+ ...observeOpts,
60
+ },
61
+ },
62
+ ],
63
+ };
64
+ }
65
+ static forRootAsync(options) {
66
+ return {
67
+ module: ObserveModule_1,
68
+ global: options.global ?? true,
69
+ imports: options.imports,
70
+ providers: [
71
+ ...this.createAsyncProviders(options),
72
+ ...(options.extraProviders || []),
73
+ ],
74
+ };
75
+ }
76
+ static createAsyncProviders(asyncOptions) {
77
+ if (asyncOptions.useExisting || asyncOptions.useFactory) {
78
+ return [this.createAsyncOptionsProvider(asyncOptions)];
79
+ }
80
+ const useClass = asyncOptions.useClass;
81
+ if (!useClass) {
82
+ throw new Error(MISSING_ASYNC_OPTIONS_PROVIDER);
83
+ }
84
+ return [
85
+ this.createAsyncOptionsProvider(asyncOptions),
86
+ {
87
+ provide: useClass,
88
+ useClass,
89
+ },
90
+ ];
91
+ }
92
+ static createAsyncOptionsProvider(asyncOptions) {
93
+ const useFactory = asyncOptions.useFactory;
94
+ if (useFactory) {
95
+ return {
96
+ provide: OBSERVE_OPTIONS,
97
+ useFactory: async (...args) => {
98
+ const opts = await useFactory(...args);
99
+ return {
100
+ ...options,
101
+ ...opts,
102
+ };
103
+ },
104
+ inject: asyncOptions.inject || [],
105
+ };
106
+ }
107
+ const optionsFactoryToken = asyncOptions.useExisting ?? asyncOptions.useClass;
108
+ if (!optionsFactoryToken) {
109
+ throw new Error(MISSING_ASYNC_OPTIONS_PROVIDER);
110
+ }
111
+ return {
112
+ provide: OBSERVE_OPTIONS,
113
+ useFactory: async (optionsFactory) => ({
114
+ ...options,
115
+ ...(await optionsFactory.createObserveOptions()),
116
+ }),
117
+ inject: [optionsFactoryToken],
118
+ };
119
+ }
120
+ };
121
+ ObserveModule = ObserveModule_1 = __decorate([
122
+ Module({
123
+ imports: [DiscoveryModule],
124
+ providers: [
125
+ {
126
+ provide: "ASSERT_MODULE_OPTIONS",
127
+ useFactory: assertModuleOptions,
128
+ inject: [{ token: OBSERVE_OPTIONS, optional: true }],
129
+ },
130
+ {
131
+ provide: AsyncLocalStorage,
132
+ useValue: asyncLocalStorage,
133
+ },
134
+ {
135
+ provide: OperationTraceRegistry,
136
+ useValue: operationTraceRegistry,
137
+ },
138
+ TracerService,
139
+ LoggerPatcherService,
140
+ HttpObserveAgentService,
141
+ RpcObserveAgentService,
142
+ GraphQLObserveAgentService,
143
+ ObserveAgentWorker,
144
+ ObserveAgentSharedBuffer,
145
+ TraceSamplerService,
146
+ NodeRuntimeMetricsService,
147
+ StdoutForwarderService,
148
+ QueueObserveAgentService,
149
+ ],
150
+ exports: [AsyncLocalStorage, TracerService],
151
+ }),
152
+ __param(2, Inject(OBSERVE_OPTIONS)),
153
+ __metadata("design:paramtypes", [HttpAdapterHost,
154
+ AsyncLocalStorage, Object])
155
+ ], ObserveModule);
156
+ return {
157
+ ObserveInstrument: {
158
+ instanceDecorator: createInstanceDecorator(asyncLocalStorage, operationTraceRegistry, {
159
+ traceIdKey: options.traceIdKey,
160
+ skipInstrumentation: (instance) => {
161
+ return ([asyncLocalStorage, operationTraceRegistry].includes(instance) ||
162
+ instance instanceof TraceSamplerService ||
163
+ instance instanceof TracerService ||
164
+ instance instanceof ObserveAgentSharedBuffer ||
165
+ instance instanceof GraphQLObserveAgentService ||
166
+ instance instanceof ModulesContainer ||
167
+ instance instanceof DiscoveryService ||
168
+ instance instanceof MetadataScanner ||
169
+ isResolverDecoratorHost(instance));
170
+ },
171
+ }),
172
+ },
173
+ ObserveModule,
174
+ };
175
+ }
176
+ function isResolverDecoratorHost(instance) {
177
+ const candidate = instance;
178
+ return (typeof candidate?.decorate === "function" &&
179
+ typeof candidate.setDecorator === "function" &&
180
+ typeof candidate.setOnRequestStartHook === "function");
181
+ }
@@ -0,0 +1,45 @@
1
+ import { FoldedStack } from "./fold-profile.util.js";
2
+ import { SpanSliceRecorder } from "./span-slice-recorder.js";
3
+ export declare const DEFAULT_SAMPLE_RATE_HZ = 99;
4
+ export declare const DEFAULT_WINDOW_MS = 60000;
5
+ export declare const DEFAULT_DUTY_MS = 10000;
6
+ export declare const DEFAULT_MAX_CPU_PERCENT = 3;
7
+ export interface ProfileWindow {
8
+ start: string;
9
+ stacks: FoldedStack[];
10
+ }
11
+ export interface CpuProfilerOptions {
12
+ sampleRateHz?: number;
13
+ windowMs?: number;
14
+ dutyMs?: number;
15
+ maxCpuPercent?: number;
16
+ onWindow: (window: ProfileWindow, sampleRateHz: number) => void;
17
+ onDisabled?: (reason: string) => void;
18
+ }
19
+ export declare class CpuProfilerService {
20
+ private readonly slices;
21
+ private readonly options;
22
+ private session;
23
+ private windowTimer;
24
+ private dutyTimer;
25
+ private running;
26
+ private disabled;
27
+ private readonly sampleRateHz;
28
+ private readonly windowMs;
29
+ private readonly dutyMs;
30
+ private readonly maxCpuPercent;
31
+ constructor(slices: SpanSliceRecorder, options: CpuProfilerOptions);
32
+ start(): Promise<void>;
33
+ stop(): Promise<void>;
34
+ isDisabled(): boolean;
35
+ private runWindow;
36
+ private windowStartedAt;
37
+ private windowStartedAtWallClock;
38
+ private cpuAtStart;
39
+ private beginBurst;
40
+ private finish;
41
+ private enforceBudget;
42
+ private disable;
43
+ private closeSession;
44
+ private postTo;
45
+ }
@@ -0,0 +1,146 @@
1
+ import { Session } from "node:inspector";
2
+ import { promisify } from "node:util";
3
+ import { foldProfile } from "./fold-profile.util.js";
4
+ export const DEFAULT_SAMPLE_RATE_HZ = 99;
5
+ export const DEFAULT_WINDOW_MS = 60_000;
6
+ export const DEFAULT_DUTY_MS = 10_000;
7
+ export const DEFAULT_MAX_CPU_PERCENT = 3;
8
+ export class CpuProfilerService {
9
+ slices;
10
+ options;
11
+ session = null;
12
+ windowTimer = null;
13
+ dutyTimer = null;
14
+ running = false;
15
+ disabled = false;
16
+ sampleRateHz;
17
+ windowMs;
18
+ dutyMs;
19
+ maxCpuPercent;
20
+ constructor(slices, options) {
21
+ this.slices = slices;
22
+ this.options = options;
23
+ this.sampleRateHz = options.sampleRateHz ?? DEFAULT_SAMPLE_RATE_HZ;
24
+ this.windowMs = options.windowMs ?? DEFAULT_WINDOW_MS;
25
+ this.dutyMs = Math.min(options.dutyMs ?? DEFAULT_DUTY_MS, this.windowMs);
26
+ this.maxCpuPercent = options.maxCpuPercent ?? DEFAULT_MAX_CPU_PERCENT;
27
+ }
28
+ async start() {
29
+ if (this.windowTimer || this.disabled) {
30
+ return;
31
+ }
32
+ this.windowTimer = setInterval(() => {
33
+ void this.runWindow();
34
+ }, this.windowMs);
35
+ this.windowTimer.unref?.();
36
+ await this.runWindow();
37
+ }
38
+ async stop() {
39
+ if (this.windowTimer) {
40
+ clearInterval(this.windowTimer);
41
+ this.windowTimer = null;
42
+ }
43
+ if (this.dutyTimer) {
44
+ clearTimeout(this.dutyTimer);
45
+ this.dutyTimer = null;
46
+ }
47
+ if (this.running) {
48
+ await this.finish().catch(() => undefined);
49
+ }
50
+ this.closeSession();
51
+ this.slices.reset();
52
+ }
53
+ isDisabled() {
54
+ return this.disabled;
55
+ }
56
+ async runWindow() {
57
+ if (this.running || this.disabled) {
58
+ return;
59
+ }
60
+ try {
61
+ await this.beginBurst();
62
+ }
63
+ catch (err) {
64
+ this.disable(`failed to start the profiler: ${String(err)}`);
65
+ return;
66
+ }
67
+ this.dutyTimer = setTimeout(() => {
68
+ void this.finish().catch((err) => this.disable(`failed to collect a profile: ${String(err)}`));
69
+ }, this.dutyMs);
70
+ this.dutyTimer.unref?.();
71
+ }
72
+ windowStartedAt = 0;
73
+ windowStartedAtWallClock = 0;
74
+ cpuAtStart = null;
75
+ async beginBurst() {
76
+ this.session = new Session();
77
+ this.session.connect();
78
+ const post = this.postTo(this.session);
79
+ await post("Profiler.enable");
80
+ await post("Profiler.setSamplingInterval", {
81
+ interval: Math.round(1_000_000 / this.sampleRateHz),
82
+ });
83
+ this.windowStartedAt = performance.now();
84
+ this.windowStartedAtWallClock = Date.now();
85
+ this.cpuAtStart = process.cpuUsage();
86
+ this.running = true;
87
+ await post("Profiler.start");
88
+ }
89
+ async finish() {
90
+ if (!this.session || !this.running) {
91
+ return;
92
+ }
93
+ const post = this.postTo(this.session);
94
+ const { profile } = (await post("Profiler.stop"));
95
+ this.running = false;
96
+ const burstMs = performance.now() - this.windowStartedAt;
97
+ const stacks = foldProfile(profile, {
98
+ startedAt: this.windowStartedAt,
99
+ slices: this.slices.drain(),
100
+ });
101
+ this.closeSession();
102
+ if (stacks.length > 0) {
103
+ this.options.onWindow({
104
+ start: new Date(this.windowStartedAtWallClock).toISOString(),
105
+ stacks,
106
+ }, this.sampleRateHz);
107
+ }
108
+ this.enforceBudget(burstMs);
109
+ }
110
+ enforceBudget(burstMs) {
111
+ if (!this.cpuAtStart || burstMs <= 0) {
112
+ return;
113
+ }
114
+ const used = process.cpuUsage(this.cpuAtStart);
115
+ const usedMs = (used.user + used.system) / 1000;
116
+ const percent = (usedMs / burstMs) * 100;
117
+ if (percent > 100 + this.maxCpuPercent) {
118
+ this.disable(`CPU use during the sampling burst was ${percent.toFixed(1)}% of one core`);
119
+ }
120
+ }
121
+ disable(reason) {
122
+ this.disabled = true;
123
+ this.running = false;
124
+ if (this.windowTimer) {
125
+ clearInterval(this.windowTimer);
126
+ this.windowTimer = null;
127
+ }
128
+ if (this.dutyTimer) {
129
+ clearTimeout(this.dutyTimer);
130
+ this.dutyTimer = null;
131
+ }
132
+ this.closeSession();
133
+ this.options.onDisabled?.(reason);
134
+ }
135
+ closeSession() {
136
+ try {
137
+ this.session?.disconnect();
138
+ }
139
+ catch {
140
+ }
141
+ this.session = null;
142
+ }
143
+ postTo(session) {
144
+ return promisify(session.post).bind(session);
145
+ }
146
+ }
@@ -0,0 +1,28 @@
1
+ import { SpanSlice } from "./span-slice-recorder.js";
2
+ export interface V8ProfileNode {
3
+ id: number;
4
+ callFrame: {
5
+ functionName: string;
6
+ url: string;
7
+ lineNumber: number;
8
+ columnNumber: number;
9
+ };
10
+ children?: number[];
11
+ }
12
+ export interface V8Profile {
13
+ nodes: V8ProfileNode[];
14
+ startTime: number;
15
+ endTime: number;
16
+ samples?: number[];
17
+ timeDeltas?: number[];
18
+ }
19
+ export interface FoldedStack {
20
+ frames: string[];
21
+ samples: number;
22
+ spanId?: string;
23
+ traceId?: string;
24
+ }
25
+ export declare function foldProfile(profile: V8Profile, options: {
26
+ startedAt: number;
27
+ slices?: SpanSlice[];
28
+ }): FoldedStack[];
@@ -0,0 +1,19 @@
1
+ import { ProfileWindow } from "./cpu-profiler.service.js";
2
+ export interface ProfileUploaderOptions {
3
+ endpoint: string;
4
+ serviceNode: string;
5
+ appKey?: string;
6
+ appSecret?: string;
7
+ onError?: (message: string) => void;
8
+ }
9
+ export declare class ProfileUploader {
10
+ private readonly options;
11
+ private readonly pending;
12
+ private inFlight;
13
+ constructor(options: ProfileUploaderOptions);
14
+ enqueue(window: ProfileWindow, sampleRateHz: number): void;
15
+ drain(): Promise<void>;
16
+ private send;
17
+ private isEntitlementError;
18
+ pendingCount(): number;
19
+ }
@@ -0,0 +1,88 @@
1
+ const MAX_PENDING_WINDOWS = 2;
2
+ export class ProfileUploader {
3
+ options;
4
+ pending = [];
5
+ inFlight = false;
6
+ constructor(options) {
7
+ this.options = options;
8
+ }
9
+ enqueue(window, sampleRateHz) {
10
+ if (window.stacks.length === 0) {
11
+ return;
12
+ }
13
+ if (this.pending.length >= MAX_PENDING_WINDOWS) {
14
+ this.pending.shift();
15
+ }
16
+ this.pending.push({ window, sampleRateHz });
17
+ void this.drain();
18
+ }
19
+ async drain() {
20
+ if (this.inFlight) {
21
+ return;
22
+ }
23
+ this.inFlight = true;
24
+ try {
25
+ while (this.pending.length > 0) {
26
+ const next = this.pending[0];
27
+ const sent = await this.send(next.window, next.sampleRateHz);
28
+ if (!sent) {
29
+ break;
30
+ }
31
+ this.pending.shift();
32
+ }
33
+ }
34
+ finally {
35
+ this.inFlight = false;
36
+ }
37
+ }
38
+ async send(window, sampleRateHz) {
39
+ const headers = {
40
+ "Content-Type": "application/json",
41
+ };
42
+ if (this.options.appKey && this.options.appSecret) {
43
+ headers["x-api-key"] = this.options.appKey;
44
+ headers["x-api-secret"] = this.options.appSecret;
45
+ }
46
+ try {
47
+ const response = await fetch(`${this.options.endpoint}/applications/profiles`, {
48
+ method: "POST",
49
+ headers,
50
+ body: JSON.stringify({
51
+ serviceNode: this.options.serviceNode,
52
+ sampleRateHz,
53
+ windows: [window],
54
+ }),
55
+ });
56
+ if (response.status === 403 &&
57
+ (await this.isEntitlementError(response))) {
58
+ this.options.onError?.("profiling is not included in this plan; discarding the window");
59
+ return true;
60
+ }
61
+ if (response.status === 401 || response.status === 403) {
62
+ this.options.onError?.(`profile upload rejected (${response.status}); check that appKey and appSecret are valid - the application is taken from the key`);
63
+ return false;
64
+ }
65
+ if (!response.ok) {
66
+ this.options.onError?.(`profile upload failed: ${response.status} ${response.statusText}`);
67
+ return false;
68
+ }
69
+ return true;
70
+ }
71
+ catch (err) {
72
+ this.options.onError?.(`profile upload failed: ${String(err)}`);
73
+ return false;
74
+ }
75
+ }
76
+ async isEntitlementError(response) {
77
+ try {
78
+ const body = (await response.clone().json());
79
+ return body?.code === "ENTITLEMENT_REQUIRED";
80
+ }
81
+ catch {
82
+ return false;
83
+ }
84
+ }
85
+ pendingCount() {
86
+ return this.pending.length;
87
+ }
88
+ }
@@ -0,0 +1,18 @@
1
+ export interface SpanSlice {
2
+ spanId: string;
3
+ traceId: string;
4
+ from: number;
5
+ to: number;
6
+ }
7
+ export declare class SpanSliceRecorder {
8
+ private readonly slices;
9
+ private readonly stack;
10
+ enter(traceId: string, spanId: string, at?: number): void;
11
+ exit(spanId: string | undefined, at?: number): void;
12
+ drain(until?: number): SpanSlice[];
13
+ reset(): void;
14
+ private closeTop;
15
+ private push;
16
+ }
17
+ export declare function activeSliceRecorder(): SpanSliceRecorder | null;
18
+ export declare function setActiveSliceRecorder(recorder: SpanSliceRecorder | null): void;
@@ -0,0 +1,78 @@
1
+ const MAX_SLICES = 20_000;
2
+ export class SpanSliceRecorder {
3
+ slices = [];
4
+ stack = [];
5
+ enter(traceId, spanId, at = performance.now()) {
6
+ this.closeTop(at);
7
+ this.stack.push({ spanId, traceId, since: at });
8
+ }
9
+ exit(spanId, at = performance.now()) {
10
+ const index = this.stack.findIndex((entry) => entry.spanId === spanId);
11
+ if (index === -1) {
12
+ return;
13
+ }
14
+ for (let depth = this.stack.length - 1; depth >= index; depth -= 1) {
15
+ const entry = this.stack[depth];
16
+ this.push({
17
+ spanId: entry.spanId,
18
+ traceId: entry.traceId,
19
+ from: entry.since,
20
+ to: at,
21
+ });
22
+ this.stack.pop();
23
+ const enclosing = this.stack[this.stack.length - 1];
24
+ if (enclosing) {
25
+ enclosing.since = at;
26
+ }
27
+ }
28
+ }
29
+ drain(until = performance.now()) {
30
+ const open = this.stack.map((entry) => ({
31
+ spanId: entry.spanId,
32
+ traceId: entry.traceId,
33
+ from: entry.since,
34
+ to: until,
35
+ }));
36
+ for (const entry of this.stack) {
37
+ entry.since = until;
38
+ }
39
+ const drained = [...this.slices, ...open].sort((a, b) => a.from - b.from);
40
+ this.slices.length = 0;
41
+ return drained;
42
+ }
43
+ reset() {
44
+ this.slices.length = 0;
45
+ this.stack.length = 0;
46
+ }
47
+ closeTop(at) {
48
+ const top = this.stack[this.stack.length - 1];
49
+ if (!top) {
50
+ return;
51
+ }
52
+ if (at > top.since) {
53
+ this.push({
54
+ spanId: top.spanId,
55
+ traceId: top.traceId,
56
+ from: top.since,
57
+ to: at,
58
+ });
59
+ }
60
+ top.since = at;
61
+ }
62
+ push(slice) {
63
+ if (slice.to <= slice.from) {
64
+ return;
65
+ }
66
+ if (this.slices.length >= MAX_SLICES) {
67
+ this.slices.shift();
68
+ }
69
+ this.slices.push(slice);
70
+ }
71
+ }
72
+ let activeRecorder = null;
73
+ export function activeSliceRecorder() {
74
+ return activeRecorder;
75
+ }
76
+ export function setActiveSliceRecorder(recorder) {
77
+ activeRecorder = recorder;
78
+ }
@@ -0,0 +1,58 @@
1
+ import { OnModuleInit } from "@nestjs/common";
2
+ import { DiscoveryService, MetadataScanner, ModuleRef } from "@nestjs/core";
3
+ import { AsyncLocalStorage } from "async_hooks";
4
+ import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
5
+ import { ObserveModuleOptionsWithDefaults } from "../interfaces/observe-options.interface.js";
6
+ import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
7
+ import { TraceSamplerService } from "../services/trace-sampler.service.js";
8
+ import { KeyOf } from "../types/key-of.type.js";
9
+ interface GqlRequestStartContext {
10
+ query?: string;
11
+ operationName?: string;
12
+ variables?: Record<string, unknown>;
13
+ context?: Record<string, unknown>;
14
+ }
15
+ interface GqlRequestEndContext extends GqlRequestStartContext {
16
+ errors?: readonly {
17
+ message?: string;
18
+ originalError?: unknown;
19
+ }[];
20
+ state?: unknown;
21
+ }
22
+ interface OperationState {
23
+ traceId: string;
24
+ spanId: string;
25
+ className: string;
26
+ methodKey: string;
27
+ previousCallerId: string | undefined;
28
+ store: Map<string, unknown> | undefined;
29
+ ownsTrace: boolean;
30
+ context: unknown;
31
+ }
32
+ export declare class GraphQLObserveAgentService<Store extends Record<string, unknown>> implements OnModuleInit {
33
+ private readonly asyncLocalStorage;
34
+ private readonly options;
35
+ private readonly operationTraceRegistry;
36
+ private readonly observeAgentSharedBuffer;
37
+ private readonly traceSamplerService;
38
+ private readonly moduleRef;
39
+ private readonly discoveryService;
40
+ private readonly metadataScanner;
41
+ private readonly logger;
42
+ private isPatched;
43
+ private resolverIndex;
44
+ constructor(asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>, options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, observeAgentSharedBuffer: ObserveAgentSharedBuffer, traceSamplerService: TraceSamplerService, moduleRef: ModuleRef, discoveryService: DiscoveryService, metadataScanner: MetadataScanner);
45
+ onModuleInit(): Promise<void>;
46
+ registerRequestHooksIfPossible(): Promise<void>;
47
+ onRequestStart(ctx: GqlRequestStartContext): OperationState | undefined;
48
+ onRequestEnd(ctx: GqlRequestEndContext): void;
49
+ private startWithinRequest;
50
+ private startAsOperation;
51
+ private openSpan;
52
+ private endOperationTrace;
53
+ private toSpanError;
54
+ private lookupResolverHandler;
55
+ private buildResolverIndex;
56
+ private applyAttributes;
57
+ }
58
+ export {};