nest-graph-inspector 0.6.0 → 0.7.0
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/LICENSE +21 -0
- package/README.md +8 -56
- package/dist/adapters/direct-run-output.adapter.d.ts +18 -0
- package/{src → dist}/adapters/direct-run-output.adapter.js +91 -31
- package/{src → dist}/adapters/file-output.adapter.js +4 -1
- package/{src → dist}/adapters/http-output.adapter.d.ts +0 -1
- package/{src → dist}/adapters/http-output.adapter.js +3 -5
- package/{src → dist}/adapters/http-serve.adapter.js +0 -1
- package/{src → dist}/adapters/json-output.adapter.js +0 -1
- package/{src → dist}/adapters/proxy.adapter.js +0 -1
- package/{src → dist}/adapters/viewer-output.adapter.d.ts +4 -1
- package/{src → dist}/adapters/viewer-output.adapter.js +30 -4
- package/{src → dist}/index.d.ts +1 -0
- package/{src → dist}/index.js +1 -1
- package/dist/inspector-endpoint-info.d.ts +7 -0
- package/dist/inspector-endpoint-info.js +31 -0
- package/{src → dist}/nest-graph-inspector.config.js +0 -1
- package/{src → dist}/nest-graph-inspector.module.js +2 -1
- package/{src → dist}/nest-graph-inspector.setup.d.ts +8 -1
- package/{src → dist}/nest-graph-inspector.setup.js +105 -23
- package/dist/nest-graph-inspector.type.js +2 -0
- package/{src → dist}/ports/output.adapter.js +0 -1
- package/{src → dist}/ports/proxy.gateway.js +0 -1
- package/dist/runtime-trace.recorder.d.ts +42 -0
- package/dist/runtime-trace.recorder.js +299 -0
- package/dist/types/direct-run.type.d.ts +75 -0
- package/{src → dist}/types/direct-run.type.js +0 -1
- package/{src → dist}/types/graph-output.schema.js +0 -1
- package/dist/types/graph-output.type.js +2 -0
- package/dist/types/module-controller.type.js +2 -0
- package/{src → dist}/types/module-map.type.js +0 -1
- package/dist/types/module-provider.type.js +2 -0
- package/{src → dist}/types/module.type.js +0 -1
- package/package.json +24 -8
- package/src/adapters/direct-run-output.adapter.d.ts +0 -10
- package/src/adapters/direct-run-output.adapter.js.map +0 -1
- package/src/adapters/file-output.adapter.js.map +0 -1
- package/src/adapters/http-output.adapter.js.map +0 -1
- package/src/adapters/http-serve.adapter.js.map +0 -1
- package/src/adapters/json-output.adapter.js.map +0 -1
- package/src/adapters/proxy.adapter.js.map +0 -1
- package/src/adapters/viewer-output.adapter.js.map +0 -1
- package/src/index.js.map +0 -1
- package/src/nest-graph-inspector.config.js.map +0 -1
- package/src/nest-graph-inspector.module.js.map +0 -1
- package/src/nest-graph-inspector.setup.js.map +0 -1
- package/src/nest-graph-inspector.type.js +0 -3
- package/src/nest-graph-inspector.type.js.map +0 -1
- package/src/ports/output.adapter.js.map +0 -1
- package/src/ports/proxy.gateway.js.map +0 -1
- package/src/types/direct-run.type.d.ts +0 -13
- package/src/types/direct-run.type.js.map +0 -1
- package/src/types/graph-output.schema.js.map +0 -1
- package/src/types/graph-output.type.js +0 -3
- package/src/types/graph-output.type.js.map +0 -1
- package/src/types/module-controller.type.js +0 -3
- package/src/types/module-controller.type.js.map +0 -1
- package/src/types/module-map.type.js.map +0 -1
- package/src/types/module-provider.type.js +0 -3
- package/src/types/module-provider.type.js.map +0 -1
- package/src/types/module.type.js.map +0 -1
- /package/{src → dist}/adapters/file-output.adapter.d.ts +0 -0
- /package/{src → dist}/adapters/http-serve.adapter.d.ts +0 -0
- /package/{src → dist}/adapters/json-output.adapter.d.ts +0 -0
- /package/{src → dist}/adapters/proxy.adapter.d.ts +0 -0
- /package/{src → dist}/nest-graph-inspector.config.d.ts +0 -0
- /package/{src → dist}/nest-graph-inspector.module.d.ts +0 -0
- /package/{src → dist}/nest-graph-inspector.type.d.ts +0 -0
- /package/{src → dist}/ports/output.adapter.d.ts +0 -0
- /package/{src → dist}/ports/proxy.gateway.d.ts +0 -0
- /package/{src → dist}/types/graph-output.schema.d.ts +0 -0
- /package/{src → dist}/types/graph-output.type.d.ts +0 -0
- /package/{src → dist}/types/module-controller.type.d.ts +0 -0
- /package/{src → dist}/types/module-map.type.d.ts +0 -0
- /package/{src → dist}/types/module-provider.type.d.ts +0 -0
- /package/{src → dist}/types/module.type.d.ts +0 -0
|
@@ -25,6 +25,7 @@ const file_output_adapter_1 = require("./adapters/file-output.adapter");
|
|
|
25
25
|
const json_output_adapter_1 = require("./adapters/json-output.adapter");
|
|
26
26
|
const viewer_output_adapter_1 = require("./adapters/viewer-output.adapter");
|
|
27
27
|
const ts_morph_1 = require("ts-morph");
|
|
28
|
+
const runtime_trace_recorder_1 = require("./runtime-trace.recorder");
|
|
28
29
|
let NestGraphInspectorSetup = NestGraphInspectorSetup_1 = class NestGraphInspectorSetup {
|
|
29
30
|
options;
|
|
30
31
|
modulesContainer;
|
|
@@ -32,6 +33,7 @@ let NestGraphInspectorSetup = NestGraphInspectorSetup_1 = class NestGraphInspect
|
|
|
32
33
|
fileOutputAdapter;
|
|
33
34
|
jsonOutputAdapter;
|
|
34
35
|
viewerOutputAdapter;
|
|
36
|
+
runtimeTraceRecorder;
|
|
35
37
|
logger = new common_1.Logger(NestGraphInspectorSetup_1.name);
|
|
36
38
|
outputAdapters;
|
|
37
39
|
ignoreProvider;
|
|
@@ -39,13 +41,15 @@ let NestGraphInspectorSetup = NestGraphInspectorSetup_1 = class NestGraphInspect
|
|
|
39
41
|
nestCoreModuleName;
|
|
40
42
|
nestCoreProviders;
|
|
41
43
|
tsMorphProject = this.createTsMorphProject();
|
|
42
|
-
|
|
44
|
+
runtimeTraceInstrumentedInstances = new WeakSet();
|
|
45
|
+
constructor(options, modulesContainer, httpOutputAdapter, fileOutputAdapter, jsonOutputAdapter, viewerOutputAdapter, runtimeTraceRecorder) {
|
|
43
46
|
this.options = options;
|
|
44
47
|
this.modulesContainer = modulesContainer;
|
|
45
48
|
this.httpOutputAdapter = httpOutputAdapter;
|
|
46
49
|
this.fileOutputAdapter = fileOutputAdapter;
|
|
47
50
|
this.jsonOutputAdapter = jsonOutputAdapter;
|
|
48
51
|
this.viewerOutputAdapter = viewerOutputAdapter;
|
|
52
|
+
this.runtimeTraceRecorder = runtimeTraceRecorder;
|
|
49
53
|
this.outputAdapters = {
|
|
50
54
|
http: this.httpOutputAdapter,
|
|
51
55
|
markdown: this.fileOutputAdapter,
|
|
@@ -98,6 +102,7 @@ let NestGraphInspectorSetup = NestGraphInspectorSetup_1 = class NestGraphInspect
|
|
|
98
102
|
getModuleTree(rootModule) {
|
|
99
103
|
const moduleTree = this.resolveModuleTree(rootModule);
|
|
100
104
|
this.resolveModuleMembers(moduleTree);
|
|
105
|
+
this.instrumentRuntimeTrace(moduleTree);
|
|
101
106
|
this.appendNestCoreModule(moduleTree);
|
|
102
107
|
return moduleTree;
|
|
103
108
|
}
|
|
@@ -157,9 +162,16 @@ let NestGraphInspectorSetup = NestGraphInspectorSetup_1 = class NestGraphInspect
|
|
|
157
162
|
}
|
|
158
163
|
return {
|
|
159
164
|
path,
|
|
165
|
+
historyDirPath: this.getDirectRunHistoryDirPath(),
|
|
160
166
|
instanceLookup: (moduleName, providerName) => this.findDirectRunProviderInstance(moduleName, providerName),
|
|
161
167
|
};
|
|
162
168
|
}
|
|
169
|
+
getDirectRunHistoryDirPath() {
|
|
170
|
+
const jsonOutput = this.options.outputs?.find((output) => output.type === 'json');
|
|
171
|
+
return jsonOutput?.type === 'json'
|
|
172
|
+
? (0, node_path_1.join)(process.cwd(), (0, node_path_1.dirname)(jsonOutput.path), 'direct-run', 'history')
|
|
173
|
+
: undefined;
|
|
174
|
+
}
|
|
163
175
|
buildModuleMapFromAutoDetect() {
|
|
164
176
|
const root = this.findRootModule();
|
|
165
177
|
const moduleTree = this.getModuleTree(root);
|
|
@@ -234,6 +246,74 @@ let NestGraphInspectorSetup = NestGraphInspectorSetup_1 = class NestGraphInspect
|
|
|
234
246
|
node.controllers = this.extractControllers(node.moduleRef, node.name);
|
|
235
247
|
});
|
|
236
248
|
}
|
|
249
|
+
instrumentRuntimeTrace(moduleTree) {
|
|
250
|
+
this.walkModuleTree(moduleTree, (node) => {
|
|
251
|
+
if (!node.moduleRef) {
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
this.instrumentRuntimeTraceWrappers({
|
|
255
|
+
moduleName: node.name,
|
|
256
|
+
type: 'provider',
|
|
257
|
+
wrappers: node.moduleRef.providers.values(),
|
|
258
|
+
shouldIgnore: (name) => name === node.name || this.ignoreProvider.includes(name),
|
|
259
|
+
});
|
|
260
|
+
this.instrumentRuntimeTraceWrappers({
|
|
261
|
+
moduleName: node.name,
|
|
262
|
+
type: 'controller',
|
|
263
|
+
wrappers: node.moduleRef.controllers.values(),
|
|
264
|
+
});
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
instrumentRuntimeTraceWrappers(param) {
|
|
268
|
+
for (const wrapper of param.wrappers) {
|
|
269
|
+
const instance = wrapper.instance;
|
|
270
|
+
if (!instance || typeof instance !== 'object') {
|
|
271
|
+
continue;
|
|
272
|
+
}
|
|
273
|
+
const className = this.wrapperClassName(wrapper);
|
|
274
|
+
if (!className || param.shouldIgnore?.(className)) {
|
|
275
|
+
continue;
|
|
276
|
+
}
|
|
277
|
+
this.instrumentRuntimeTraceInstance({
|
|
278
|
+
instance,
|
|
279
|
+
moduleName: param.moduleName,
|
|
280
|
+
className,
|
|
281
|
+
type: param.type,
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
instrumentRuntimeTraceInstance(param) {
|
|
286
|
+
if (this.runtimeTraceInstrumentedInstances.has(param.instance)) {
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
this.runtimeTraceInstrumentedInstances.add(param.instance);
|
|
290
|
+
const prototype = Object.getPrototypeOf(param.instance);
|
|
291
|
+
if (!prototype) {
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
for (const methodName of Object.getOwnPropertyNames(prototype)) {
|
|
295
|
+
if (methodName === 'constructor') {
|
|
296
|
+
continue;
|
|
297
|
+
}
|
|
298
|
+
const descriptor = Object.getOwnPropertyDescriptor(prototype, methodName);
|
|
299
|
+
const method = descriptor?.value;
|
|
300
|
+
if (typeof method !== 'function') {
|
|
301
|
+
continue;
|
|
302
|
+
}
|
|
303
|
+
Object.defineProperty(param.instance, methodName, {
|
|
304
|
+
configurable: true,
|
|
305
|
+
writable: true,
|
|
306
|
+
value: (...args) => this.runtimeTraceRecorder.recordSpan({
|
|
307
|
+
name: `${param.className}.${methodName}`,
|
|
308
|
+
type: param.type,
|
|
309
|
+
moduleName: param.moduleName,
|
|
310
|
+
className: param.className,
|
|
311
|
+
methodName,
|
|
312
|
+
args: this.runtimeTraceRecorder.previewValue(args),
|
|
313
|
+
}, () => method.apply(param.instance, args)),
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
}
|
|
237
317
|
appendNestCoreModule(moduleTree) {
|
|
238
318
|
const usedProviders = this.findUsedNestCoreProvidersFromTree(moduleTree);
|
|
239
319
|
if (!usedProviders.length) {
|
|
@@ -596,13 +676,14 @@ let NestGraphInspectorSetup = NestGraphInspectorSetup_1 = class NestGraphInspect
|
|
|
596
676
|
};
|
|
597
677
|
}
|
|
598
678
|
findDirectRunProviderInstance(moduleName, providerName) {
|
|
599
|
-
const moduleRef = [...this.modulesContainer.values()].find(candidate => this.moduleName(candidate) === moduleName);
|
|
679
|
+
const moduleRef = [...this.modulesContainer.values()].find((candidate) => this.moduleName(candidate) === moduleName);
|
|
600
680
|
if (!moduleRef) {
|
|
601
681
|
return undefined;
|
|
602
682
|
}
|
|
603
683
|
const providerWrapper = [...moduleRef.providers.values()].find((wrapper) => {
|
|
604
684
|
const instance = wrapper.instance &&
|
|
605
|
-
(typeof wrapper.instance === 'object' ||
|
|
685
|
+
(typeof wrapper.instance === 'object' ||
|
|
686
|
+
typeof wrapper.instance === 'function')
|
|
606
687
|
? wrapper.instance
|
|
607
688
|
: null;
|
|
608
689
|
const resolvedName = wrapper.metatype?.name ||
|
|
@@ -613,7 +694,8 @@ let NestGraphInspectorSetup = NestGraphInspectorSetup_1 = class NestGraphInspect
|
|
|
613
694
|
return providerWrapper?.instance;
|
|
614
695
|
}
|
|
615
696
|
getDirectRunMethods(instance) {
|
|
616
|
-
if (!instance ||
|
|
697
|
+
if (!instance ||
|
|
698
|
+
(typeof instance !== 'object' && typeof instance !== 'function')) {
|
|
617
699
|
return [];
|
|
618
700
|
}
|
|
619
701
|
const prototype = Object.getPrototypeOf(instance);
|
|
@@ -621,7 +703,7 @@ let NestGraphInspectorSetup = NestGraphInspectorSetup_1 = class NestGraphInspect
|
|
|
621
703
|
return [];
|
|
622
704
|
}
|
|
623
705
|
const methods = Object.getOwnPropertyNames(prototype)
|
|
624
|
-
.filter(name => name !== 'constructor')
|
|
706
|
+
.filter((name) => name !== 'constructor')
|
|
625
707
|
.map((name) => {
|
|
626
708
|
const candidate = prototype[name];
|
|
627
709
|
if (typeof candidate !== 'function') {
|
|
@@ -640,7 +722,9 @@ let NestGraphInspectorSetup = NestGraphInspectorSetup_1 = class NestGraphInspect
|
|
|
640
722
|
})
|
|
641
723
|
.filter((method) => method !== null)
|
|
642
724
|
.sort((left, right) => left.name.localeCompare(right.name));
|
|
643
|
-
return [
|
|
725
|
+
return [
|
|
726
|
+
...new Map(methods.map((method) => [method.name, method])).values(),
|
|
727
|
+
];
|
|
644
728
|
}
|
|
645
729
|
getDirectRunMethodParameterTypes(param) {
|
|
646
730
|
const { instance, method, methodName } = param;
|
|
@@ -657,20 +741,20 @@ let NestGraphInspectorSetup = NestGraphInspectorSetup_1 = class NestGraphInspect
|
|
|
657
741
|
if (!runtimeNames?.length) {
|
|
658
742
|
return '[]';
|
|
659
743
|
}
|
|
660
|
-
return `[${runtimeNames.map(name => `${name}: unknown`).join(', ')}]`;
|
|
744
|
+
return `[${runtimeNames.map((name) => `${name}: unknown`).join(', ')}]`;
|
|
661
745
|
}
|
|
662
746
|
extractMethodParameterTypesFromProject(className, methodName) {
|
|
663
747
|
const targetClass = this.tsMorphProject
|
|
664
748
|
.getSourceFiles()
|
|
665
|
-
.flatMap(sourceFile => sourceFile.getDescendantsOfKind(ts_morph_1.SyntaxKind.ClassDeclaration))
|
|
666
|
-
.find(classDeclaration => classDeclaration.getName() === className);
|
|
749
|
+
.flatMap((sourceFile) => sourceFile.getDescendantsOfKind(ts_morph_1.SyntaxKind.ClassDeclaration))
|
|
750
|
+
.find((classDeclaration) => classDeclaration.getName() === className);
|
|
667
751
|
const method = targetClass?.getInstanceMethod(methodName);
|
|
668
752
|
if (!method) {
|
|
669
753
|
return undefined;
|
|
670
754
|
}
|
|
671
755
|
const parameters = method.getParameters();
|
|
672
756
|
return `[${parameters
|
|
673
|
-
.map(parameter => `${parameter.getName()}: ${this.typeToTypeScriptCode(parameter.getType(), parameter)}`)
|
|
757
|
+
.map((parameter) => `${parameter.getName()}: ${this.typeToTypeScriptCode(parameter.getType(), parameter)}`)
|
|
674
758
|
.join(', ')}]`;
|
|
675
759
|
}
|
|
676
760
|
extractMethodParameterNamesFromFunctionSource(methodName, method) {
|
|
@@ -682,7 +766,7 @@ let NestGraphInspectorSetup = NestGraphInspectorSetup_1 = class NestGraphInspect
|
|
|
682
766
|
.getClassOrThrow('DirectRunMethodSource')
|
|
683
767
|
.getInstanceMethod(methodName)
|
|
684
768
|
?.getParameters()
|
|
685
|
-
.map(parameter => parameter.getName());
|
|
769
|
+
.map((parameter) => parameter.getName());
|
|
686
770
|
if (names) {
|
|
687
771
|
return names;
|
|
688
772
|
}
|
|
@@ -696,15 +780,14 @@ let NestGraphInspectorSetup = NestGraphInspectorSetup_1 = class NestGraphInspect
|
|
|
696
780
|
.getInitializer();
|
|
697
781
|
const callable = initializer?.asKind(ts_morph_1.SyntaxKind.FunctionExpression) ??
|
|
698
782
|
initializer?.asKind(ts_morph_1.SyntaxKind.ArrowFunction);
|
|
699
|
-
return callable?.getParameters().map(parameter => parameter.getName());
|
|
783
|
+
return callable?.getParameters().map((parameter) => parameter.getName());
|
|
700
784
|
}
|
|
701
785
|
catch {
|
|
702
786
|
return undefined;
|
|
703
787
|
}
|
|
704
788
|
}
|
|
705
789
|
typeToTypeScriptCode(type, enclosingNode, seenTypeTexts = new Set()) {
|
|
706
|
-
if (type.isAny()
|
|
707
|
-
|| type.isUnknown()) {
|
|
790
|
+
if (type.isAny() || type.isUnknown()) {
|
|
708
791
|
return 'unknown';
|
|
709
792
|
}
|
|
710
793
|
if (type.isNever()) {
|
|
@@ -740,13 +823,13 @@ let NestGraphInspectorSetup = NestGraphInspectorSetup_1 = class NestGraphInspect
|
|
|
740
823
|
if (type.isUnion()) {
|
|
741
824
|
return type
|
|
742
825
|
.getUnionTypes()
|
|
743
|
-
.map(unionType => this.typeToTypeScriptCode(unionType, enclosingNode, new Set(seenTypeTexts)))
|
|
826
|
+
.map((unionType) => this.typeToTypeScriptCode(unionType, enclosingNode, new Set(seenTypeTexts)))
|
|
744
827
|
.join(' | ');
|
|
745
828
|
}
|
|
746
829
|
if (type.isTuple()) {
|
|
747
830
|
return `[${type
|
|
748
831
|
.getTupleElements()
|
|
749
|
-
.map(tupleType => this.typeToTypeScriptCode(tupleType, enclosingNode, new Set(seenTypeTexts)))
|
|
832
|
+
.map((tupleType) => this.typeToTypeScriptCode(tupleType, enclosingNode, new Set(seenTypeTexts)))
|
|
750
833
|
.join(', ')}]`;
|
|
751
834
|
}
|
|
752
835
|
if (type.isArray() || type.isReadonlyArray()) {
|
|
@@ -769,8 +852,7 @@ let NestGraphInspectorSetup = NestGraphInspectorSetup_1 = class NestGraphInspect
|
|
|
769
852
|
.map((property) => {
|
|
770
853
|
const propertyNode = property.getValueDeclaration() ?? property.getDeclarations()[0];
|
|
771
854
|
const propertyType = property.getTypeAtLocation(propertyNode ?? enclosingNode);
|
|
772
|
-
const optional = property.isOptional()
|
|
773
|
-
|| this.typeAllowsUndefined(propertyType);
|
|
855
|
+
const optional = property.isOptional() || this.typeAllowsUndefined(propertyType);
|
|
774
856
|
return `${this.propertyNameToTypeScriptCode(property.getName())}${optional ? '?' : ''}: ${this.typeToTypeScriptCode(propertyType, propertyNode ?? enclosingNode, new Set(seenTypeTexts))}`;
|
|
775
857
|
})
|
|
776
858
|
.join('; ')} }`;
|
|
@@ -784,9 +866,9 @@ let NestGraphInspectorSetup = NestGraphInspectorSetup_1 = class NestGraphInspect
|
|
|
784
866
|
return /^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name);
|
|
785
867
|
}
|
|
786
868
|
typeAllowsUndefined(type) {
|
|
787
|
-
return type.isUndefined()
|
|
788
|
-
|
|
789
|
-
|
|
869
|
+
return (type.isUndefined() ||
|
|
870
|
+
(type.isUnion() &&
|
|
871
|
+
type.getUnionTypes().some((unionType) => unionType.isUndefined())));
|
|
790
872
|
}
|
|
791
873
|
findGraphCycles(modules) {
|
|
792
874
|
let nextId = 1;
|
|
@@ -1003,6 +1085,6 @@ exports.NestGraphInspectorSetup = NestGraphInspectorSetup = NestGraphInspectorSe
|
|
|
1003
1085
|
http_output_adapter_1.HttpOutputAdapter,
|
|
1004
1086
|
file_output_adapter_1.FileOutputAdapter,
|
|
1005
1087
|
json_output_adapter_1.JsonOutputAdapter,
|
|
1006
|
-
viewer_output_adapter_1.ViewerOutputAdapter
|
|
1088
|
+
viewer_output_adapter_1.ViewerOutputAdapter,
|
|
1089
|
+
runtime_trace_recorder_1.RuntimeTraceRecorder])
|
|
1007
1090
|
], NestGraphInspectorSetup);
|
|
1008
|
-
//# sourceMappingURL=nest-graph-inspector.setup.js.map
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { DirectRunTraceRecorder, RuntimeTrace, RuntimeTraceHandle, RuntimeTraceSpanType, RuntimeTraceStartContext } from './types/direct-run.type';
|
|
2
|
+
type RuntimeTraceSpanInput = {
|
|
3
|
+
name: string;
|
|
4
|
+
type: RuntimeTraceSpanType;
|
|
5
|
+
moduleName?: string;
|
|
6
|
+
className?: string;
|
|
7
|
+
methodName?: string;
|
|
8
|
+
resource?: string;
|
|
9
|
+
args?: unknown;
|
|
10
|
+
metadata?: Record<string, string | number | boolean | null>;
|
|
11
|
+
};
|
|
12
|
+
export declare class RuntimeTraceRecorder implements DirectRunTraceRecorder {
|
|
13
|
+
private readonly activeContextStorage;
|
|
14
|
+
private readonly activeSpanStackStorage;
|
|
15
|
+
private readonly completedTraces;
|
|
16
|
+
private readonly activeSpans;
|
|
17
|
+
private readonly pendingSpans;
|
|
18
|
+
start(context: RuntimeTraceStartContext): RuntimeTraceHandle;
|
|
19
|
+
finishSuccess(handle: RuntimeTraceHandle, result: unknown): Promise<RuntimeTrace>;
|
|
20
|
+
finishError(handle: RuntimeTraceHandle, error: unknown): Promise<RuntimeTrace>;
|
|
21
|
+
getCompletedTrace(traceId: string): RuntimeTrace | undefined;
|
|
22
|
+
getCompletedTraces(): RuntimeTrace[];
|
|
23
|
+
runWithContext<T>(handle: RuntimeTraceHandle, callback: () => Promise<T>): Promise<T>;
|
|
24
|
+
recordSpan<T>(span: RuntimeTraceSpanInput, callback: () => T): T;
|
|
25
|
+
private finishTrace;
|
|
26
|
+
private pushSpan;
|
|
27
|
+
private updateSpan;
|
|
28
|
+
private trackPendingSpan;
|
|
29
|
+
private waitForPendingSpans;
|
|
30
|
+
private markPendingSpansNotAwaited;
|
|
31
|
+
private isRootSpan;
|
|
32
|
+
private buildFallbackTrace;
|
|
33
|
+
private persistCompletedTrace;
|
|
34
|
+
private isPromiseLike;
|
|
35
|
+
private classifyProviderType;
|
|
36
|
+
private resolveErrorName;
|
|
37
|
+
private resolveErrorMessage;
|
|
38
|
+
summarizeValue(value: unknown): string | null;
|
|
39
|
+
previewValue(value: unknown): unknown;
|
|
40
|
+
private errorResult;
|
|
41
|
+
}
|
|
42
|
+
export {};
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
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;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
8
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
+
exports.RuntimeTraceRecorder = void 0;
|
|
10
|
+
const node_async_hooks_1 = require("node:async_hooks");
|
|
11
|
+
const node_crypto_1 = require("node:crypto");
|
|
12
|
+
const common_1 = require("@nestjs/common");
|
|
13
|
+
let RuntimeTraceRecorder = class RuntimeTraceRecorder {
|
|
14
|
+
activeContextStorage = new node_async_hooks_1.AsyncLocalStorage();
|
|
15
|
+
activeSpanStackStorage = new node_async_hooks_1.AsyncLocalStorage();
|
|
16
|
+
completedTraces = new Map();
|
|
17
|
+
activeSpans = new Map();
|
|
18
|
+
pendingSpans = new Map();
|
|
19
|
+
start(context) {
|
|
20
|
+
return {
|
|
21
|
+
traceId: (0, node_crypto_1.randomUUID)(),
|
|
22
|
+
runId: (0, node_crypto_1.randomUUID)(),
|
|
23
|
+
rootSpanId: (0, node_crypto_1.randomUUID)(),
|
|
24
|
+
startedAtMs: Date.now(),
|
|
25
|
+
...context,
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
async finishSuccess(handle, result) {
|
|
29
|
+
return await this.finishTrace(handle, { ok: true, result });
|
|
30
|
+
}
|
|
31
|
+
async finishError(handle, error) {
|
|
32
|
+
return await this.finishTrace(handle, { ok: false, error });
|
|
33
|
+
}
|
|
34
|
+
getCompletedTrace(traceId) {
|
|
35
|
+
return this.completedTraces.get(traceId);
|
|
36
|
+
}
|
|
37
|
+
getCompletedTraces() {
|
|
38
|
+
return [...this.completedTraces.values()];
|
|
39
|
+
}
|
|
40
|
+
async runWithContext(handle, callback) {
|
|
41
|
+
const activeHandle = handle;
|
|
42
|
+
this.activeSpans.set(activeHandle.traceId, []);
|
|
43
|
+
this.pendingSpans.set(activeHandle.traceId, new Set());
|
|
44
|
+
return await this.activeContextStorage.run(activeHandle, async () => this.activeSpanStackStorage.run([activeHandle.rootSpanId], callback));
|
|
45
|
+
}
|
|
46
|
+
recordSpan(span, callback) {
|
|
47
|
+
const context = this.activeContextStorage.getStore();
|
|
48
|
+
if (!context) {
|
|
49
|
+
return callback();
|
|
50
|
+
}
|
|
51
|
+
if (this.isRootSpan(context, span)) {
|
|
52
|
+
return callback();
|
|
53
|
+
}
|
|
54
|
+
const startedAtMs = Date.now();
|
|
55
|
+
const spanId = (0, node_crypto_1.randomUUID)();
|
|
56
|
+
const parentStack = this.activeSpanStackStorage.getStore() ?? [
|
|
57
|
+
context.rootSpanId,
|
|
58
|
+
];
|
|
59
|
+
const stack = [...parentStack, spanId];
|
|
60
|
+
const parentSpanId = parentStack.at(-1);
|
|
61
|
+
return this.activeSpanStackStorage.run(stack, () => {
|
|
62
|
+
try {
|
|
63
|
+
const result = callback();
|
|
64
|
+
if (this.isPromiseLike(result)) {
|
|
65
|
+
this.pushSpan(context, span, spanId, parentSpanId, startedAtMs, 'partial', undefined, undefined, { async: true });
|
|
66
|
+
const pendingSpan = result.then((value) => {
|
|
67
|
+
this.updateSpan(context, spanId, startedAtMs, 'success', undefined, value, { async: true });
|
|
68
|
+
return value;
|
|
69
|
+
}, (error) => {
|
|
70
|
+
this.updateSpan(context, spanId, startedAtMs, 'error', error, undefined, { async: true });
|
|
71
|
+
throw error;
|
|
72
|
+
});
|
|
73
|
+
const trackedPendingSpan = Promise.resolve(pendingSpan).then(() => undefined, () => undefined);
|
|
74
|
+
this.trackPendingSpan(context.traceId, trackedPendingSpan);
|
|
75
|
+
return pendingSpan;
|
|
76
|
+
}
|
|
77
|
+
this.pushSpan(context, span, spanId, parentSpanId, startedAtMs, 'success', undefined, result);
|
|
78
|
+
return result;
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
this.pushSpan(context, span, spanId, parentSpanId, startedAtMs, 'error', error);
|
|
82
|
+
throw error;
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
async finishTrace(handle, param) {
|
|
87
|
+
const context = handle ||
|
|
88
|
+
this.activeContextStorage.getStore();
|
|
89
|
+
if (!context) {
|
|
90
|
+
return this.persistCompletedTrace(this.buildFallbackTrace());
|
|
91
|
+
}
|
|
92
|
+
const startedAt = new Date(context.startedAtMs).toISOString();
|
|
93
|
+
const status = param.ok ? 'success' : 'error';
|
|
94
|
+
this.markPendingSpansNotAwaited(context.traceId);
|
|
95
|
+
await this.waitForPendingSpans(context.traceId);
|
|
96
|
+
const endedAtMs = Date.now();
|
|
97
|
+
const endedAt = new Date(endedAtMs).toISOString();
|
|
98
|
+
const durationMs = Math.max(endedAtMs - context.startedAtMs, 0);
|
|
99
|
+
const rootSpan = {
|
|
100
|
+
spanId: context.rootSpanId,
|
|
101
|
+
runId: context.runId,
|
|
102
|
+
order: 0,
|
|
103
|
+
name: `${context.providerName}.${context.methodName}`,
|
|
104
|
+
moduleName: context.moduleName,
|
|
105
|
+
className: context.providerName,
|
|
106
|
+
methodName: context.methodName,
|
|
107
|
+
startedAt,
|
|
108
|
+
endedAt,
|
|
109
|
+
durationMs,
|
|
110
|
+
status,
|
|
111
|
+
errorName: !param.ok ? this.resolveErrorName(param.error) : undefined,
|
|
112
|
+
errorMessage: !param.ok
|
|
113
|
+
? this.resolveErrorMessage(param.error)
|
|
114
|
+
: undefined,
|
|
115
|
+
args: this.previewValue(context.args),
|
|
116
|
+
result: param.ok
|
|
117
|
+
? this.previewValue(param.result)
|
|
118
|
+
: this.errorResult(param.error),
|
|
119
|
+
};
|
|
120
|
+
const spans = [
|
|
121
|
+
rootSpan,
|
|
122
|
+
...(this.activeSpans.get(context.traceId) || []),
|
|
123
|
+
].sort((left, right) => left.order - right.order);
|
|
124
|
+
const failedSpan = spans.find((span) => span.status === 'error');
|
|
125
|
+
this.activeSpans.delete(context.traceId);
|
|
126
|
+
this.pendingSpans.delete(context.traceId);
|
|
127
|
+
return this.persistCompletedTrace({
|
|
128
|
+
traceId: context.traceId,
|
|
129
|
+
runId: context.runId,
|
|
130
|
+
entrypoint: {
|
|
131
|
+
module: context.moduleName,
|
|
132
|
+
className: context.providerName,
|
|
133
|
+
methodName: context.methodName,
|
|
134
|
+
},
|
|
135
|
+
startedAt,
|
|
136
|
+
endedAt,
|
|
137
|
+
totalDurationMs: durationMs,
|
|
138
|
+
status,
|
|
139
|
+
totalSpans: spans.length,
|
|
140
|
+
failedSpanId: failedSpan?.spanId,
|
|
141
|
+
spans,
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
pushSpan(context, input, spanId, parentSpanId, startedAtMs, status, error, result, metadata) {
|
|
145
|
+
const endedAtMs = Date.now();
|
|
146
|
+
const spans = this.activeSpans.get(context.traceId) || [];
|
|
147
|
+
spans.push({
|
|
148
|
+
spanId,
|
|
149
|
+
parentSpanId,
|
|
150
|
+
runId: context.runId,
|
|
151
|
+
order: spans.length + 1,
|
|
152
|
+
name: input.name,
|
|
153
|
+
moduleName: input.moduleName,
|
|
154
|
+
className: input.className,
|
|
155
|
+
methodName: input.methodName,
|
|
156
|
+
resource: input.resource,
|
|
157
|
+
startedAt: new Date(startedAtMs).toISOString(),
|
|
158
|
+
endedAt: new Date(endedAtMs).toISOString(),
|
|
159
|
+
durationMs: Math.max(endedAtMs - startedAtMs, 0),
|
|
160
|
+
status,
|
|
161
|
+
errorName: status === 'error' ? this.resolveErrorName(error) : undefined,
|
|
162
|
+
errorMessage: status === 'error' ? this.resolveErrorMessage(error) : undefined,
|
|
163
|
+
args: input.args,
|
|
164
|
+
result: status === 'error' ? this.errorResult(error) : this.previewValue(result),
|
|
165
|
+
metadata: { ...input.metadata, ...metadata },
|
|
166
|
+
});
|
|
167
|
+
this.activeSpans.set(context.traceId, spans);
|
|
168
|
+
}
|
|
169
|
+
updateSpan(context, spanId, startedAtMs, status, error, result, metadata) {
|
|
170
|
+
const spans = this.activeSpans.get(context.traceId);
|
|
171
|
+
const span = spans?.find((item) => item.spanId === spanId);
|
|
172
|
+
if (!span)
|
|
173
|
+
return;
|
|
174
|
+
const endedAtMs = Date.now();
|
|
175
|
+
span.endedAt = new Date(endedAtMs).toISOString();
|
|
176
|
+
span.durationMs = Math.max(endedAtMs - startedAtMs, 0);
|
|
177
|
+
span.status = status;
|
|
178
|
+
span.errorName =
|
|
179
|
+
status === 'error' ? this.resolveErrorName(error) : undefined;
|
|
180
|
+
span.errorMessage =
|
|
181
|
+
status === 'error' ? this.resolveErrorMessage(error) : undefined;
|
|
182
|
+
span.result =
|
|
183
|
+
status === 'error' ? this.errorResult(error) : this.previewValue(result);
|
|
184
|
+
span.metadata = { ...span.metadata, ...metadata };
|
|
185
|
+
}
|
|
186
|
+
trackPendingSpan(traceId, promise) {
|
|
187
|
+
const promises = this.pendingSpans.get(traceId);
|
|
188
|
+
if (!promises)
|
|
189
|
+
return;
|
|
190
|
+
promises.add(promise);
|
|
191
|
+
promise.finally(() => promises.delete(promise));
|
|
192
|
+
}
|
|
193
|
+
async waitForPendingSpans(traceId) {
|
|
194
|
+
const promises = this.pendingSpans.get(traceId);
|
|
195
|
+
if (!promises?.size)
|
|
196
|
+
return;
|
|
197
|
+
await Promise.all([...promises]);
|
|
198
|
+
}
|
|
199
|
+
markPendingSpansNotAwaited(traceId) {
|
|
200
|
+
const spans = this.activeSpans.get(traceId) || [];
|
|
201
|
+
for (const span of spans) {
|
|
202
|
+
if (span.status === 'partial' && span.metadata?.async) {
|
|
203
|
+
span.metadata = { ...span.metadata, awaited: false };
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
isRootSpan(context, span) {
|
|
208
|
+
return (span.moduleName === context.moduleName &&
|
|
209
|
+
span.className === context.providerName &&
|
|
210
|
+
span.methodName === context.methodName);
|
|
211
|
+
}
|
|
212
|
+
buildFallbackTrace() {
|
|
213
|
+
const now = new Date().toISOString();
|
|
214
|
+
const traceId = (0, node_crypto_1.randomUUID)();
|
|
215
|
+
const runId = (0, node_crypto_1.randomUUID)();
|
|
216
|
+
return {
|
|
217
|
+
traceId,
|
|
218
|
+
runId,
|
|
219
|
+
entrypoint: {
|
|
220
|
+
methodName: 'unknown',
|
|
221
|
+
},
|
|
222
|
+
startedAt: now,
|
|
223
|
+
endedAt: now,
|
|
224
|
+
totalDurationMs: 0,
|
|
225
|
+
status: 'partial',
|
|
226
|
+
totalSpans: 0,
|
|
227
|
+
spans: [],
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
persistCompletedTrace(trace) {
|
|
231
|
+
this.completedTraces.set(trace.traceId, trace);
|
|
232
|
+
return trace;
|
|
233
|
+
}
|
|
234
|
+
isPromiseLike(value) {
|
|
235
|
+
return Boolean(value &&
|
|
236
|
+
(typeof value === 'object' || typeof value === 'function') &&
|
|
237
|
+
'then' in value &&
|
|
238
|
+
typeof value.then === 'function');
|
|
239
|
+
}
|
|
240
|
+
classifyProviderType(providerName) {
|
|
241
|
+
const normalized = providerName.toLowerCase();
|
|
242
|
+
if (normalized.endsWith('controller')) {
|
|
243
|
+
return 'controller';
|
|
244
|
+
}
|
|
245
|
+
if (normalized.endsWith('repository')) {
|
|
246
|
+
return 'repository';
|
|
247
|
+
}
|
|
248
|
+
if (normalized.endsWith('service') || normalized.endsWith('provider')) {
|
|
249
|
+
return 'provider';
|
|
250
|
+
}
|
|
251
|
+
return 'unknown';
|
|
252
|
+
}
|
|
253
|
+
resolveErrorName(error) {
|
|
254
|
+
return error instanceof Error ? error.name : undefined;
|
|
255
|
+
}
|
|
256
|
+
resolveErrorMessage(error) {
|
|
257
|
+
if (error instanceof Error) {
|
|
258
|
+
return error.message;
|
|
259
|
+
}
|
|
260
|
+
return typeof error === 'string' ? error : undefined;
|
|
261
|
+
}
|
|
262
|
+
summarizeValue(value) {
|
|
263
|
+
if (value === undefined) {
|
|
264
|
+
return null;
|
|
265
|
+
}
|
|
266
|
+
try {
|
|
267
|
+
const json = JSON.stringify(value);
|
|
268
|
+
if (json === undefined) {
|
|
269
|
+
return null;
|
|
270
|
+
}
|
|
271
|
+
return json.length > 160 ? `${json.slice(0, 159)}…` : json;
|
|
272
|
+
}
|
|
273
|
+
catch {
|
|
274
|
+
return '[unserializable]';
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
previewValue(value) {
|
|
278
|
+
if (value === undefined) {
|
|
279
|
+
return null;
|
|
280
|
+
}
|
|
281
|
+
try {
|
|
282
|
+
JSON.stringify(value);
|
|
283
|
+
return value;
|
|
284
|
+
}
|
|
285
|
+
catch {
|
|
286
|
+
return '[unserializable]';
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
errorResult(error) {
|
|
290
|
+
return {
|
|
291
|
+
name: this.resolveErrorName(error),
|
|
292
|
+
message: this.resolveErrorMessage(error),
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
exports.RuntimeTraceRecorder = RuntimeTraceRecorder;
|
|
297
|
+
exports.RuntimeTraceRecorder = RuntimeTraceRecorder = __decorate([
|
|
298
|
+
(0, common_1.Injectable)()
|
|
299
|
+
], RuntimeTraceRecorder);
|