@nestjs/observe 0.1.3 → 0.1.5
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/dist/.tsbuildinfo +1 -1
- package/dist/agent/detached-observe-worker.js +52 -0
- package/dist/agent/observe-agent.shared-buffer.js +13 -0
- package/dist/instrument/create-instance-decorator.instrument.js +121 -8
- package/dist/interfaces/observe-options.interface.d.ts +15 -0
- package/dist/observe.module.js +51 -27
- package/dist/profiling/profile-uploader.d.ts +13 -0
- package/dist/profiling/profile-uploader.js +41 -1
- package/dist/protocols/http-observe-agent.service.d.ts +8 -0
- package/dist/protocols/http-observe-agent.service.js +21 -2
- package/package.json +3 -2
|
@@ -48,6 +48,42 @@ export const detachedObserveWorker = () => {
|
|
|
48
48
|
* that it never competes with anything.
|
|
49
49
|
*/
|
|
50
50
|
const AUTH_REJECTION_REPORT_EVERY = 720;
|
|
51
|
+
/**
|
|
52
|
+
* When sending may resume after the collector answered 429.
|
|
53
|
+
*
|
|
54
|
+
* A 429 means the account is out of credits or over budget, and that does
|
|
55
|
+
* not change batch to batch: retrying at the flush cadence is sixty more
|
|
56
|
+
* refusals in five minutes, each costing the collector a request and this
|
|
57
|
+
* process a log line. So sends pause outright. The main thread keeps
|
|
58
|
+
* overwriting the shared buffer with newer batches in the meantime - the
|
|
59
|
+
* buffer holds exactly one, so pausing drops data by replacement rather
|
|
60
|
+
* than growing a queue - and once the pause lapses the next flush goes out
|
|
61
|
+
* normally. If the collector is still refusing, it answers 429 again and
|
|
62
|
+
* the pause restarts.
|
|
63
|
+
*/
|
|
64
|
+
let rateLimitedUntil = 0;
|
|
65
|
+
/**
|
|
66
|
+
* How long to pause when the 429 carries no usable Retry-After. Long enough
|
|
67
|
+
* that a depleted account is not being polled, short enough that a topped-up
|
|
68
|
+
* one resumes within minutes.
|
|
69
|
+
*/
|
|
70
|
+
const RATE_LIMIT_PAUSE_MS = 5 * 60 * 1000;
|
|
71
|
+
/** Ceiling on a server-sent Retry-After, so a bad header cannot park the
|
|
72
|
+
* worker for a day. */
|
|
73
|
+
const RATE_LIMIT_PAUSE_MAX_MS = 60 * 60 * 1000;
|
|
74
|
+
/**
|
|
75
|
+
* How long to pause for, from the response's Retry-After when it carries
|
|
76
|
+
* one. Only the delta-seconds form is parsed - the HTTP-date form is rare
|
|
77
|
+
* on rate limits and mis-parsing it risks an enormous pause - and anything
|
|
78
|
+
* absent, malformed, or out of range falls back to the default.
|
|
79
|
+
*/
|
|
80
|
+
const rateLimitPauseMs = (response) => {
|
|
81
|
+
const retryAfter = Number(response.headers.get("retry-after"));
|
|
82
|
+
if (Number.isFinite(retryAfter) && retryAfter > 0) {
|
|
83
|
+
return Math.min(retryAfter * 1000, RATE_LIMIT_PAUSE_MAX_MS);
|
|
84
|
+
}
|
|
85
|
+
return RATE_LIMIT_PAUSE_MS;
|
|
86
|
+
};
|
|
51
87
|
/**
|
|
52
88
|
* How long to block waiting for the main thread to release the lock, and how
|
|
53
89
|
* long to sleep when the buffer holds nothing.
|
|
@@ -96,6 +132,12 @@ export const detachedObserveWorker = () => {
|
|
|
96
132
|
* immediately or to sleep first.
|
|
97
133
|
*/
|
|
98
134
|
const sendInstrumentationJsonData = async () => {
|
|
135
|
+
if (Date.now() < rateLimitedUntil) {
|
|
136
|
+
// Rate-limited: not even worth taking the lock. Returning false routes
|
|
137
|
+
// through the idle sleep, and the main thread goes on replacing the
|
|
138
|
+
// buffered batch with fresher ones.
|
|
139
|
+
return false;
|
|
140
|
+
}
|
|
99
141
|
waitWhileLocked();
|
|
100
142
|
if (!acquireLock()) {
|
|
101
143
|
// Lost the race to the main thread, which is flushing. Nothing to report
|
|
@@ -145,6 +187,16 @@ export const detachedObserveWorker = () => {
|
|
|
145
187
|
}
|
|
146
188
|
return true;
|
|
147
189
|
}
|
|
190
|
+
if (response.status === 429) {
|
|
191
|
+
const pauseMs = rateLimitPauseMs(response);
|
|
192
|
+
rateLimitedUntil = Date.now() + pauseMs;
|
|
193
|
+
// One line per pause window, so a long depletion reads as one line
|
|
194
|
+
// every few minutes rather than one per flush. The batch is dropped
|
|
195
|
+
// - `finally` clears the buffer - same as every other failure here.
|
|
196
|
+
parentPort.postMessage(`Error: Telemetry rate-limited (429) - the account may be out of credits or over budget. ` +
|
|
197
|
+
`Pausing sends for ${Math.round(pauseMs / 60000)} minute(s); batches in the meantime are dropped.`);
|
|
198
|
+
return true;
|
|
199
|
+
}
|
|
148
200
|
// Read as text, defensively: an error body is not guaranteed to be
|
|
149
201
|
// JSON, and a parse failure here must not fall through to the catch
|
|
150
202
|
// below and report a reachable collector as unreachable.
|
|
@@ -77,6 +77,19 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
77
77
|
this.options = options;
|
|
78
78
|
}
|
|
79
79
|
insertRequestSnapshot(snapshot) {
|
|
80
|
+
// A request can end before its route metadata is ever captured - an auth
|
|
81
|
+
// guard rejecting it, or a GraphQL document that never reaches a resolver
|
|
82
|
+
// (`{ __typename }`) - leaving no operation id. The collector requires one
|
|
83
|
+
// on every snapshot and rejects the *entire batch* over a single miss, so
|
|
84
|
+
// fall back to the transport's URL, and drop the snapshot when even that
|
|
85
|
+
// is absent rather than poison the batch it would ride in.
|
|
86
|
+
snapshot.operationId ??= snapshot.attributes?.originalUrl;
|
|
87
|
+
if (!snapshot.operationId) {
|
|
88
|
+
if (this.options.debug) {
|
|
89
|
+
this.logger.debug(`Snapshot for traceId "${snapshot.traceId}" has no operation id nor URL to fall back on. Ignoring snapshot.`);
|
|
90
|
+
}
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
80
93
|
if (!this._mainThreadBuffer) {
|
|
81
94
|
this._mainThreadBuffer = this.createEmptyPayload();
|
|
82
95
|
}
|
|
@@ -36,6 +36,19 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
36
36
|
spec.setActive(true);
|
|
37
37
|
const callerId = store?.get(CALLER_METADATA_KEY);
|
|
38
38
|
const newStepId = operationTraceRegistry.internalStartTraceStep(requestId, className, methodName, callerId);
|
|
39
|
+
// No step means the registry holds no snapshot for this trace id: the
|
|
40
|
+
// request was dropped by `http.ignore` or sampled out, but its store
|
|
41
|
+
// still carries the id - log correlation needs it there. Nothing was
|
|
42
|
+
// opened, so nothing must be closed; without this bail-out every
|
|
43
|
+
// provider call on an ignored route logged a registry error.
|
|
44
|
+
if (newStepId === undefined) {
|
|
45
|
+
try {
|
|
46
|
+
return callUntraced(this, args);
|
|
47
|
+
}
|
|
48
|
+
finally {
|
|
49
|
+
spec.setActive(false);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
39
52
|
const onReturnValue = (res) => {
|
|
40
53
|
operationTraceRegistry.internalEndTraceStep(requestId, spanId, className, methodName, newStepId);
|
|
41
54
|
return res;
|
|
@@ -104,6 +117,22 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
104
117
|
if (options.skipInstrumentation(instance)) {
|
|
105
118
|
return instance;
|
|
106
119
|
}
|
|
120
|
+
// Native private members (`this.#x`) are branded to the instance itself,
|
|
121
|
+
// and no proxy trap can satisfy that check: a method invoked with the
|
|
122
|
+
// proxy as its receiver throws "Receiver must be an instance of class".
|
|
123
|
+
// Such classes get the raw instance as receiver instead - trading away
|
|
124
|
+
// nested `this.other()` spans (those calls no longer pass through the
|
|
125
|
+
// proxy) for methods that run at all.
|
|
126
|
+
let hasPrivateMembers;
|
|
127
|
+
try {
|
|
128
|
+
hasPrivateMembers = usesNativePrivateMembers(instance);
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
// Reading the prototype ran a trap that threw (nestjs-cls proxy
|
|
132
|
+
// providers do this outside a CLS context). An instance that cannot be
|
|
133
|
+
// inspected cannot be instrumented; hand it back untouched.
|
|
134
|
+
return instance;
|
|
135
|
+
}
|
|
107
136
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
|
|
108
137
|
const methodRefsCache = new WeakMap();
|
|
109
138
|
const currentlyTracing = new WeakMap();
|
|
@@ -111,11 +140,17 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
111
140
|
get: (target, prop, receiver) => {
|
|
112
141
|
const attributeValue = Reflect.get(target, prop);
|
|
113
142
|
const isFunction = typeof attributeValue === "function" && prop !== "constructor";
|
|
114
|
-
const shouldProxy = isFunction &&
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
143
|
+
const shouldProxy = isFunction &&
|
|
144
|
+
!isClass(attributeValue) &&
|
|
145
|
+
// A callable *object* - a Mongoose model, an Axios instance, an
|
|
146
|
+
// EventEmitter-backed client - is a field, not a method. The traced
|
|
147
|
+
// wrapper is a fresh bound function, so wrapping one silently drops
|
|
148
|
+
// everything hanging off it (`svc.model.find` became undefined
|
|
149
|
+
// mid-trace). This subsumes the Axios special case that used to sit
|
|
150
|
+
// here: an Axios instance is a bound `request` carrying its API as
|
|
151
|
+
// own properties.
|
|
152
|
+
!isCallableObject(attributeValue);
|
|
153
|
+
if (!shouldProxy) {
|
|
119
154
|
return Reflect.get(target, prop);
|
|
120
155
|
}
|
|
121
156
|
const className = target.constructor.name;
|
|
@@ -125,7 +160,13 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
125
160
|
if (methodRefsCache.has(attributeValue)) {
|
|
126
161
|
return methodRefsCache.get(attributeValue);
|
|
127
162
|
}
|
|
128
|
-
|
|
163
|
+
// For a private-member class, `Reflect.get` with the proxy as receiver
|
|
164
|
+
// would already throw on an accessor that touches `this.#x`, so the
|
|
165
|
+
// value fetched against the target above is reused instead.
|
|
166
|
+
const originalMethod = hasPrivateMembers
|
|
167
|
+
? attributeValue
|
|
168
|
+
: Reflect.get(target, prop, receiver);
|
|
169
|
+
const tracedReceiver = hasPrivateMembers ? target : receiver;
|
|
129
170
|
const proxyFn = createTracedWrapper({
|
|
130
171
|
className,
|
|
131
172
|
methodName,
|
|
@@ -144,8 +185,10 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
144
185
|
}
|
|
145
186
|
},
|
|
146
187
|
// Traced calls run against the proxy so that a method calling into
|
|
147
|
-
// itself (`this.other()`) is instrumented as a nested step
|
|
148
|
-
|
|
188
|
+
// itself (`this.other()`) is instrumented as a nested step - except
|
|
189
|
+
// for private-member classes, whose brand checks only the raw
|
|
190
|
+
// instance satisfies.
|
|
191
|
+
call: named(frameName, (_thisArg, args) => originalMethod.apply(tracedReceiver, args)),
|
|
149
192
|
callUntraced: named(frameName, (_thisArg, args) => originalMethod.apply(target, args)),
|
|
150
193
|
});
|
|
151
194
|
// V8 hard-codes the type name of a stack frame to "Proxy" whenever the
|
|
@@ -227,6 +270,76 @@ function escapeRegExp(value) {
|
|
|
227
270
|
function isClass(value) {
|
|
228
271
|
return /^\s*class\s+/.test(value.toString());
|
|
229
272
|
}
|
|
273
|
+
/**
|
|
274
|
+
* The prototypes every ordinary function - plain, async, generator, async
|
|
275
|
+
* generator, arrow, bound - hangs off. Anything else above a callable means it
|
|
276
|
+
* was built by a library as an object that happens to be invocable.
|
|
277
|
+
*/
|
|
278
|
+
const INTRINSIC_FUNCTION_PROTOTYPES = new Set([
|
|
279
|
+
Function.prototype,
|
|
280
|
+
Object.getPrototypeOf(async function () { }),
|
|
281
|
+
Object.getPrototypeOf(function* () { }),
|
|
282
|
+
Object.getPrototypeOf(async function* () { }),
|
|
283
|
+
]);
|
|
284
|
+
/**
|
|
285
|
+
* Whether a function is really an object with a call signature - a Mongoose
|
|
286
|
+
* model with its statics, a client with methods hung directly on it - rather
|
|
287
|
+
* than a method to be traced.
|
|
288
|
+
*
|
|
289
|
+
* Two tells, either sufficient: a prototype that is not one of the intrinsic
|
|
290
|
+
* function prototypes (Mongoose sets `M.__proto__ = Model`), or own enumerable
|
|
291
|
+
* properties, which a plain method never carries but statics are. The traced
|
|
292
|
+
* wrapper is a fresh function that preserves only `name` and reflect-metadata,
|
|
293
|
+
* so anything matching here must be handed out untouched.
|
|
294
|
+
*/
|
|
295
|
+
function isCallableObject(fn) {
|
|
296
|
+
return (!INTRINSIC_FUNCTION_PROTOTYPES.has(Object.getPrototypeOf(fn)) ||
|
|
297
|
+
Object.keys(fn).length > 0);
|
|
298
|
+
}
|
|
299
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
|
|
300
|
+
const privateMemberCache = new WeakMap();
|
|
301
|
+
/**
|
|
302
|
+
* Whether any class in the instance's prototype chain declares native private
|
|
303
|
+
* members (`#field`, `#method()`).
|
|
304
|
+
*
|
|
305
|
+
* Detection reads the class source: private members can only be touched from
|
|
306
|
+
* inside the lexical class body, so a class whose text contains no `#name`
|
|
307
|
+
* token cannot perform a brand check. A `#` inside a string or comment can
|
|
308
|
+
* false-positive, which merely selects the raw-instance receiver - every call
|
|
309
|
+
* still works, only nested self-call spans are lost - so the cheap test is
|
|
310
|
+
* safe to lean on.
|
|
311
|
+
*/
|
|
312
|
+
function usesNativePrivateMembers(instance) {
|
|
313
|
+
let proto = Object.getPrototypeOf(instance);
|
|
314
|
+
while (proto && proto !== Object.prototype) {
|
|
315
|
+
const ctor = proto.constructor;
|
|
316
|
+
if (typeof ctor === "function" && ctor !== Object) {
|
|
317
|
+
let hasPrivate = privateMemberCache.get(ctor);
|
|
318
|
+
if (hasPrivate === undefined) {
|
|
319
|
+
hasPrivate = declaresPrivateMembers(ctor);
|
|
320
|
+
privateMemberCache.set(ctor, hasPrivate);
|
|
321
|
+
}
|
|
322
|
+
if (hasPrivate) {
|
|
323
|
+
return true;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
proto = Object.getPrototypeOf(proto);
|
|
327
|
+
}
|
|
328
|
+
return false;
|
|
329
|
+
}
|
|
330
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
|
|
331
|
+
function declaresPrivateMembers(ctor) {
|
|
332
|
+
try {
|
|
333
|
+
// `#` starting a private name is never preceded by an identifier
|
|
334
|
+
// character; `obj.#x` and `#x in obj` and declarations all match.
|
|
335
|
+
return /(^|[^\w$])#[\w$]/.test(Function.prototype.toString.call(ctor));
|
|
336
|
+
}
|
|
337
|
+
catch {
|
|
338
|
+
// A constructor whose source is unavailable (bound functions, some
|
|
339
|
+
// natives) cannot be a class body with private members.
|
|
340
|
+
return false;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
230
343
|
function generateSpanId(instance, methodKey) {
|
|
231
344
|
return `${instance.constructor.name}#${methodKey}`;
|
|
232
345
|
}
|
|
@@ -63,6 +63,21 @@ export interface CreateObserveModuleOptions {
|
|
|
63
63
|
* @default true
|
|
64
64
|
*/
|
|
65
65
|
attachTraceIdToLogs?: boolean;
|
|
66
|
+
/**
|
|
67
|
+
* Excludes providers from instrumentation. Return true for an instance that
|
|
68
|
+
* should stay untouched - no proxy is placed around it and none of its
|
|
69
|
+
* methods produce spans.
|
|
70
|
+
*
|
|
71
|
+
* Runs before the built-in checks, so it also shields providers that
|
|
72
|
+
* cannot even be inspected safely: some libraries (nestjs-cls proxy
|
|
73
|
+
* providers, for instance) register proxies that throw on any property
|
|
74
|
+
* access outside their own context. Those are skipped automatically when
|
|
75
|
+
* inspection throws, but this hook lets you exclude them - or anything
|
|
76
|
+
* else - explicitly.
|
|
77
|
+
* @example (instance) => instance instanceof MyUninstrumentableService
|
|
78
|
+
* @default () => false
|
|
79
|
+
*/
|
|
80
|
+
skipInstrumentation?: (instance: unknown) => boolean;
|
|
66
81
|
/**
|
|
67
82
|
* Attaches the source around each in-app stack frame to captured errors, so the
|
|
68
83
|
* throw site can be shown with its code rather than just a file and line.
|
package/dist/observe.module.js
CHANGED
|
@@ -41,6 +41,7 @@ export function createObserveModule(options = {}) {
|
|
|
41
41
|
options.traceIdKey ??= "traceId";
|
|
42
42
|
options.attachTraceIdToLogs ??= true;
|
|
43
43
|
options.traceIdGenerator ??= defaultTraceIdGenerator;
|
|
44
|
+
options.skipInstrumentation ??= () => false;
|
|
44
45
|
const asyncLocalStorage = new AsyncLocalStorage();
|
|
45
46
|
const operationTraceRegistry = new OperationTraceRegistry(asyncLocalStorage, options.sourceContext);
|
|
46
47
|
let ObserveModule = ObserveModule_1 = class ObserveModule {
|
|
@@ -166,37 +167,60 @@ export function createObserveModule(options = {}) {
|
|
|
166
167
|
__metadata("design:paramtypes", [HttpAdapterHost,
|
|
167
168
|
AsyncLocalStorage, Object])
|
|
168
169
|
], ObserveModule);
|
|
170
|
+
const skipInstrumentation = (instance) => {
|
|
171
|
+
try {
|
|
172
|
+
return (
|
|
173
|
+
// The user hook runs first so it can exclude providers whose mere
|
|
174
|
+
// inspection throws before the structural checks below ever touch
|
|
175
|
+
// them.
|
|
176
|
+
options.skipInstrumentation(instance) ||
|
|
177
|
+
[asyncLocalStorage, operationTraceRegistry].includes(instance) ||
|
|
178
|
+
instance instanceof TraceSamplerService ||
|
|
179
|
+
instance instanceof TracerService ||
|
|
180
|
+
instance instanceof ObserveAgentSharedBuffer ||
|
|
181
|
+
// Its methods run *inside* the traces it opens, so instrumenting it
|
|
182
|
+
// would put a span for the agent itself at the root of every GraphQL
|
|
183
|
+
// operation it records.
|
|
184
|
+
instance instanceof GraphQLObserveAgentService ||
|
|
185
|
+
// Same reason: its wrapper runs inside the job traces it opens.
|
|
186
|
+
instance instanceof ScheduleObserveAgentService ||
|
|
187
|
+
// Nest's discovery machinery, which the GraphQL agent walks to map
|
|
188
|
+
// root fields back to their resolver classes. It has to stay
|
|
189
|
+
// unproxied: ModulesContainer extends Map, and a Map method invoked
|
|
190
|
+
// with the instrumentation proxy as its receiver throws "called on
|
|
191
|
+
// incompatible receiver" - Map's internal slots live on the target,
|
|
192
|
+
// and a proxy does not forward them.
|
|
193
|
+
instance instanceof ModulesContainer ||
|
|
194
|
+
instance instanceof DiscoveryService ||
|
|
195
|
+
instance instanceof MetadataScanner ||
|
|
196
|
+
// `@nestjs/graphql`'s ResolverDecoratorHost, matched structurally
|
|
197
|
+
// because the package is an optional peer. Its `onRequestStart` /
|
|
198
|
+
// `onRequestEnd` methods invoke the hooks this module registers, so
|
|
199
|
+
// instrumenting it would wrap the agent's own bookkeeping in spans
|
|
200
|
+
// inside every operation it measures.
|
|
201
|
+
isResolverDecoratorHost(instance));
|
|
202
|
+
}
|
|
203
|
+
catch {
|
|
204
|
+
// An instance that throws on inspection - `instanceof` runs its
|
|
205
|
+
// prototype trap, `isResolverDecoratorHost` reads properties - cannot
|
|
206
|
+
// be instrumented either way. nestjs-cls proxy providers are the
|
|
207
|
+
// canonical case: any access outside a CLS context throws
|
|
208
|
+
// ProxyProviderNotResolvedException, and instrumentation runs at
|
|
209
|
+
// bootstrap, where no such context exists. Leaving the provider alone
|
|
210
|
+
// is the only answer that lets the app start.
|
|
211
|
+
return true;
|
|
212
|
+
}
|
|
213
|
+
};
|
|
169
214
|
return {
|
|
170
215
|
ObserveInstrument: {
|
|
216
|
+
// Exclusions live entirely in the decorator: the framework's contract
|
|
217
|
+
// is `instanceDecorator` alone (nestjs/nest#17559 dropped a separate
|
|
218
|
+
// skip hook to avoid duplicating APIs). Newer cores additionally wrap
|
|
219
|
+
// this in a safety net that falls back to the undecorated instance,
|
|
220
|
+
// with a warning, should it ever throw.
|
|
171
221
|
instanceDecorator: createInstanceDecorator(asyncLocalStorage, operationTraceRegistry, {
|
|
172
222
|
traceIdKey: options.traceIdKey,
|
|
173
|
-
skipInstrumentation
|
|
174
|
-
return ([asyncLocalStorage, operationTraceRegistry].includes(instance) ||
|
|
175
|
-
instance instanceof TraceSamplerService ||
|
|
176
|
-
instance instanceof TracerService ||
|
|
177
|
-
instance instanceof ObserveAgentSharedBuffer ||
|
|
178
|
-
// Its methods run *inside* the traces it opens, so instrumenting
|
|
179
|
-
// it would put a span for the agent itself at the root of every
|
|
180
|
-
// GraphQL operation it records.
|
|
181
|
-
instance instanceof GraphQLObserveAgentService ||
|
|
182
|
-
// Same reason: its wrapper runs inside the job traces it opens.
|
|
183
|
-
instance instanceof ScheduleObserveAgentService ||
|
|
184
|
-
// Nest's discovery machinery, which the GraphQL agent walks to
|
|
185
|
-
// map root fields back to their resolver classes. It has to stay
|
|
186
|
-
// unproxied: ModulesContainer extends Map, and a Map method
|
|
187
|
-
// invoked with the instrumentation proxy as its receiver throws
|
|
188
|
-
// "called on incompatible receiver" - Map's internal slots live
|
|
189
|
-
// on the target, and a proxy does not forward them.
|
|
190
|
-
instance instanceof ModulesContainer ||
|
|
191
|
-
instance instanceof DiscoveryService ||
|
|
192
|
-
instance instanceof MetadataScanner ||
|
|
193
|
-
// `@nestjs/graphql`'s ResolverDecoratorHost, matched structurally
|
|
194
|
-
// because the package is an optional peer. Its `onRequestStart` /
|
|
195
|
-
// `onRequestEnd` methods invoke the hooks this module registers,
|
|
196
|
-
// so instrumenting it would wrap the agent's own bookkeeping in
|
|
197
|
-
// spans inside every operation it measures.
|
|
198
|
-
isResolverDecoratorHost(instance));
|
|
199
|
-
},
|
|
223
|
+
skipInstrumentation,
|
|
200
224
|
}),
|
|
201
225
|
},
|
|
202
226
|
ObserveModule,
|
|
@@ -20,6 +20,12 @@ export declare class ProfileUploader {
|
|
|
20
20
|
private readonly options;
|
|
21
21
|
private readonly pending;
|
|
22
22
|
private inFlight;
|
|
23
|
+
/**
|
|
24
|
+
* When uploads may resume after a 429. Windows enqueued while paused sit in
|
|
25
|
+
* `pending` under its usual two-window cap, so a lapsed pause resumes with
|
|
26
|
+
* the freshest profiles rather than a backlog.
|
|
27
|
+
*/
|
|
28
|
+
private rateLimitedUntil;
|
|
23
29
|
constructor(options: ProfileUploaderOptions);
|
|
24
30
|
enqueue(window: ProfileWindow, sampleRateHz: number): void;
|
|
25
31
|
/**
|
|
@@ -41,5 +47,12 @@ export declare class ProfileUploader {
|
|
|
41
47
|
* that path retries and the entitlement path discards.
|
|
42
48
|
*/
|
|
43
49
|
private isEntitlementError;
|
|
50
|
+
/**
|
|
51
|
+
* How long to pause for, honouring the response's Retry-After when it
|
|
52
|
+
* carries one. Only the delta-seconds form is parsed - the HTTP-date form
|
|
53
|
+
* is rare on rate limits and mis-parsing it risks an enormous pause - and
|
|
54
|
+
* anything absent, malformed, or out of range falls back to the default.
|
|
55
|
+
*/
|
|
56
|
+
private rateLimitPauseMs;
|
|
44
57
|
pendingCount(): number;
|
|
45
58
|
}
|
|
@@ -8,6 +8,15 @@
|
|
|
8
8
|
* that the oldest is dropped.
|
|
9
9
|
*/
|
|
10
10
|
const MAX_PENDING_WINDOWS = 2;
|
|
11
|
+
/**
|
|
12
|
+
* How long to stop uploading after a 429, when the response carries no usable
|
|
13
|
+
* Retry-After. Out-of-credits does not clear between windows, so retrying at
|
|
14
|
+
* the once-a-minute cadence only spends requests on refusals.
|
|
15
|
+
*/
|
|
16
|
+
const RATE_LIMIT_PAUSE_MS = 5 * 60 * 1000;
|
|
17
|
+
/** Ceiling on a server-sent Retry-After, so a bad header cannot park uploads
|
|
18
|
+
* for a day. */
|
|
19
|
+
const RATE_LIMIT_PAUSE_MAX_MS = 60 * 60 * 1000;
|
|
11
20
|
/**
|
|
12
21
|
* Ships one folded-stack window per upload.
|
|
13
22
|
*
|
|
@@ -21,6 +30,12 @@ export class ProfileUploader {
|
|
|
21
30
|
options;
|
|
22
31
|
pending = [];
|
|
23
32
|
inFlight = false;
|
|
33
|
+
/**
|
|
34
|
+
* When uploads may resume after a 429. Windows enqueued while paused sit in
|
|
35
|
+
* `pending` under its usual two-window cap, so a lapsed pause resumes with
|
|
36
|
+
* the freshest profiles rather than a backlog.
|
|
37
|
+
*/
|
|
38
|
+
rateLimitedUntil = 0;
|
|
24
39
|
constructor(options) {
|
|
25
40
|
this.options = options;
|
|
26
41
|
}
|
|
@@ -42,7 +57,7 @@ export class ProfileUploader {
|
|
|
42
57
|
* duplicate rather than an addition.
|
|
43
58
|
*/
|
|
44
59
|
async drain() {
|
|
45
|
-
if (this.inFlight) {
|
|
60
|
+
if (this.inFlight || Date.now() < this.rateLimitedUntil) {
|
|
46
61
|
return;
|
|
47
62
|
}
|
|
48
63
|
this.inFlight = true;
|
|
@@ -94,6 +109,18 @@ export class ProfileUploader {
|
|
|
94
109
|
this.options.onError?.("profiling is not included in this plan; discarding the window");
|
|
95
110
|
return true;
|
|
96
111
|
}
|
|
112
|
+
if (response.status === 429) {
|
|
113
|
+
// Out of credits or over budget. Pause outright instead of retrying
|
|
114
|
+
// every minute: the answer will not change window to window, and each
|
|
115
|
+
// retry is a request spent on a refusal. The window stays queued -
|
|
116
|
+
// `drain` skips while paused - so the first upload after the pause
|
|
117
|
+
// carries the freshest profiles the two-window cap kept.
|
|
118
|
+
const pauseMs = this.rateLimitPauseMs(response);
|
|
119
|
+
this.rateLimitedUntil = Date.now() + pauseMs;
|
|
120
|
+
this.options.onError?.(`profile upload rate-limited (429) - the account may be out of credits or over budget; ` +
|
|
121
|
+
`pausing uploads for ${Math.round(pauseMs / 60000)} minute(s)`);
|
|
122
|
+
return false;
|
|
123
|
+
}
|
|
97
124
|
if (response.status === 401 || response.status === 403) {
|
|
98
125
|
// A credential problem, not an entitlement one. Reported specifically
|
|
99
126
|
// and not discarded: it is a misconfiguration the operator can fix,
|
|
@@ -134,6 +161,19 @@ export class ProfileUploader {
|
|
|
134
161
|
return false;
|
|
135
162
|
}
|
|
136
163
|
}
|
|
164
|
+
/**
|
|
165
|
+
* How long to pause for, honouring the response's Retry-After when it
|
|
166
|
+
* carries one. Only the delta-seconds form is parsed - the HTTP-date form
|
|
167
|
+
* is rare on rate limits and mis-parsing it risks an enormous pause - and
|
|
168
|
+
* anything absent, malformed, or out of range falls back to the default.
|
|
169
|
+
*/
|
|
170
|
+
rateLimitPauseMs(response) {
|
|
171
|
+
const retryAfter = Number(response.headers.get("retry-after"));
|
|
172
|
+
if (Number.isFinite(retryAfter) && retryAfter > 0) {
|
|
173
|
+
return Math.min(retryAfter * 1000, RATE_LIMIT_PAUSE_MAX_MS);
|
|
174
|
+
}
|
|
175
|
+
return RATE_LIMIT_PAUSE_MS;
|
|
176
|
+
}
|
|
137
177
|
pendingCount() {
|
|
138
178
|
return this.pending.length;
|
|
139
179
|
}
|
|
@@ -14,6 +14,14 @@ export declare class HttpObserveAgentService<Store extends Record<string, unknow
|
|
|
14
14
|
private readonly observeAgentSharedBuffer;
|
|
15
15
|
private readonly traceSamplerService;
|
|
16
16
|
private httpAdapterInitSubscription;
|
|
17
|
+
/**
|
|
18
|
+
* `http.queryParamsObfuscateRegex`, rebuilt with the global flag when it was
|
|
19
|
+
* supplied without one. It is applied with `replaceAll`, which throws on a
|
|
20
|
+
* non-global RegExp - inside the request hook, so every traced request would
|
|
21
|
+
* answer 500 while ignored routes (health checks) kept passing. Same
|
|
22
|
+
* normalisation `RedactionOptions.patterns` already receives.
|
|
23
|
+
*/
|
|
24
|
+
private readonly queryParamsObfuscateRegex;
|
|
17
25
|
constructor(httpAdapterHost: HttpAdapterHost, asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>, options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, observeAgentSharedBuffer: ObserveAgentSharedBuffer, traceSamplerService: TraceSamplerService);
|
|
18
26
|
onModuleInit(): void;
|
|
19
27
|
onModuleDestroy(): void;
|
|
@@ -32,6 +32,14 @@ let HttpObserveAgentService = class HttpObserveAgentService {
|
|
|
32
32
|
observeAgentSharedBuffer;
|
|
33
33
|
traceSamplerService;
|
|
34
34
|
httpAdapterInitSubscription;
|
|
35
|
+
/**
|
|
36
|
+
* `http.queryParamsObfuscateRegex`, rebuilt with the global flag when it was
|
|
37
|
+
* supplied without one. It is applied with `replaceAll`, which throws on a
|
|
38
|
+
* non-global RegExp - inside the request hook, so every traced request would
|
|
39
|
+
* answer 500 while ignored routes (health checks) kept passing. Same
|
|
40
|
+
* normalisation `RedactionOptions.patterns` already receives.
|
|
41
|
+
*/
|
|
42
|
+
queryParamsObfuscateRegex;
|
|
35
43
|
constructor(httpAdapterHost, asyncLocalStorage, options, operationTraceRegistry, observeAgentSharedBuffer, traceSamplerService) {
|
|
36
44
|
this.httpAdapterHost = httpAdapterHost;
|
|
37
45
|
this.asyncLocalStorage = asyncLocalStorage;
|
|
@@ -39,6 +47,7 @@ let HttpObserveAgentService = class HttpObserveAgentService {
|
|
|
39
47
|
this.operationTraceRegistry = operationTraceRegistry;
|
|
40
48
|
this.observeAgentSharedBuffer = observeAgentSharedBuffer;
|
|
41
49
|
this.traceSamplerService = traceSamplerService;
|
|
50
|
+
this.queryParamsObfuscateRegex = toGlobalRegExp(this.options.http?.queryParamsObfuscateRegex);
|
|
42
51
|
// The "setOnRouteTriggered" hook must be set immediately
|
|
43
52
|
// to ensure that route metadata is captured correctly.
|
|
44
53
|
const { httpAdapter } = this.httpAdapterHost;
|
|
@@ -112,8 +121,8 @@ let HttpObserveAgentService = class HttpObserveAgentService {
|
|
|
112
121
|
// than instead - it exists for the keys only that deployment knows
|
|
113
122
|
// about.
|
|
114
123
|
const redactedUrl = redactUrlQuery(req.url);
|
|
115
|
-
const originalUrl = this.
|
|
116
|
-
? redactedUrl.replaceAll(this.
|
|
124
|
+
const originalUrl = this.queryParamsObfuscateRegex
|
|
125
|
+
? redactedUrl.replaceAll(this.queryParamsObfuscateRegex, "[REDACTED]")
|
|
117
126
|
: redactedUrl;
|
|
118
127
|
this.operationTraceRegistry.startTrace(traceId, {
|
|
119
128
|
protocol: req.protocol,
|
|
@@ -218,3 +227,13 @@ HttpObserveAgentService = __decorate([
|
|
|
218
227
|
TraceSamplerService])
|
|
219
228
|
], HttpObserveAgentService);
|
|
220
229
|
export { HttpObserveAgentService };
|
|
230
|
+
/**
|
|
231
|
+
* Rebuilds a RegExp with the global flag when it lacks one, keeping the
|
|
232
|
+
* original otherwise. `replaceAll` refuses a non-global pattern outright.
|
|
233
|
+
*/
|
|
234
|
+
function toGlobalRegExp(pattern) {
|
|
235
|
+
if (!pattern || pattern.global) {
|
|
236
|
+
return pattern;
|
|
237
|
+
}
|
|
238
|
+
return new RegExp(pattern.source, pattern.flags + "g");
|
|
239
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nestjs/observe",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.5",
|
|
4
4
|
"description": "Observability and APM agent for NestJS - traces, runtime metrics, custom metrics and CPU profiles",
|
|
5
5
|
"author": "Kamil Mysliwiec",
|
|
6
6
|
"homepage": "https://nestjs.com",
|
|
@@ -100,7 +100,7 @@
|
|
|
100
100
|
"@nestjs/apollo": "13.4.5",
|
|
101
101
|
"@nestjs/bullmq": "11.0.5",
|
|
102
102
|
"@nestjs/common": "11.2.1",
|
|
103
|
-
"@nestjs/core": "11.2.
|
|
103
|
+
"@nestjs/core": "11.2.2",
|
|
104
104
|
"@nestjs/graphql": "13.4.5",
|
|
105
105
|
"@nestjs/microservices": "11.2.1",
|
|
106
106
|
"@nestjs/platform-express": "11.2.1",
|
|
@@ -115,6 +115,7 @@
|
|
|
115
115
|
"graphql": "16.14.2",
|
|
116
116
|
"husky": "9.1.7",
|
|
117
117
|
"lint-staged": "17.3.0",
|
|
118
|
+
"nestjs-cls": "6.2.1",
|
|
118
119
|
"oxlint": "1.79.0",
|
|
119
120
|
"oxlint-tsgolint": "7.0.2001",
|
|
120
121
|
"prettier": "3.2.5",
|