@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,261 @@
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
+ var GraphQLObserveAgentService_1;
14
+ import { Inject, Injectable, Logger } from "@nestjs/common";
15
+ import { DiscoveryService, MetadataScanner, ModuleRef } from "@nestjs/core";
16
+ import { AsyncLocalStorage } from "async_hooks";
17
+ import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
18
+ import { CALLER_METADATA_KEY, OBSERVE_OPTIONS } from "../observe.constants.js";
19
+ import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
20
+ import { TraceSamplerService } from "../services/trace-sampler.service.js";
21
+ import { parseGraphQLOperation, toResolveInfoLike, } from "./graphql-operation-parser.js";
22
+ const GRAPHQL_PROTOCOL = "graphql";
23
+ const RESOLVER_TYPE_METADATA = "graphql:resolver_type";
24
+ const RESOLVER_NAME_METADATA = "graphql:resolver_name";
25
+ const ROOT_TYPE_NAMES = new Set(["Query", "Mutation", "Subscription"]);
26
+ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObserveAgentService {
27
+ asyncLocalStorage;
28
+ options;
29
+ operationTraceRegistry;
30
+ observeAgentSharedBuffer;
31
+ traceSamplerService;
32
+ moduleRef;
33
+ discoveryService;
34
+ metadataScanner;
35
+ logger = new Logger(GraphQLObserveAgentService_1.name);
36
+ isPatched = false;
37
+ resolverIndex;
38
+ constructor(asyncLocalStorage, options, operationTraceRegistry, observeAgentSharedBuffer, traceSamplerService, moduleRef, discoveryService, metadataScanner) {
39
+ this.asyncLocalStorage = asyncLocalStorage;
40
+ this.options = options;
41
+ this.operationTraceRegistry = operationTraceRegistry;
42
+ this.observeAgentSharedBuffer = observeAgentSharedBuffer;
43
+ this.traceSamplerService = traceSamplerService;
44
+ this.moduleRef = moduleRef;
45
+ this.discoveryService = discoveryService;
46
+ this.metadataScanner = metadataScanner;
47
+ void this.registerRequestHooksIfPossible();
48
+ }
49
+ async onModuleInit() {
50
+ await this.registerRequestHooksIfPossible();
51
+ }
52
+ async registerRequestHooksIfPossible() {
53
+ if (this.isPatched) {
54
+ return;
55
+ }
56
+ let ResolverDecoratorHost;
57
+ try {
58
+ ({ ResolverDecoratorHost } = (await import("@nestjs/graphql")));
59
+ }
60
+ catch {
61
+ return;
62
+ }
63
+ if (!ResolverDecoratorHost) {
64
+ this.logger.warn("The installed version of @nestjs/graphql does not expose 'ResolverDecoratorHost', so GraphQL operations cannot be instrumented. Upgrade @nestjs/graphql to collect per-operation traces.");
65
+ return;
66
+ }
67
+ let host;
68
+ try {
69
+ host = this.moduleRef.get(ResolverDecoratorHost, {
70
+ strict: false,
71
+ });
72
+ }
73
+ catch {
74
+ return;
75
+ }
76
+ if (!host) {
77
+ return;
78
+ }
79
+ if (typeof host.setOnRequestStartHook !== "function" ||
80
+ typeof host.setOnRequestEndHook !== "function") {
81
+ this.logger.warn("The installed version of @nestjs/graphql does not expose the GraphQL request lifecycle hooks ('setOnRequestStartHook' / 'setOnRequestEndHook'), so GraphQL operations cannot be instrumented. Upgrade @nestjs/graphql to collect per-operation traces.");
82
+ return;
83
+ }
84
+ host.setOnRequestStartHook((ctx) => this.onRequestStart(ctx));
85
+ host.setOnRequestEndHook((ctx) => this.onRequestEnd(ctx));
86
+ this.isPatched = true;
87
+ }
88
+ onRequestStart(ctx) {
89
+ const parsed = parseGraphQLOperation(ctx.query);
90
+ if (!parsed) {
91
+ return undefined;
92
+ }
93
+ const operationName = parsed.operationName ?? ctx.operationName;
94
+ const info = toResolveInfoLike({
95
+ ...parsed,
96
+ operationName,
97
+ });
98
+ if (this.options.graphql?.ignore?.(info)) {
99
+ return undefined;
100
+ }
101
+ const operationId = `${info.parentType.name}.${info.fieldName}`;
102
+ const attributes = {
103
+ originalUrl: parsed.sanitizedDocument,
104
+ };
105
+ const store = this.asyncLocalStorage.getStore();
106
+ const traceId = store?.get(this.options.traceIdKey);
107
+ if (traceId) {
108
+ return this.startWithinRequest(traceId, operationId, attributes, info, ctx);
109
+ }
110
+ return this.startAsOperation(operationId, attributes, info, ctx);
111
+ }
112
+ onRequestEnd(ctx) {
113
+ const state = ctx.state;
114
+ if (!state) {
115
+ return;
116
+ }
117
+ if (state.store) {
118
+ if (state.previousCallerId === undefined) {
119
+ state.store.delete(CALLER_METADATA_KEY);
120
+ }
121
+ else {
122
+ state.store.set(CALLER_METADATA_KEY, state.previousCallerId);
123
+ }
124
+ }
125
+ this.operationTraceRegistry.internalEndTraceStep(state.traceId, `${state.className}#${state.methodKey}`, state.className, state.methodKey, state.spanId, this.toSpanError(ctx.errors));
126
+ if (state.ownsTrace) {
127
+ this.endOperationTrace(state.traceId, state.context);
128
+ }
129
+ }
130
+ startWithinRequest(traceId, operationId, attributes, info, ctx) {
131
+ this.applyAttributes(info, ctx.context);
132
+ this.operationTraceRegistry.addGraphQLMetadataToTrace(traceId, {
133
+ operationId,
134
+ tags: this.options.graphql?.tags,
135
+ attributes,
136
+ });
137
+ return this.openSpan(traceId, info, ctx, false);
138
+ }
139
+ startAsOperation(operationId, attributes, info, ctx) {
140
+ const shouldCapture = this.traceSamplerService.shouldCapture("graphql", {
141
+ operationId,
142
+ });
143
+ if (!shouldCapture) {
144
+ return undefined;
145
+ }
146
+ const traceId = this.options.traceIdGenerator(info);
147
+ const store = new Map();
148
+ store.set(this.options.traceIdKey, traceId);
149
+ this.asyncLocalStorage.enterWith(store);
150
+ this.applyAttributes(info, ctx.context);
151
+ this.operationTraceRegistry.startTrace(traceId, {
152
+ protocol: GRAPHQL_PROTOCOL,
153
+ operationId,
154
+ tags: this.options.graphql?.tags,
155
+ attributes,
156
+ });
157
+ return this.openSpan(traceId, info, ctx, true);
158
+ }
159
+ openSpan(traceId, info, ctx, ownsTrace) {
160
+ const handler = this.lookupResolverHandler(info.parentType.name, info.fieldName);
161
+ const className = handler?.className ?? info.parentType.name;
162
+ const methodKey = handler?.methodKey ?? info.fieldName;
163
+ const store = this.asyncLocalStorage.getStore();
164
+ const previousCallerId = store?.get(CALLER_METADATA_KEY);
165
+ const spanId = this.operationTraceRegistry.internalStartTraceStep(traceId, className, methodKey, previousCallerId);
166
+ if (!spanId) {
167
+ return undefined;
168
+ }
169
+ store?.set(CALLER_METADATA_KEY, spanId);
170
+ return {
171
+ traceId,
172
+ spanId,
173
+ className,
174
+ methodKey,
175
+ previousCallerId,
176
+ store: store,
177
+ ownsTrace,
178
+ context: ctx.context,
179
+ };
180
+ }
181
+ endOperationTrace(traceId, context) {
182
+ setTimeout(async () => {
183
+ const userId = this.options.graphql?.getUserId?.(context);
184
+ this.operationTraceRegistry.endTrace(traceId, { userId });
185
+ const snapshot = await this.operationTraceRegistry.pluckSnapshot(traceId);
186
+ if (!snapshot) {
187
+ return;
188
+ }
189
+ this.observeAgentSharedBuffer.insertRequestSnapshot(snapshot);
190
+ }, 0);
191
+ }
192
+ toSpanError(errors) {
193
+ const [first] = errors ?? [];
194
+ if (!first) {
195
+ return undefined;
196
+ }
197
+ return first.originalError ?? first;
198
+ }
199
+ lookupResolverHandler(rootTypeName, fieldName) {
200
+ this.resolverIndex ??= this.buildResolverIndex();
201
+ return this.resolverIndex.get(`${rootTypeName}.${fieldName}`);
202
+ }
203
+ buildResolverIndex() {
204
+ const index = new Map();
205
+ for (const wrapper of this.discoveryService.getProviders()) {
206
+ const metatype = wrapper.metatype;
207
+ const prototype = wrapper.instance
208
+ ? Object.getPrototypeOf(wrapper.instance)
209
+ : typeof metatype === "function"
210
+ ? metatype.prototype
211
+ : undefined;
212
+ if (!prototype) {
213
+ continue;
214
+ }
215
+ const className = wrapper.instance?.constructor?.name ?? metatype?.name;
216
+ if (!className) {
217
+ continue;
218
+ }
219
+ for (const methodKey of this.metadataScanner.getAllMethodNames(prototype)) {
220
+ const method = prototype[methodKey];
221
+ if (typeof method !== "function") {
222
+ continue;
223
+ }
224
+ const rootTypeName = Reflect.getMetadata(RESOLVER_TYPE_METADATA, method);
225
+ if (!rootTypeName || !ROOT_TYPE_NAMES.has(rootTypeName)) {
226
+ continue;
227
+ }
228
+ const fieldName = Reflect.getMetadata(RESOLVER_NAME_METADATA, method) ?? methodKey;
229
+ index.set(`${rootTypeName}.${fieldName}`, { className, methodKey });
230
+ }
231
+ }
232
+ return index;
233
+ }
234
+ applyAttributes(info, context) {
235
+ if (!this.options.graphql?.setAttributes) {
236
+ return;
237
+ }
238
+ const store = this.asyncLocalStorage.getStore();
239
+ if (!store) {
240
+ return;
241
+ }
242
+ const attributes = this.options.graphql.setAttributes(info, context);
243
+ if (!attributes) {
244
+ return;
245
+ }
246
+ for (const [key, value] of Object.entries(attributes)) {
247
+ store.set(key, value);
248
+ }
249
+ }
250
+ };
251
+ GraphQLObserveAgentService = GraphQLObserveAgentService_1 = __decorate([
252
+ Injectable(),
253
+ __param(1, Inject(OBSERVE_OPTIONS)),
254
+ __metadata("design:paramtypes", [AsyncLocalStorage, Object, OperationTraceRegistry,
255
+ ObserveAgentSharedBuffer,
256
+ TraceSamplerService,
257
+ ModuleRef,
258
+ DiscoveryService,
259
+ MetadataScanner])
260
+ ], GraphQLObserveAgentService);
261
+ export { GraphQLObserveAgentService };
@@ -0,0 +1,10 @@
1
+ import { GraphQLResolveInfoLike } from "../interfaces/index.js";
2
+ export interface ParsedGraphQLOperation {
3
+ rootTypeName: string;
4
+ fieldName: string;
5
+ operationName?: string;
6
+ sanitizedDocument: string;
7
+ }
8
+ export declare function toResolveInfoLike(operation: Pick<ParsedGraphQLOperation, "rootTypeName" | "fieldName" | "operationName">): GraphQLResolveInfoLike;
9
+ export declare function parseGraphQLOperation(document: string | undefined): ParsedGraphQLOperation | undefined;
10
+ export declare function clearGraphQLOperationCache(): void;
@@ -0,0 +1,174 @@
1
+ const ROOT_TYPE_BY_KEYWORD = {
2
+ query: "Query",
3
+ mutation: "Mutation",
4
+ subscription: "Subscription",
5
+ };
6
+ const CACHE_LIMIT = 512;
7
+ const cache = new Map();
8
+ export function toResolveInfoLike(operation) {
9
+ return {
10
+ fieldName: operation.fieldName,
11
+ parentType: { name: operation.rootTypeName },
12
+ operation: {
13
+ operation: operation.rootTypeName.toLowerCase(),
14
+ name: operation.operationName
15
+ ? { value: operation.operationName }
16
+ : undefined,
17
+ },
18
+ };
19
+ }
20
+ export function parseGraphQLOperation(document) {
21
+ if (!document) {
22
+ return undefined;
23
+ }
24
+ if (cache.has(document)) {
25
+ return cache.get(document);
26
+ }
27
+ const parsed = scan(document);
28
+ if (cache.size >= CACHE_LIMIT) {
29
+ cache.delete(cache.keys().next().value);
30
+ }
31
+ cache.set(document, parsed);
32
+ return parsed;
33
+ }
34
+ export function clearGraphQLOperationCache() {
35
+ cache.clear();
36
+ }
37
+ function scan(document) {
38
+ const source = stripIgnoredTokens(document);
39
+ const words = [];
40
+ let index = 0;
41
+ while (index < source.length) {
42
+ const char = source[index];
43
+ if (isNameStart(char)) {
44
+ const start = index;
45
+ while (index < source.length && isNameChar(source[index])) {
46
+ index += 1;
47
+ }
48
+ words.push(source.slice(start, index));
49
+ continue;
50
+ }
51
+ if (char === "@") {
52
+ index += 1;
53
+ while (index < source.length && isNameChar(source[index])) {
54
+ index += 1;
55
+ }
56
+ continue;
57
+ }
58
+ if (char === "(") {
59
+ index = skipBalanced(source, index, "(", ")");
60
+ continue;
61
+ }
62
+ if (char === "{") {
63
+ if (words[0] === "fragment") {
64
+ index = skipBalanced(source, index, "{", "}");
65
+ words.length = 0;
66
+ continue;
67
+ }
68
+ return toOperation(words, readFirstFieldName(source, index + 1), source);
69
+ }
70
+ index += 1;
71
+ }
72
+ return undefined;
73
+ }
74
+ function toOperation(words, fieldName, source) {
75
+ if (!fieldName) {
76
+ return undefined;
77
+ }
78
+ const keyword = words[0] ? words[0].toLowerCase() : "query";
79
+ const rootTypeName = ROOT_TYPE_BY_KEYWORD[keyword];
80
+ if (!rootTypeName) {
81
+ return undefined;
82
+ }
83
+ return {
84
+ rootTypeName,
85
+ fieldName,
86
+ operationName: words[0] ? words[1] : undefined,
87
+ sanitizedDocument: source.replace(/\s+/g, " ").trim(),
88
+ };
89
+ }
90
+ function readFirstFieldName(source, from) {
91
+ let index = from;
92
+ while (index < source.length) {
93
+ const char = source[index];
94
+ if (isNameStart(char)) {
95
+ const start = index;
96
+ while (index < source.length && isNameChar(source[index])) {
97
+ index += 1;
98
+ }
99
+ const name = source.slice(start, index);
100
+ let lookahead = index;
101
+ while (lookahead < source.length && isIgnored(source[lookahead])) {
102
+ lookahead += 1;
103
+ }
104
+ if (source[lookahead] === ":") {
105
+ index = lookahead + 1;
106
+ continue;
107
+ }
108
+ return name;
109
+ }
110
+ if (char === "." || char === "}") {
111
+ return undefined;
112
+ }
113
+ index += 1;
114
+ }
115
+ return undefined;
116
+ }
117
+ function stripIgnoredTokens(document) {
118
+ let out = "";
119
+ let index = 0;
120
+ while (index < document.length) {
121
+ const char = document[index];
122
+ if (char === "#") {
123
+ while (index < document.length && document[index] !== "\n") {
124
+ index += 1;
125
+ }
126
+ continue;
127
+ }
128
+ if (char === '"') {
129
+ if (document.startsWith('"""', index)) {
130
+ const end = document.indexOf('"""', index + 3);
131
+ index = end === -1 ? document.length : end + 3;
132
+ }
133
+ else {
134
+ index += 1;
135
+ while (index < document.length && document[index] !== '"') {
136
+ index += document[index] === "\\" ? 2 : 1;
137
+ }
138
+ index += 1;
139
+ }
140
+ out += "_";
141
+ continue;
142
+ }
143
+ out += char;
144
+ index += 1;
145
+ }
146
+ return out;
147
+ }
148
+ function skipBalanced(source, from, open, close) {
149
+ let depth = 0;
150
+ let index = from;
151
+ while (index < source.length) {
152
+ const char = source[index];
153
+ if (char === open) {
154
+ depth += 1;
155
+ }
156
+ else if (char === close) {
157
+ depth -= 1;
158
+ if (depth === 0) {
159
+ return index + 1;
160
+ }
161
+ }
162
+ index += 1;
163
+ }
164
+ return source.length;
165
+ }
166
+ function isNameStart(char) {
167
+ return /[_A-Za-z]/.test(char);
168
+ }
169
+ function isNameChar(char) {
170
+ return /[_0-9A-Za-z]/.test(char);
171
+ }
172
+ function isIgnored(char) {
173
+ return char === " " || char === "\t" || char === "\n" || char === "\r";
174
+ }
@@ -0,0 +1,31 @@
1
+ import { OnModuleDestroy, OnModuleInit } from "@nestjs/common";
2
+ import { HttpAdapterHost } 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
+ export declare class HttpObserveAgentService<Store extends Record<string, unknown>> implements OnModuleInit, OnModuleDestroy {
10
+ private readonly httpAdapterHost;
11
+ private readonly asyncLocalStorage;
12
+ private readonly options;
13
+ private readonly operationTraceRegistry;
14
+ private readonly observeAgentSharedBuffer;
15
+ private readonly traceSamplerService;
16
+ private httpAdapterInitSubscription;
17
+ constructor(httpAdapterHost: HttpAdapterHost, asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>, options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, observeAgentSharedBuffer: ObserveAgentSharedBuffer, traceSamplerService: TraceSamplerService);
18
+ onModuleInit(): void;
19
+ onModuleDestroy(): void;
20
+ registerHttpHooks(): void;
21
+ startHttpRequestTracing(req: {
22
+ url: string;
23
+ method: string;
24
+ protocol: string;
25
+ }, res: unknown, done: () => void): void;
26
+ endHttpRequestTracing(req: unknown, res: {
27
+ statusCode: number;
28
+ }): void;
29
+ private evictTraceOnClientAbort;
30
+ private shouldIgnoreRequest;
31
+ }
@@ -0,0 +1,186 @@
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, Injectable, } from "@nestjs/common";
14
+ import { HttpAdapterHost } from "@nestjs/core";
15
+ import { AsyncLocalStorage } from "async_hooks";
16
+ import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
17
+ import { OBSERVE_OPTIONS } from "../observe.constants.js";
18
+ import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
19
+ import { TraceSamplerService } from "../services/trace-sampler.service.js";
20
+ import { redactUrlQuery } from "../utils/redact-url-query.js";
21
+ const ABORTED_TRACE_EVICTION_GRACE_MS = 30_000;
22
+ let HttpObserveAgentService = class HttpObserveAgentService {
23
+ httpAdapterHost;
24
+ asyncLocalStorage;
25
+ options;
26
+ operationTraceRegistry;
27
+ observeAgentSharedBuffer;
28
+ traceSamplerService;
29
+ httpAdapterInitSubscription;
30
+ constructor(httpAdapterHost, asyncLocalStorage, options, operationTraceRegistry, observeAgentSharedBuffer, traceSamplerService) {
31
+ this.httpAdapterHost = httpAdapterHost;
32
+ this.asyncLocalStorage = asyncLocalStorage;
33
+ this.options = options;
34
+ this.operationTraceRegistry = operationTraceRegistry;
35
+ this.observeAgentSharedBuffer = observeAgentSharedBuffer;
36
+ this.traceSamplerService = traceSamplerService;
37
+ const { httpAdapter } = this.httpAdapterHost;
38
+ if (!httpAdapter) {
39
+ return;
40
+ }
41
+ if (!("setOnRouteTriggered" in httpAdapter)) {
42
+ throw new Error("The HTTP adapter does not support the 'setOnRouteTriggered' method. Please ensure you are using the latest version of the NestJS HTTP adapter that supports this method.");
43
+ }
44
+ httpAdapter.setOnRouteTriggered((requestMethod, path) => {
45
+ const store = this.asyncLocalStorage.getStore();
46
+ if (!store) {
47
+ return;
48
+ }
49
+ const traceId = store.get(this.options.traceIdKey);
50
+ if (!traceId) {
51
+ return;
52
+ }
53
+ this.operationTraceRegistry.addRouteMetadataToTrace(traceId, requestMethod, path);
54
+ });
55
+ }
56
+ onModuleInit() {
57
+ this.httpAdapterInitSubscription = this.httpAdapterHost.init$?.subscribe(() => this.registerHttpHooks());
58
+ }
59
+ onModuleDestroy() {
60
+ if (this.httpAdapterInitSubscription) {
61
+ this.httpAdapterInitSubscription.unsubscribe();
62
+ }
63
+ }
64
+ registerHttpHooks() {
65
+ const { httpAdapter } = this.httpAdapterHost;
66
+ if (!httpAdapter) {
67
+ return;
68
+ }
69
+ httpAdapter.setOnRequestHook((req, res, done) => {
70
+ this.startHttpRequestTracing(req, res, done);
71
+ });
72
+ httpAdapter.setOnResponseHook((req, res) => {
73
+ this.endHttpRequestTracing(req, res);
74
+ });
75
+ }
76
+ startHttpRequestTracing(req, res, done) {
77
+ const store = new Map();
78
+ this.asyncLocalStorage.run(store, () => {
79
+ const traceId = this.options.traceIdGenerator(req);
80
+ store.set(this.options.traceIdKey, traceId);
81
+ if (this.options.http?.setAttributes) {
82
+ const attributes = this.options.http?.setAttributes?.(req);
83
+ if (attributes) {
84
+ for (const [key, value] of Object.entries(attributes)) {
85
+ store.set(key, value);
86
+ }
87
+ }
88
+ }
89
+ if (this.shouldIgnoreRequest(req)) {
90
+ return done();
91
+ }
92
+ const shouldCapture = this.traceSamplerService.shouldCapture("http", {
93
+ url: req.url,
94
+ method: req.method,
95
+ });
96
+ if (!shouldCapture) {
97
+ return done();
98
+ }
99
+ const redactedUrl = redactUrlQuery(req.url);
100
+ const originalUrl = this.options.http?.queryParamsObfuscateRegex
101
+ ? redactedUrl.replaceAll(this.options.http.queryParamsObfuscateRegex, "[REDACTED]")
102
+ : redactedUrl;
103
+ this.operationTraceRegistry.startTrace(traceId, {
104
+ protocol: req.protocol,
105
+ tags: this.options.http?.tags,
106
+ attributes: {
107
+ method: req.method,
108
+ originalUrl,
109
+ },
110
+ });
111
+ this.evictTraceOnClientAbort(res, traceId);
112
+ done();
113
+ });
114
+ }
115
+ endHttpRequestTracing(req, res) {
116
+ const store = this.asyncLocalStorage.getStore();
117
+ if (!store) {
118
+ return;
119
+ }
120
+ const traceId = store.get(this.options.traceIdKey);
121
+ if (!traceId) {
122
+ return;
123
+ }
124
+ setTimeout(async () => {
125
+ let userId;
126
+ if (this.options.http?.getUserId) {
127
+ userId = this.options.http?.getUserId?.(req);
128
+ }
129
+ this.operationTraceRegistry.endTrace(traceId, {
130
+ statusCode: res.statusCode,
131
+ userId,
132
+ });
133
+ const snapshot = await this.operationTraceRegistry.pluckSnapshot(traceId);
134
+ if (!snapshot) {
135
+ return;
136
+ }
137
+ this.observeAgentSharedBuffer.insertRequestSnapshot(snapshot);
138
+ }, 0);
139
+ }
140
+ evictTraceOnClientAbort(res, traceId) {
141
+ const response = res;
142
+ if (typeof response?.on !== "function") {
143
+ return;
144
+ }
145
+ response.on("close", () => {
146
+ if (response.writableFinished) {
147
+ return;
148
+ }
149
+ const timer = setTimeout(() => this.operationTraceRegistry.abandonTrace(traceId), ABORTED_TRACE_EVICTION_GRACE_MS);
150
+ timer.unref?.();
151
+ });
152
+ }
153
+ shouldIgnoreRequest(req) {
154
+ if (typeof this.options.http?.ignore === "function") {
155
+ return this.options.http.ignore(req);
156
+ }
157
+ if (Array.isArray(this.options.http?.ignore)) {
158
+ const blocklist = this.options.http.ignore;
159
+ return blocklist.some((item) => {
160
+ if (typeof item === "string") {
161
+ return req.url === item;
162
+ }
163
+ if (item instanceof RegExp) {
164
+ return item.test(req.url);
165
+ }
166
+ if (typeof item === "object") {
167
+ return (item.method === req.method &&
168
+ (typeof item.path === "string"
169
+ ? req.url === item.path
170
+ : item.path.test(req.url)));
171
+ }
172
+ return false;
173
+ });
174
+ }
175
+ return false;
176
+ }
177
+ };
178
+ HttpObserveAgentService = __decorate([
179
+ Injectable(),
180
+ __param(2, Inject(OBSERVE_OPTIONS)),
181
+ __metadata("design:paramtypes", [HttpAdapterHost,
182
+ AsyncLocalStorage, Object, OperationTraceRegistry,
183
+ ObserveAgentSharedBuffer,
184
+ TraceSamplerService])
185
+ ], HttpObserveAgentService);
186
+ export { HttpObserveAgentService };
@@ -0,0 +1,15 @@
1
+ import { AsyncLocalStorage } from "async_hooks";
2
+ import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
3
+ import { ObserveModuleOptionsWithDefaults } from "../interfaces/index.js";
4
+ import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
5
+ import { KeyOf } from "../types/key-of.type.js";
6
+ export declare class QueueObserveAgentService<Store extends Record<string, unknown>> {
7
+ private readonly observeAgentSharedBuffer;
8
+ private readonly options;
9
+ private readonly operationTraceRegistry;
10
+ private readonly asyncLocalStorage;
11
+ private readonly logger;
12
+ constructor(observeAgentSharedBuffer: ObserveAgentSharedBuffer, options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>);
13
+ private readQueueMetadata;
14
+ private patchDecorate;
15
+ }