@nestjs/observe 0.1.2 → 0.1.3
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/protocols/queue-observe-agent.service.d.ts +9 -0
- package/dist/protocols/queue-observe-agent.service.js +29 -1
- package/dist/protocols/rpc-observe-agent.service.d.ts +16 -1
- package/dist/protocols/rpc-observe-agent.service.js +50 -9
- package/dist/protocols/schedule-observe-agent.service.d.ts +4 -4
- package/dist/protocols/schedule-observe-agent.service.js +16 -12
- package/dist/services/operation-trace.registry.d.ts +15 -0
- package/dist/services/operation-trace.registry.js +36 -17
- package/dist/utils/optional-peer.util.d.ts +36 -0
- package/dist/utils/optional-peer.util.js +38 -0
- package/package.json +1 -1
|
@@ -19,5 +19,14 @@ export declare class QueueObserveAgentService<Store extends Record<string, unkno
|
|
|
19
19
|
* omitted rather than reported as zero.
|
|
20
20
|
*/
|
|
21
21
|
private readQueueMetadata;
|
|
22
|
+
/**
|
|
23
|
+
* Loads `@nestjs/bullmq`'s processor decorator without a static import, so a
|
|
24
|
+
* service that runs no queue need not install the package. The prototype is
|
|
25
|
+
* patched from the constructor, strictly before any processor is decorated.
|
|
26
|
+
*
|
|
27
|
+
* Returns `undefined` when the package is not installed and `null` when it
|
|
28
|
+
* is, but does not expose the decorator service where expected.
|
|
29
|
+
*/
|
|
30
|
+
private loadProcessorDecoratorService;
|
|
22
31
|
private patchDecorate;
|
|
23
32
|
}
|
|
@@ -11,13 +11,13 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
11
11
|
return function (target, key) { decorator(target, key, paramIndex); }
|
|
12
12
|
};
|
|
13
13
|
var QueueObserveAgentService_1;
|
|
14
|
-
import { ProcessorDecoratorService } from "@nestjs/bullmq/dist/instrument/processor-decorator.service.js";
|
|
15
14
|
import { Inject, Injectable, Logger } from "@nestjs/common";
|
|
16
15
|
import { AsyncLocalStorage } from "async_hooks";
|
|
17
16
|
import { randomUUID } from "crypto";
|
|
18
17
|
import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
|
|
19
18
|
import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
|
|
20
19
|
import { OBSERVE_OPTIONS } from "../observe.constants.js";
|
|
20
|
+
import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
|
|
21
21
|
let QueueObserveAgentService = QueueObserveAgentService_1 = class QueueObserveAgentService {
|
|
22
22
|
observeAgentSharedBuffer;
|
|
23
23
|
options;
|
|
@@ -62,7 +62,35 @@ let QueueObserveAgentService = QueueObserveAgentService_1 = class QueueObserveAg
|
|
|
62
62
|
}
|
|
63
63
|
return metadata;
|
|
64
64
|
}
|
|
65
|
+
/**
|
|
66
|
+
* Loads `@nestjs/bullmq`'s processor decorator without a static import, so a
|
|
67
|
+
* service that runs no queue need not install the package. The prototype is
|
|
68
|
+
* patched from the constructor, strictly before any processor is decorated.
|
|
69
|
+
*
|
|
70
|
+
* Returns `undefined` when the package is not installed and `null` when it
|
|
71
|
+
* is, but does not expose the decorator service where expected.
|
|
72
|
+
*/
|
|
73
|
+
loadProcessorDecoratorService() {
|
|
74
|
+
const result = loadOptionalPeer("@nestjs/bullmq", "@nestjs/bullmq/dist/instrument/processor-decorator.service.js");
|
|
75
|
+
if (!result.installed) {
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
78
|
+
if (result.error) {
|
|
79
|
+
// The real cause - a version that moved the file, an exports map that
|
|
80
|
+
// hides it - so the "update to the latest version" advice below is
|
|
81
|
+
// never the only diagnostic.
|
|
82
|
+
this.logger.warn(`@nestjs/bullmq is installed but its processor decorator could not be loaded: ${describePeerLoadError(result.error)}`);
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
return result.module?.ProcessorDecoratorService ?? null;
|
|
86
|
+
}
|
|
65
87
|
patchDecorate() {
|
|
88
|
+
const ProcessorDecoratorService = this.loadProcessorDecoratorService();
|
|
89
|
+
if (ProcessorDecoratorService === undefined) {
|
|
90
|
+
// The @nestjs/bullmq package is an optional peer. No queue means no
|
|
91
|
+
// processor to wrap, and that is not a misconfiguration.
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
66
94
|
if (!ProcessorDecoratorService?.prototype) {
|
|
67
95
|
this.logger.warn("ProcessorDecoratorService is not available. Please, update to the latest version of @nestjs/bullmq. Skipping patching.");
|
|
68
96
|
return;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { OnModuleDestroy, OnModuleInit } from "@nestjs/common";
|
|
2
2
|
import { ModulesContainer } from "@nestjs/core";
|
|
3
|
-
import { BaseRpcContext, Server, Transport } from "@nestjs/microservices";
|
|
3
|
+
import type { BaseRpcContext, Server, Transport } from "@nestjs/microservices";
|
|
4
4
|
import { AsyncLocalStorage } from "async_hooks";
|
|
5
5
|
import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
|
|
6
6
|
import { ObserveModuleOptionsWithDefaults } from "../interfaces/observe-options.interface.js";
|
|
@@ -19,10 +19,25 @@ export declare class RpcObserveAgentService<Store extends Record<string, unknown
|
|
|
19
19
|
private readonly operationTraceRegistry;
|
|
20
20
|
private readonly observeAgentSharedBuffer;
|
|
21
21
|
private readonly traceSamplerService;
|
|
22
|
+
private readonly logger;
|
|
22
23
|
private rpcTargetAddedSubscription;
|
|
24
|
+
/**
|
|
25
|
+
* Assigned in `onModuleInit`. Every use below is reached only through the
|
|
26
|
+
* hooks registered there, after a successful load - a service without the
|
|
27
|
+
* package has no RPC target to hook.
|
|
28
|
+
*/
|
|
29
|
+
private microservices;
|
|
23
30
|
constructor(asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>, options: ObserveModuleOptionsWithDefaults, modulesContainer: ModulesContainer, operationTraceRegistry: OperationTraceRegistry, observeAgentSharedBuffer: ObserveAgentSharedBuffer, traceSamplerService: TraceSamplerService);
|
|
24
31
|
onModuleInit(): void;
|
|
25
32
|
onModuleDestroy(): void;
|
|
33
|
+
/**
|
|
34
|
+
* Loads `@nestjs/microservices` without a static import, so a service that
|
|
35
|
+
* exposes no microservice need not install the package. Loaded here rather
|
|
36
|
+
* than lazily because the target registry is subscribed from `onModuleInit`,
|
|
37
|
+
* and a dynamic `import()` would resolve after a target may already have
|
|
38
|
+
* been announced.
|
|
39
|
+
*/
|
|
40
|
+
private loadMicroservices;
|
|
26
41
|
registerRpcHooks(target: Server): void;
|
|
27
42
|
/**
|
|
28
43
|
* Names the transport for the snapshot's `protocol` field.
|
|
@@ -10,22 +10,30 @@ var __metadata = (this && this.__metadata) || function (k, v) {
|
|
|
10
10
|
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
11
11
|
return function (target, key) { decorator(target, key, paramIndex); }
|
|
12
12
|
};
|
|
13
|
-
|
|
13
|
+
var RpcObserveAgentService_1;
|
|
14
|
+
import { Inject, Injectable, Logger, } from "@nestjs/common";
|
|
14
15
|
import { ModulesContainer } from "@nestjs/core";
|
|
15
|
-
import { KafkaContext, MqttContext, NatsContext, RedisContext, RmqContext, TcpContext, Transport, } from "@nestjs/microservices";
|
|
16
16
|
import { AsyncLocalStorage } from "async_hooks";
|
|
17
17
|
import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
|
|
18
18
|
import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
|
|
19
19
|
import { TraceSamplerService } from "../services/trace-sampler.service.js";
|
|
20
20
|
import { OBSERVE_OPTIONS } from "../observe.constants.js";
|
|
21
|
-
|
|
21
|
+
import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
|
|
22
|
+
let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentService {
|
|
22
23
|
asyncLocalStorage;
|
|
23
24
|
options;
|
|
24
25
|
modulesContainer;
|
|
25
26
|
operationTraceRegistry;
|
|
26
27
|
observeAgentSharedBuffer;
|
|
27
28
|
traceSamplerService;
|
|
29
|
+
logger = new Logger(RpcObserveAgentService_1.name);
|
|
28
30
|
rpcTargetAddedSubscription;
|
|
31
|
+
/**
|
|
32
|
+
* Assigned in `onModuleInit`. Every use below is reached only through the
|
|
33
|
+
* hooks registered there, after a successful load - a service without the
|
|
34
|
+
* package has no RPC target to hook.
|
|
35
|
+
*/
|
|
36
|
+
microservices;
|
|
29
37
|
constructor(asyncLocalStorage, options, modulesContainer, operationTraceRegistry, observeAgentSharedBuffer, traceSamplerService) {
|
|
30
38
|
this.asyncLocalStorage = asyncLocalStorage;
|
|
31
39
|
this.options = options;
|
|
@@ -35,6 +43,10 @@ let RpcObserveAgentService = class RpcObserveAgentService {
|
|
|
35
43
|
this.traceSamplerService = traceSamplerService;
|
|
36
44
|
}
|
|
37
45
|
onModuleInit() {
|
|
46
|
+
this.microservices = this.loadMicroservices();
|
|
47
|
+
if (!this.microservices) {
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
38
50
|
this.rpcTargetAddedSubscription = this.modulesContainer
|
|
39
51
|
.getRpcTargetRegistry?.()
|
|
40
52
|
.subscribe((target) => this.registerRpcHooks(target));
|
|
@@ -44,9 +56,31 @@ let RpcObserveAgentService = class RpcObserveAgentService {
|
|
|
44
56
|
this.rpcTargetAddedSubscription.unsubscribe();
|
|
45
57
|
}
|
|
46
58
|
}
|
|
59
|
+
/**
|
|
60
|
+
* Loads `@nestjs/microservices` without a static import, so a service that
|
|
61
|
+
* exposes no microservice need not install the package. Loaded here rather
|
|
62
|
+
* than lazily because the target registry is subscribed from `onModuleInit`,
|
|
63
|
+
* and a dynamic `import()` would resolve after a target may already have
|
|
64
|
+
* been announced.
|
|
65
|
+
*/
|
|
66
|
+
loadMicroservices() {
|
|
67
|
+
const result = loadOptionalPeer("@nestjs/microservices");
|
|
68
|
+
if (!result.installed) {
|
|
69
|
+
// No microservice means no RPC target to hook, and that is not a
|
|
70
|
+
// misconfiguration.
|
|
71
|
+
return undefined;
|
|
72
|
+
}
|
|
73
|
+
if (!result.module) {
|
|
74
|
+
// Installed but unloadable is a misconfiguration, and the symptom
|
|
75
|
+
// otherwise is a service whose RPC operations silently never appear.
|
|
76
|
+
this.logger.warn(`@nestjs/microservices is installed but could not be loaded, so RPC operations will not be instrumented: ${describePeerLoadError(result.error)}`);
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
return result.module;
|
|
80
|
+
}
|
|
47
81
|
registerRpcHooks(target) {
|
|
48
82
|
target.setOnProcessingStartHook((transportId, ctx, done) => {
|
|
49
|
-
if (transportId === Transport.GRPC) {
|
|
83
|
+
if (transportId === this.microservices.Transport.GRPC) {
|
|
50
84
|
this.startGrpcRequestTracing(transportId, ctx, done);
|
|
51
85
|
return;
|
|
52
86
|
}
|
|
@@ -66,7 +100,7 @@ let RpcObserveAgentService = class RpcObserveAgentService {
|
|
|
66
100
|
toProtocolName(transportId) {
|
|
67
101
|
return typeof transportId === "symbol"
|
|
68
102
|
? transportId.description ?? "custom"
|
|
69
|
-
: Transport[transportId];
|
|
103
|
+
: this.microservices.Transport[transportId];
|
|
70
104
|
}
|
|
71
105
|
startRpcRequestTracing(transportId, ctx, done) {
|
|
72
106
|
// The same map `run` is given, rather than `getStore()` inside the callback:
|
|
@@ -147,7 +181,7 @@ let RpcObserveAgentService = class RpcObserveAgentService {
|
|
|
147
181
|
}
|
|
148
182
|
setTimeout(async () => {
|
|
149
183
|
let userId;
|
|
150
|
-
if (transportId === Transport.GRPC) {
|
|
184
|
+
if (transportId === this.microservices.Transport.GRPC) {
|
|
151
185
|
if (this.options.grpc?.getUserId) {
|
|
152
186
|
userId = this.options.grpc?.getUserId?.(ctx);
|
|
153
187
|
}
|
|
@@ -168,6 +202,7 @@ let RpcObserveAgentService = class RpcObserveAgentService {
|
|
|
168
202
|
}, 0);
|
|
169
203
|
}
|
|
170
204
|
getOperationIdFromContext(ctx) {
|
|
205
|
+
const { KafkaContext, MqttContext, NatsContext, RedisContext, RmqContext, TcpContext, } = this.microservices;
|
|
171
206
|
switch (true) {
|
|
172
207
|
case ctx instanceof KafkaContext:
|
|
173
208
|
case ctx instanceof MqttContext:
|
|
@@ -179,12 +214,18 @@ let RpcObserveAgentService = class RpcObserveAgentService {
|
|
|
179
214
|
return ctx.getChannel();
|
|
180
215
|
case ctx instanceof NatsContext:
|
|
181
216
|
return ctx.getSubject();
|
|
182
|
-
default:
|
|
183
|
-
|
|
217
|
+
default: {
|
|
218
|
+
// A custom transporter delivers its own context class - expected, per
|
|
219
|
+
// `toProtocolName` - and there is no universal accessor for its
|
|
220
|
+
// routing key. Throwing here would fail the message before `done()`
|
|
221
|
+
// ever ran, so fall back to a conventional accessor when one exists.
|
|
222
|
+
const pattern = ctx?.getPattern?.();
|
|
223
|
+
return typeof pattern === "string" ? pattern : "unknown";
|
|
224
|
+
}
|
|
184
225
|
}
|
|
185
226
|
}
|
|
186
227
|
};
|
|
187
|
-
RpcObserveAgentService = __decorate([
|
|
228
|
+
RpcObserveAgentService = RpcObserveAgentService_1 = __decorate([
|
|
188
229
|
Injectable(),
|
|
189
230
|
__param(1, Inject(OBSERVE_OPTIONS)),
|
|
190
231
|
__metadata("design:paramtypes", [AsyncLocalStorage, Object, ModulesContainer,
|
|
@@ -35,10 +35,10 @@ export declare class ScheduleObserveAgentService<Store extends Record<string, un
|
|
|
35
35
|
constructor(observeAgentSharedBuffer: ObserveAgentSharedBuffer, options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>);
|
|
36
36
|
/**
|
|
37
37
|
* Loads the explorer without a static import, so a service that schedules
|
|
38
|
-
* nothing need not install the package.
|
|
39
|
-
* `import()` would resolve after provider instantiation, with no
|
|
40
|
-
* of landing before the explorer's `onModuleInit` has already
|
|
41
|
-
*
|
|
38
|
+
* nothing need not install the package. Loaded from the constructor because
|
|
39
|
+
* a dynamic `import()` would resolve after provider instantiation, with no
|
|
40
|
+
* guarantee of landing before the explorer's `onModuleInit` has already
|
|
41
|
+
* wrapped every handler.
|
|
42
42
|
*/
|
|
43
43
|
private loadScheduleExplorer;
|
|
44
44
|
private patchScheduleExplorer;
|
|
@@ -14,10 +14,10 @@ var ScheduleObserveAgentService_1;
|
|
|
14
14
|
import { Inject, Injectable, Logger } from "@nestjs/common";
|
|
15
15
|
import { AsyncLocalStorage } from "async_hooks";
|
|
16
16
|
import { randomUUID } from "crypto";
|
|
17
|
-
import { createRequire } from "module";
|
|
18
17
|
import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
|
|
19
18
|
import { OBSERVE_OPTIONS } from "../observe.constants.js";
|
|
20
19
|
import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
|
|
20
|
+
import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
|
|
21
21
|
/**
|
|
22
22
|
* `@nestjs/schedule`'s metadata keys and scheduler-type enum, inlined so the
|
|
23
23
|
* package stays an optional peer. `@Cron`/`@Interval`/`@Timeout` stamp all
|
|
@@ -71,22 +71,26 @@ let ScheduleObserveAgentService = ScheduleObserveAgentService_1 = class Schedule
|
|
|
71
71
|
}
|
|
72
72
|
/**
|
|
73
73
|
* Loads the explorer without a static import, so a service that schedules
|
|
74
|
-
* nothing need not install the package.
|
|
75
|
-
* `import()` would resolve after provider instantiation, with no
|
|
76
|
-
* of landing before the explorer's `onModuleInit` has already
|
|
77
|
-
*
|
|
74
|
+
* nothing need not install the package. Loaded from the constructor because
|
|
75
|
+
* a dynamic `import()` would resolve after provider instantiation, with no
|
|
76
|
+
* guarantee of landing before the explorer's `onModuleInit` has already
|
|
77
|
+
* wrapped every handler.
|
|
78
78
|
*/
|
|
79
79
|
loadScheduleExplorer() {
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
80
|
+
const result = loadOptionalPeer("@nestjs/schedule", "@nestjs/schedule/dist/schedule.explorer.js");
|
|
81
|
+
if (!result.installed) {
|
|
82
|
+
// Nothing scheduled, nothing to patch, and that is not a
|
|
83
|
+
// misconfiguration.
|
|
84
|
+
return undefined;
|
|
84
85
|
}
|
|
85
|
-
|
|
86
|
-
//
|
|
87
|
-
//
|
|
86
|
+
if (result.error) {
|
|
87
|
+
// Installed but the explorer cannot be loaded - a version that moved
|
|
88
|
+
// the file, say. Worth saying out loud, with the actual cause: the
|
|
89
|
+
// symptom otherwise is a service whose jobs silently never appear.
|
|
90
|
+
this.logger.warn(`@nestjs/schedule is installed but its ScheduleExplorer could not be loaded, so scheduled jobs will not be instrumented: ${describePeerLoadError(result.error)}`);
|
|
88
91
|
return undefined;
|
|
89
92
|
}
|
|
93
|
+
return result.module?.ScheduleExplorer;
|
|
90
94
|
}
|
|
91
95
|
patchScheduleExplorer() {
|
|
92
96
|
const ScheduleExplorer = this.loadScheduleExplorer();
|
|
@@ -56,6 +56,21 @@ export declare class OperationTraceRegistry {
|
|
|
56
56
|
private toErrorStatusCode;
|
|
57
57
|
private setStatusCode;
|
|
58
58
|
internalStartTraceStep(traceId: TraceId, className: string, methodKey: string, callerId: string | undefined): string | undefined;
|
|
59
|
+
/**
|
|
60
|
+
* Nests a freshly opened node under its caller when that caller is still
|
|
61
|
+
* live, and at the trace root otherwise.
|
|
62
|
+
*
|
|
63
|
+
* A caller that has already completed has had its scratch fields stripped
|
|
64
|
+
* (`type`, and `children` when it had none), so there is nothing left to
|
|
65
|
+
* nest under. That happens whenever a callee outlives its caller - most
|
|
66
|
+
* commonly a handler that Nest bound (`AsyncResource.bind` in its
|
|
67
|
+
* interceptors consumer) to the async context of an interceptor whose
|
|
68
|
+
* `intercept()` returned synchronously. Fall back to the root rather than
|
|
69
|
+
* throw into the request: the mirror case, a step ending after its caller
|
|
70
|
+
* did, is already tolerated in `internalEndTraceStep`. Auto and manual spans
|
|
71
|
+
* both attach through here, so they share the tolerance.
|
|
72
|
+
*/
|
|
73
|
+
private attachToCaller;
|
|
59
74
|
internalEndTraceStep(traceId: TraceId,
|
|
60
75
|
/**
|
|
61
76
|
* Diagnostic label only - it names the span in the two warnings below and
|
|
@@ -227,15 +227,7 @@ export class OperationTraceRegistry {
|
|
|
227
227
|
spanId: newNodeId,
|
|
228
228
|
};
|
|
229
229
|
let refsByCaller = this.callerIdsByTraceId.get(traceId);
|
|
230
|
-
|
|
231
|
-
const caller = refsByCaller.get(callerId);
|
|
232
|
-
caller.children.push(newNode);
|
|
233
|
-
newNode.parent = caller;
|
|
234
|
-
}
|
|
235
|
-
else {
|
|
236
|
-
// No caller means insert trace at the root level
|
|
237
|
-
snapshot.traces.push(newNode);
|
|
238
|
-
}
|
|
230
|
+
this.attachToCaller(snapshot, refsByCaller, callerId, newNode);
|
|
239
231
|
if (!refsByCaller) {
|
|
240
232
|
refsByCaller = new Map();
|
|
241
233
|
this.callerIdsByTraceId.set(traceId, refsByCaller);
|
|
@@ -243,6 +235,31 @@ export class OperationTraceRegistry {
|
|
|
243
235
|
refsByCaller.set(newNodeId, newNode);
|
|
244
236
|
return newNodeId;
|
|
245
237
|
}
|
|
238
|
+
/**
|
|
239
|
+
* Nests a freshly opened node under its caller when that caller is still
|
|
240
|
+
* live, and at the trace root otherwise.
|
|
241
|
+
*
|
|
242
|
+
* A caller that has already completed has had its scratch fields stripped
|
|
243
|
+
* (`type`, and `children` when it had none), so there is nothing left to
|
|
244
|
+
* nest under. That happens whenever a callee outlives its caller - most
|
|
245
|
+
* commonly a handler that Nest bound (`AsyncResource.bind` in its
|
|
246
|
+
* interceptors consumer) to the async context of an interceptor whose
|
|
247
|
+
* `intercept()` returned synchronously. Fall back to the root rather than
|
|
248
|
+
* throw into the request: the mirror case, a step ending after its caller
|
|
249
|
+
* did, is already tolerated in `internalEndTraceStep`. Auto and manual spans
|
|
250
|
+
* both attach through here, so they share the tolerance.
|
|
251
|
+
*/
|
|
252
|
+
attachToCaller(snapshot, refsByCaller, callerId, newNode) {
|
|
253
|
+
const caller = callerId ? refsByCaller?.get(callerId) : undefined;
|
|
254
|
+
if (caller?.type === "start") {
|
|
255
|
+
caller.children.push(newNode);
|
|
256
|
+
newNode.parent = caller;
|
|
257
|
+
}
|
|
258
|
+
else {
|
|
259
|
+
// No (live) caller means insert trace at the root level
|
|
260
|
+
snapshot.traces.push(newNode);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
246
263
|
internalEndTraceStep(traceId,
|
|
247
264
|
/**
|
|
248
265
|
* Diagnostic label only - it names the span in the two warnings below and
|
|
@@ -429,11 +446,15 @@ export class OperationTraceRegistry {
|
|
|
429
446
|
}
|
|
430
447
|
async createManualSpan(traceId, callerId, name, spanFunction) {
|
|
431
448
|
// await new Promise((resolve) => setImmediate(resolve));
|
|
449
|
+
// The caller may already have completed (its entry survives completion in
|
|
450
|
+
// `refsByCaller`); it is still the right source for the class and method
|
|
451
|
+
// labels, which outlive completion. Where the new span *attaches* is
|
|
452
|
+
// decided by `attachToCaller`, which nests only under a live caller.
|
|
432
453
|
const activeSpan = this.getActiveSpan(traceId, callerId);
|
|
433
|
-
|
|
454
|
+
const snapshot = this.traceSnapshots.get(traceId);
|
|
455
|
+
if (!activeSpan || !snapshot) {
|
|
434
456
|
return spanFunction(new TraceSpanDelegate("", name, {}));
|
|
435
457
|
}
|
|
436
|
-
const snapshot = this.traceSnapshots.get(traceId);
|
|
437
458
|
// Book the span in the same ledger auto spans use. Completion goes through
|
|
438
459
|
// internalEndTraceStep, which increments refsMarkedAsComplete - without
|
|
439
460
|
// the matching increment here, every completed manual span pushed the
|
|
@@ -441,9 +462,7 @@ export class OperationTraceRegistry {
|
|
|
441
462
|
// one manual span read as complete: pluckSnapshot then shipped a
|
|
442
463
|
// half-built tree whose ongoing node still held its circular `parent`
|
|
443
464
|
// reference, and JSON.stringify threw away the whole flush window.
|
|
444
|
-
|
|
445
|
-
snapshot.refsCounter += 1;
|
|
446
|
-
}
|
|
465
|
+
snapshot.refsCounter += 1;
|
|
447
466
|
const newNodeId = randomUUID();
|
|
448
467
|
const startTime = performance.now();
|
|
449
468
|
// Same as internalStartTraceStep: without an enter, the exit issued on
|
|
@@ -463,10 +482,10 @@ export class OperationTraceRegistry {
|
|
|
463
482
|
startTime,
|
|
464
483
|
startOffset: this.toStartOffset(snapshot, startTime),
|
|
465
484
|
children: [],
|
|
466
|
-
parent: activeSpan,
|
|
467
485
|
};
|
|
468
|
-
|
|
469
|
-
this.
|
|
486
|
+
const refsByCaller = this.callerIdsByTraceId.get(traceId);
|
|
487
|
+
this.attachToCaller(snapshot, refsByCaller, callerId, manualSpan);
|
|
488
|
+
refsByCaller?.set(newNodeId, manualSpan);
|
|
470
489
|
const onResponse = (res) => {
|
|
471
490
|
// setImmediate
|
|
472
491
|
this.internalEndTraceStep(traceId, newNodeId, manualSpan.className, manualSpan.methodKey, newNodeId);
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What loading an optional peer produced.
|
|
3
|
+
*
|
|
4
|
+
* `installed: false` is the normal case for a service that does not use the
|
|
5
|
+
* feature - not a misconfiguration, and callers should stay silent about it.
|
|
6
|
+
* `installed: true` with no `module` means the package is present but the
|
|
7
|
+
* requested entry could not be loaded; `error` carries the cause so the
|
|
8
|
+
* caller can say something truthful instead of guessing.
|
|
9
|
+
*/
|
|
10
|
+
export type OptionalPeerResult<T> = {
|
|
11
|
+
installed: false;
|
|
12
|
+
} | {
|
|
13
|
+
installed: true;
|
|
14
|
+
module: T | undefined;
|
|
15
|
+
error?: unknown;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Loads an optional peer dependency without a static import, so a service
|
|
19
|
+
* that does not use the feature need not install the package.
|
|
20
|
+
*
|
|
21
|
+
* Synchronous on purpose: every caller patches or subscribes during provider
|
|
22
|
+
* instantiation or `onModuleInit`, strictly before the peer's own lifecycle
|
|
23
|
+
* runs, and a dynamic `import()` would resolve too late. All current peers
|
|
24
|
+
* ship CommonJS, so `require` can load them.
|
|
25
|
+
*
|
|
26
|
+
* The package's presence is probed with `require.resolve(packageName)` before
|
|
27
|
+
* `specifier` (which may be a deep path into the package) is required, so
|
|
28
|
+
* "not installed" is kept apart from "installed but broken or reshaped".
|
|
29
|
+
* `createRequire` itself failing - a CJS bundle that erased `import.meta.url`,
|
|
30
|
+
* say - is treated as "not installed": with no resolver there is nothing to
|
|
31
|
+
* load, and crashing the constructor would defeat the point of the peer being
|
|
32
|
+
* optional.
|
|
33
|
+
*/
|
|
34
|
+
/** Names a load failure for a log line: the message for an `Error`, `String` otherwise. */
|
|
35
|
+
export declare function describePeerLoadError(error: unknown): string;
|
|
36
|
+
export declare function loadOptionalPeer<T>(packageName: string, specifier?: string): OptionalPeerResult<T>;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { createRequire } from "module";
|
|
2
|
+
/**
|
|
3
|
+
* Loads an optional peer dependency without a static import, so a service
|
|
4
|
+
* that does not use the feature need not install the package.
|
|
5
|
+
*
|
|
6
|
+
* Synchronous on purpose: every caller patches or subscribes during provider
|
|
7
|
+
* instantiation or `onModuleInit`, strictly before the peer's own lifecycle
|
|
8
|
+
* runs, and a dynamic `import()` would resolve too late. All current peers
|
|
9
|
+
* ship CommonJS, so `require` can load them.
|
|
10
|
+
*
|
|
11
|
+
* The package's presence is probed with `require.resolve(packageName)` before
|
|
12
|
+
* `specifier` (which may be a deep path into the package) is required, so
|
|
13
|
+
* "not installed" is kept apart from "installed but broken or reshaped".
|
|
14
|
+
* `createRequire` itself failing - a CJS bundle that erased `import.meta.url`,
|
|
15
|
+
* say - is treated as "not installed": with no resolver there is nothing to
|
|
16
|
+
* load, and crashing the constructor would defeat the point of the peer being
|
|
17
|
+
* optional.
|
|
18
|
+
*/
|
|
19
|
+
/** Names a load failure for a log line: the message for an `Error`, `String` otherwise. */
|
|
20
|
+
export function describePeerLoadError(error) {
|
|
21
|
+
return error instanceof Error ? error.message : String(error);
|
|
22
|
+
}
|
|
23
|
+
export function loadOptionalPeer(packageName, specifier = packageName) {
|
|
24
|
+
let require;
|
|
25
|
+
try {
|
|
26
|
+
require = createRequire(import.meta.url);
|
|
27
|
+
require.resolve(packageName);
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return { installed: false };
|
|
31
|
+
}
|
|
32
|
+
try {
|
|
33
|
+
return { installed: true, module: require(specifier) };
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
return { installed: true, module: undefined, error };
|
|
37
|
+
}
|
|
38
|
+
}
|
package/package.json
CHANGED