@aomex/async-trace 3.30.6 → 3.30.8-alpha.62.sha-92b25bb
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/CHANGELOG.md +8 -0
- package/dist/index.d.ts +112 -64
- package/dist/index.js +124 -111
- package/dist/index.js.map +1 -1
- package/package.json +20 -18
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,14 @@
|
|
|
3
3
|
All notable changes to this project will be documented in this file.
|
|
4
4
|
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
|
5
5
|
|
|
6
|
+
## [3.30.7](https://github.com/aomex/aomex/compare/v3.30.6...v3.30.7) (2026-11-01)
|
|
7
|
+
|
|
8
|
+
**Note:** Version bump only for package @aomex/async-trace
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
|
|
6
14
|
## [3.30.6](https://github.com/aomex/aomex/compare/v3.30.5...v3.30.6) (2026-10-19)
|
|
7
15
|
|
|
8
16
|
**Note:** Version bump only for package @aomex/async-trace
|
package/dist/index.d.ts
CHANGED
|
@@ -1,72 +1,122 @@
|
|
|
1
|
-
import { AsyncLocalStorage } from
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
*/
|
|
36
|
-
error?: Error | null;
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
export interface AsyncTraceRecord {
|
|
3
|
+
/**
|
|
4
|
+
* 唯一编号,用于识别子链路
|
|
5
|
+
*/
|
|
6
|
+
id: string;
|
|
7
|
+
/**
|
|
8
|
+
* 标签
|
|
9
|
+
*/
|
|
10
|
+
label: string;
|
|
11
|
+
/**
|
|
12
|
+
* 开始时间,毫秒时间戳
|
|
13
|
+
*/
|
|
14
|
+
start: number;
|
|
15
|
+
/**
|
|
16
|
+
* 结束时间,毫秒时间戳
|
|
17
|
+
*/
|
|
18
|
+
end: number;
|
|
19
|
+
/**
|
|
20
|
+
* 时间周期,毫秒
|
|
21
|
+
*/
|
|
22
|
+
duration: number;
|
|
23
|
+
/**
|
|
24
|
+
* 父链路
|
|
25
|
+
*/
|
|
26
|
+
parent?: string;
|
|
27
|
+
/**
|
|
28
|
+
* 子链路
|
|
29
|
+
*/
|
|
30
|
+
children: AsyncTraceRecord[];
|
|
31
|
+
/**
|
|
32
|
+
* 报错内容
|
|
33
|
+
*/
|
|
34
|
+
error?: Error | null;
|
|
37
35
|
}
|
|
38
36
|
declare class AsyncTrace {
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
37
|
+
records: AsyncTraceRecord[];
|
|
38
|
+
protected readonly storage: AsyncLocalStorage<string>;
|
|
39
|
+
protected idSequence: number;
|
|
40
|
+
run<T>(label: string, callback: (id: string) => Promise<T>): Promise<T>;
|
|
41
|
+
getRecord(id: string): AsyncTraceRecord;
|
|
42
|
+
/**
|
|
43
|
+
* 转成调用栈字符串
|
|
44
|
+
* ```
|
|
45
|
+
* foo: 123ms
|
|
46
|
+
* bar: 2000ms
|
|
47
|
+
* baz: 300ms
|
|
48
|
+
* test: 501ms
|
|
49
|
+
* ```
|
|
50
|
+
*/
|
|
51
|
+
toStack(records: AsyncTraceRecord[], indent?: number, level?: number): string;
|
|
54
52
|
}
|
|
55
|
-
declare const asyncTrace: AsyncTrace;
|
|
56
|
-
|
|
57
|
-
|
|
53
|
+
export declare const asyncTrace: AsyncTrace;
|
|
54
|
+
type NonReadonly<T extends object> = { -readonly [K in keyof T]: T[K]; };
|
|
55
|
+
declare module './middleware' {
|
|
56
|
+
interface MiddlewarePlatform<Deps extends object = object> {
|
|
58
57
|
/**
|
|
59
|
-
*
|
|
58
|
+
* 没有特定上下文的纯中间件,支持所有应用
|
|
60
59
|
*/
|
|
61
|
-
readonly
|
|
62
|
-
|
|
60
|
+
readonly mixin: {
|
|
61
|
+
<Props extends object = object>(fn: (ctx: NonReadonly<Middleware.MergeDeps<Props, Deps>>, next: Next) => any): object extends Deps ? MixinMiddleware<Props> : MixinMiddleware<Props> & {
|
|
62
|
+
_contextType: Middleware.WithDeps<object, Deps>;
|
|
63
|
+
};
|
|
63
64
|
};
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
declare class MixinMiddleware<Props extends object = object> extends Middleware<Props> {
|
|
68
|
+
protected _mixin_middleware_: 'mixin-middleware';
|
|
69
|
+
}
|
|
70
|
+
declare namespace Middleware {
|
|
71
|
+
type Infer<T> = T extends Middleware<infer R> ? R : T extends ((...args: any[]) => infer Return) ? Awaited<Return> extends Middleware<infer R> ? R : never : never;
|
|
72
|
+
/** 合并依赖;默认 `object` 不参与交叉 */
|
|
73
|
+
type MergeDeps<Current extends object, Next extends object> = object extends Current ? object extends Next ? Current : Next : object extends Next ? Current : Flatten<Current & Next>;
|
|
74
|
+
type Flatten<T extends object> = { [K in keyof T]: T[K]; } & {};
|
|
75
|
+
/** 把 Deps 叠到平台上下文上 */
|
|
76
|
+
type WithDeps<Ctx extends object, Deps extends object> = object extends Deps ? Ctx : object extends Ctx ? Flatten<Deps> : Ctx & Flatten<Deps>;
|
|
77
|
+
type Fn<Ctx = any> = (ctx: Ctx, next: Next) => any;
|
|
78
|
+
type CollectArrayType<T> = T extends Middleware<infer R> ? R : unknown;
|
|
79
|
+
}
|
|
80
|
+
interface MiddlewarePlatform<Deps extends object = object> {
|
|
81
|
+
/**
|
|
82
|
+
* 仅用于类型提示:假定上游已挂载对应中间件,不实际执行。
|
|
83
|
+
* 可无限链式调用。
|
|
84
|
+
*/
|
|
85
|
+
readonly dependsOn: <T extends Middleware<any> | ((...args: any[]) => Middleware<any> | Promise<Middleware<any>>)>(_middleware: T) => MiddlewarePlatform<Middleware.MergeDeps<Deps, Middleware.Infer<T>>>;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* 中间件基类
|
|
89
|
+
*/
|
|
90
|
+
declare abstract class Middleware<Props extends object = object> {
|
|
91
|
+
protected readonly fn: Middleware.Fn;
|
|
92
|
+
_contextType: object;
|
|
93
|
+
protected _props_must_be_used_: Props;
|
|
94
|
+
constructor(fn: Middleware.Fn);
|
|
95
|
+
/**
|
|
96
|
+
* 跳过执行中间件。
|
|
97
|
+
*
|
|
98
|
+
* 可传入布尔值(固定跳过/不跳过),或根据上下文动态判断的函数。
|
|
99
|
+
* 返回的类型未使用Partial,因为skip的设计是在部分场景下才需要触发的。
|
|
100
|
+
*/
|
|
101
|
+
skip(when: boolean | ((ctx: this['_contextType']) => boolean | Promise<boolean>)): MixinMiddleware<Props>;
|
|
102
|
+
/**
|
|
103
|
+
* 注册中间件
|
|
104
|
+
*/
|
|
105
|
+
static register(platform: Exclude<keyof MiddlewarePlatform, 'dependsOn'>, SubMiddleware: new (...args: any[]) => Middleware): void;
|
|
106
|
+
}
|
|
107
|
+
type Next = () => Promise<any>;
|
|
108
|
+
export interface AsyncTraceMiddlewareProps {
|
|
109
|
+
/**
|
|
110
|
+
* 链路追踪记录,仅在中间件后面的任务结束后才会生成
|
|
111
|
+
*/
|
|
112
|
+
readonly asyncTrace?: {
|
|
113
|
+
record: AsyncTraceRecord;
|
|
114
|
+
};
|
|
64
115
|
}
|
|
65
116
|
/**
|
|
66
117
|
* 追踪中间件从开始到结束的总链路
|
|
67
118
|
*/
|
|
68
|
-
declare const traceMiddleware: (label: string, callback?: (record: AsyncTraceRecord, ctx: any) => any) =>
|
|
69
|
-
|
|
119
|
+
export declare const traceMiddleware: (label: string, callback?: (record: AsyncTraceRecord, ctx: any) => any) => MixinMiddleware<AsyncTraceMiddlewareProps>;
|
|
70
120
|
/**
|
|
71
121
|
* 追踪类的方法或静态方法的链路
|
|
72
122
|
* ```typescript
|
|
@@ -78,8 +128,7 @@ declare const traceMiddleware: (label: string, callback?: (record: AsyncTraceRec
|
|
|
78
128
|
* }
|
|
79
129
|
* ```
|
|
80
130
|
*/
|
|
81
|
-
declare const traceMethod: <T, P extends (...args: any[]) => Promise<T>>(label?: string | ((...args: Parameters<P>) => string), callback?: (record: AsyncTraceRecord) => any) => (originalMethod: P, context: ClassMethodDecoratorContext) => (this: object, ...args: Parameters<P>) => Promise<any>;
|
|
82
|
-
|
|
131
|
+
export declare const traceMethod: <T, P extends (...args: any[]) => Promise<T>>(label?: string | ((...args: Parameters<P>) => string), callback?: (record: AsyncTraceRecord) => any) => (originalMethod: P, context: ClassMethodDecoratorContext) => (this: object, ...args: Parameters<P>) => Promise<any>;
|
|
83
132
|
/**
|
|
84
133
|
* 追踪代码段的链路
|
|
85
134
|
* ```typescript
|
|
@@ -93,6 +142,5 @@ declare const traceMethod: <T, P extends (...args: any[]) => Promise<T>>(label?:
|
|
|
93
142
|
* console.log(result); // 'bar'
|
|
94
143
|
* ```
|
|
95
144
|
*/
|
|
96
|
-
declare const traceBlock: <T>(label: string, logic: () => Promise<T>, callback?: (record: AsyncTraceRecord) => any) => Promise<T>;
|
|
97
|
-
|
|
98
|
-
export { type AsyncTraceMiddlewareProps, type AsyncTraceRecord, asyncTrace, traceBlock, traceMethod, traceMiddleware };
|
|
145
|
+
export declare const traceBlock: <T>(label: string, logic: () => Promise<T>, callback?: (record: AsyncTraceRecord) => any) => Promise<T>;
|
|
146
|
+
export {};
|
package/dist/index.js
CHANGED
|
@@ -1,122 +1,135 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import { middleware } from "@aomex/common";
|
|
1
3
|
// src/async-trace.ts
|
|
2
|
-
import { AsyncLocalStorage } from "async_hooks";
|
|
3
4
|
var AsyncTrace = class {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
*/
|
|
57
|
-
toStack(records, indent = 4, level = 0) {
|
|
58
|
-
return records.map((record) => {
|
|
59
|
-
return `${" ".repeat(level * indent)}${record.label}: ${record.duration}ms
|
|
5
|
+
records = [];
|
|
6
|
+
storage = new AsyncLocalStorage();
|
|
7
|
+
idSequence = 0;
|
|
8
|
+
async run(label, callback) {
|
|
9
|
+
const parent = this.storage.getStore();
|
|
10
|
+
if (++this.idSequence >= Number.MAX_SAFE_INTEGER) this.idSequence = 0;
|
|
11
|
+
const start = Date.now();
|
|
12
|
+
const id = start + "." + this.idSequence;
|
|
13
|
+
return this.storage.run(id, async () => {
|
|
14
|
+
const done = (err) => {
|
|
15
|
+
const end = Date.now();
|
|
16
|
+
this.records.push({
|
|
17
|
+
id,
|
|
18
|
+
start,
|
|
19
|
+
end,
|
|
20
|
+
duration: end - start,
|
|
21
|
+
label,
|
|
22
|
+
parent,
|
|
23
|
+
children: this.records.filter((item) => item.parent === id),
|
|
24
|
+
error: err
|
|
25
|
+
});
|
|
26
|
+
this.records = this.records.filter((item) => item.parent !== id);
|
|
27
|
+
};
|
|
28
|
+
try {
|
|
29
|
+
const result = await callback(id);
|
|
30
|
+
done(null);
|
|
31
|
+
return result;
|
|
32
|
+
} catch (e) {
|
|
33
|
+
const err = e instanceof Error ? e : new Error(String(e));
|
|
34
|
+
done(err);
|
|
35
|
+
throw err;
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
getRecord(id) {
|
|
40
|
+
const index = this.records.findIndex((item) => item.id === id);
|
|
41
|
+
const record = this.records[index];
|
|
42
|
+
if (record && !record.parent) this.records.splice(index, 1);
|
|
43
|
+
return record;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* 转成调用栈字符串
|
|
47
|
+
* ```
|
|
48
|
+
* foo: 123ms
|
|
49
|
+
* bar: 2000ms
|
|
50
|
+
* baz: 300ms
|
|
51
|
+
* test: 501ms
|
|
52
|
+
* ```
|
|
53
|
+
*/
|
|
54
|
+
toStack(records, indent = 4, level = 0) {
|
|
55
|
+
return records.map((record) => {
|
|
56
|
+
return `${" ".repeat(level * indent)}${record.label}: ${record.duration}ms
|
|
60
57
|
${this.toStack(record.children, indent, level + 1)}`;
|
|
61
|
-
|
|
62
|
-
|
|
58
|
+
}).join("");
|
|
59
|
+
}
|
|
63
60
|
};
|
|
64
|
-
|
|
65
|
-
|
|
61
|
+
const asyncTrace = new AsyncTrace();
|
|
66
62
|
// src/trace-middleware.ts
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
63
|
+
/**
|
|
64
|
+
* 追踪中间件从开始到结束的总链路
|
|
65
|
+
*/
|
|
66
|
+
const traceMiddleware = (label, callback) => {
|
|
67
|
+
return middleware.mixin(async (ctx, next) => {
|
|
68
|
+
let traceId;
|
|
69
|
+
try {
|
|
70
|
+
await asyncTrace.run(label, async (id) => {
|
|
71
|
+
traceId = id;
|
|
72
|
+
await next();
|
|
73
|
+
});
|
|
74
|
+
} finally {
|
|
75
|
+
const record = asyncTrace.getRecord(traceId);
|
|
76
|
+
ctx.asyncTrace = { record };
|
|
77
|
+
await callback?.(record, ctx);
|
|
78
|
+
}
|
|
79
|
+
});
|
|
82
80
|
};
|
|
83
|
-
|
|
84
81
|
// src/trace-method.ts
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
82
|
+
/**
|
|
83
|
+
* 追踪类的方法或静态方法的链路
|
|
84
|
+
* ```typescript
|
|
85
|
+
* class MyService {
|
|
86
|
+
* .@traceMethod('label')
|
|
87
|
+
* async getData() {
|
|
88
|
+
* return [];
|
|
89
|
+
* }
|
|
90
|
+
* }
|
|
91
|
+
* ```
|
|
92
|
+
*/
|
|
93
|
+
const traceMethod = (label, callback) => {
|
|
94
|
+
return (originalMethod, context) => {
|
|
95
|
+
return async function(...args) {
|
|
96
|
+
let traceId;
|
|
97
|
+
try {
|
|
98
|
+
return await asyncTrace.run(label === void 0 ? `${"displayName" in this && typeof this.displayName === "string" ? this.displayName : this.constructor.name}.${String(context.name)}` : typeof label === "string" ? label : label(...args), (id) => {
|
|
99
|
+
traceId = id;
|
|
100
|
+
return originalMethod.apply(this, args);
|
|
101
|
+
});
|
|
102
|
+
} finally {
|
|
103
|
+
await callback?.(asyncTrace.getRecord(traceId));
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
};
|
|
102
107
|
};
|
|
103
|
-
|
|
104
108
|
// src/trace-block.ts
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
109
|
+
/**
|
|
110
|
+
* 追踪代码段的链路
|
|
111
|
+
* ```typescript
|
|
112
|
+
* const result = await traceBlock('foo', async () => {
|
|
113
|
+
* await ...
|
|
114
|
+
* return 'bar';
|
|
115
|
+
* }, (record)=> {
|
|
116
|
+
* console.log(record); // { label: 'foo', delta: 123, ... }
|
|
117
|
+
* });
|
|
118
|
+
*
|
|
119
|
+
* console.log(result); // 'bar'
|
|
120
|
+
* ```
|
|
121
|
+
*/
|
|
122
|
+
const traceBlock = async (label, logic, callback) => {
|
|
123
|
+
let traceId;
|
|
124
|
+
try {
|
|
125
|
+
return await asyncTrace.run(label, (id) => {
|
|
126
|
+
traceId = id;
|
|
127
|
+
return logic();
|
|
128
|
+
});
|
|
129
|
+
} finally {
|
|
130
|
+
await callback?.(asyncTrace.getRecord(traceId));
|
|
131
|
+
}
|
|
121
132
|
};
|
|
133
|
+
export { asyncTrace, traceBlock, traceMethod, traceMiddleware };
|
|
134
|
+
|
|
122
135
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/async-trace.ts","../src/trace-middleware.ts","../src/trace-method.ts","../src/trace-block.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\n\nexport interface AsyncTraceRecord {\n /**\n * 唯一编号,用于识别子链路\n */\n id: string;\n /**\n * 标签\n */\n label: string;\n /**\n * 开始时间,毫秒时间戳\n */\n start: number;\n /**\n * 结束时间,毫秒时间戳\n */\n end: number;\n /**\n * 时间周期,毫秒\n */\n duration: number;\n /**\n * 父链路\n */\n parent?: string;\n /**\n * 子链路\n */\n children: AsyncTraceRecord[];\n /**\n * 报错内容\n */\n error?: Error | null;\n}\n\nclass AsyncTrace {\n public records: AsyncTraceRecord[] = [];\n\n protected readonly storage = new AsyncLocalStorage<string>();\n protected idSequence = 0;\n\n async run<T>(label: string, callback: (id: string) => Promise<T>): Promise<T> {\n const parent = this.storage.getStore();\n\n if (++this.idSequence >= Number.MAX_SAFE_INTEGER) {\n this.idSequence = 0;\n }\n\n const start = Date.now();\n const id = start + '.' + this.idSequence;\n\n return this.storage.run(id, async () => {\n const done = (err: Error | null) => {\n const end = Date.now();\n this.records.push({\n id,\n start,\n end,\n duration: end - start,\n label,\n parent,\n children: this.records.filter((item) => item.parent === id),\n error: err,\n });\n this.records = this.records.filter((item) => item.parent !== id);\n };\n\n try {\n const result = await callback(id);\n done(null);\n return result;\n } catch (e) {\n const err = e instanceof Error ? e : new Error(String(e));\n done(err);\n throw err;\n }\n });\n }\n\n getRecord(id: string) {\n const index = this.records.findIndex((item) => item.id === id);\n const record = this.records[index];\n if (record && !record.parent) {\n this.records.splice(index, 1);\n }\n return record!;\n }\n\n /**\n * 转成调用栈字符串\n * ```\n * foo: 123ms\n * bar: 2000ms\n * baz: 300ms\n * test: 501ms\n * ```\n */\n toStack(records: AsyncTraceRecord[], indent: number = 4, level: number = 0): string {\n return records\n .map((record) => {\n return `${' '.repeat(level * indent)}${record.label}: ${record.duration}ms\n${this.toStack(record.children, indent, level + 1)}`;\n })\n .join('');\n }\n}\n\nexport const asyncTrace = new AsyncTrace();\n","import { middleware } from '@aomex/common';\nimport { asyncTrace, type AsyncTraceRecord } from './async-trace';\n\nexport interface AsyncTraceMiddlewareProps {\n /**\n * 链路追踪记录,仅在中间件后面的任务结束后才会生成\n */\n readonly asyncTrace?: { record: AsyncTraceRecord };\n}\n\n/**\n * 追踪中间件从开始到结束的总链路\n */\nexport const traceMiddleware = (\n label: string,\n callback?: (record: AsyncTraceRecord, ctx: any) => any,\n) => {\n return middleware.mixin<AsyncTraceMiddlewareProps>(async (ctx, next) => {\n let traceId!: string;\n try {\n await asyncTrace.run(label, async (id) => {\n traceId = id;\n await next();\n });\n } finally {\n const record = asyncTrace.getRecord(traceId);\n ctx.asyncTrace = { record };\n await callback?.(record, ctx);\n }\n });\n};\n","import { asyncTrace, type AsyncTraceRecord } from './async-trace';\n\n/**\n * 追踪类的方法或静态方法的链路\n * ```typescript\n * class MyService {\n * .@traceMethod('label')\n * async getData() {\n * return [];\n * }\n * }\n * ```\n */\nexport const traceMethod = <T, P extends (...args: any[]) => Promise<T>>(\n label?: string | ((...args: Parameters<P>) => string),\n callback?: (record: AsyncTraceRecord) => any,\n) => {\n return (originalMethod: P, context: ClassMethodDecoratorContext) => {\n return async function (this: object, ...args: Parameters<P>): Promise<any> {\n let traceId!: string;\n try {\n return await asyncTrace.run<T>(\n label === undefined\n ? `${\n 'displayName' in this && typeof this.displayName === 'string'\n ? this.displayName\n : this.constructor.name\n }.${String(context.name)}`\n : typeof label === 'string'\n ? label\n : label(...args),\n (id) => {\n traceId = id;\n return originalMethod.apply(this, args);\n },\n );\n } finally {\n await callback?.(asyncTrace.getRecord(traceId));\n }\n };\n };\n};\n","import { asyncTrace, type AsyncTraceRecord } from './async-trace';\n\n/**\n * 追踪代码段的链路\n * ```typescript\n * const result = await traceBlock('foo', async () => {\n * await ...\n * return 'bar';\n * }, (record)=> {\n * console.log(record); // { label: 'foo', delta: 123, ... }\n * });\n *\n * console.log(result); // 'bar'\n * ```\n */\nexport const traceBlock = async <T>(\n label: string,\n logic: () => Promise<T>,\n callback?: (record: AsyncTraceRecord) => any,\n): Promise<T> => {\n let traceId!: string;\n try {\n return await asyncTrace.run<T>(label, (id) => {\n traceId = id;\n return logic();\n });\n } finally {\n await callback?.(asyncTrace.getRecord(traceId));\n }\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/async-trace.ts","../src/trace-middleware.ts","../src/trace-method.ts","../src/trace-block.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\n\nexport interface AsyncTraceRecord {\n /**\n * 唯一编号,用于识别子链路\n */\n id: string;\n /**\n * 标签\n */\n label: string;\n /**\n * 开始时间,毫秒时间戳\n */\n start: number;\n /**\n * 结束时间,毫秒时间戳\n */\n end: number;\n /**\n * 时间周期,毫秒\n */\n duration: number;\n /**\n * 父链路\n */\n parent?: string;\n /**\n * 子链路\n */\n children: AsyncTraceRecord[];\n /**\n * 报错内容\n */\n error?: Error | null;\n}\n\nclass AsyncTrace {\n public records: AsyncTraceRecord[] = [];\n\n protected readonly storage = new AsyncLocalStorage<string>();\n protected idSequence = 0;\n\n async run<T>(label: string, callback: (id: string) => Promise<T>): Promise<T> {\n const parent = this.storage.getStore();\n\n if (++this.idSequence >= Number.MAX_SAFE_INTEGER) {\n this.idSequence = 0;\n }\n\n const start = Date.now();\n const id = start + '.' + this.idSequence;\n\n return this.storage.run(id, async () => {\n const done = (err: Error | null) => {\n const end = Date.now();\n this.records.push({\n id,\n start,\n end,\n duration: end - start,\n label,\n parent,\n children: this.records.filter((item) => item.parent === id),\n error: err,\n });\n this.records = this.records.filter((item) => item.parent !== id);\n };\n\n try {\n const result = await callback(id);\n done(null);\n return result;\n } catch (e) {\n const err = e instanceof Error ? e : new Error(String(e));\n done(err);\n throw err;\n }\n });\n }\n\n getRecord(id: string) {\n const index = this.records.findIndex((item) => item.id === id);\n const record = this.records[index];\n if (record && !record.parent) {\n this.records.splice(index, 1);\n }\n return record!;\n }\n\n /**\n * 转成调用栈字符串\n * ```\n * foo: 123ms\n * bar: 2000ms\n * baz: 300ms\n * test: 501ms\n * ```\n */\n toStack(records: AsyncTraceRecord[], indent: number = 4, level: number = 0): string {\n return records\n .map((record) => {\n return `${' '.repeat(level * indent)}${record.label}: ${record.duration}ms\n${this.toStack(record.children, indent, level + 1)}`;\n })\n .join('');\n }\n}\n\nexport const asyncTrace = new AsyncTrace();\n","import { middleware } from '@aomex/common';\nimport { asyncTrace, type AsyncTraceRecord } from './async-trace';\n\nexport interface AsyncTraceMiddlewareProps {\n /**\n * 链路追踪记录,仅在中间件后面的任务结束后才会生成\n */\n readonly asyncTrace?: { record: AsyncTraceRecord };\n}\n\n/**\n * 追踪中间件从开始到结束的总链路\n */\nexport const traceMiddleware = (\n label: string,\n callback?: (record: AsyncTraceRecord, ctx: any) => any,\n) => {\n return middleware.mixin<AsyncTraceMiddlewareProps>(async (ctx, next) => {\n let traceId!: string;\n try {\n await asyncTrace.run(label, async (id) => {\n traceId = id;\n await next();\n });\n } finally {\n const record = asyncTrace.getRecord(traceId);\n ctx.asyncTrace = { record };\n await callback?.(record, ctx);\n }\n });\n};\n","import { asyncTrace, type AsyncTraceRecord } from './async-trace';\n\n/**\n * 追踪类的方法或静态方法的链路\n * ```typescript\n * class MyService {\n * .@traceMethod('label')\n * async getData() {\n * return [];\n * }\n * }\n * ```\n */\nexport const traceMethod = <T, P extends (...args: any[]) => Promise<T>>(\n label?: string | ((...args: Parameters<P>) => string),\n callback?: (record: AsyncTraceRecord) => any,\n) => {\n return (originalMethod: P, context: ClassMethodDecoratorContext) => {\n return async function (this: object, ...args: Parameters<P>): Promise<any> {\n let traceId!: string;\n try {\n return await asyncTrace.run<T>(\n label === undefined\n ? `${\n 'displayName' in this && typeof this.displayName === 'string'\n ? this.displayName\n : this.constructor.name\n }.${String(context.name)}`\n : typeof label === 'string'\n ? label\n : label(...args),\n (id) => {\n traceId = id;\n return originalMethod.apply(this, args);\n },\n );\n } finally {\n await callback?.(asyncTrace.getRecord(traceId));\n }\n };\n };\n};\n","import { asyncTrace, type AsyncTraceRecord } from './async-trace';\n\n/**\n * 追踪代码段的链路\n * ```typescript\n * const result = await traceBlock('foo', async () => {\n * await ...\n * return 'bar';\n * }, (record)=> {\n * console.log(record); // { label: 'foo', delta: 123, ... }\n * });\n *\n * console.log(result); // 'bar'\n * ```\n */\nexport const traceBlock = async <T>(\n label: string,\n logic: () => Promise<T>,\n callback?: (record: AsyncTraceRecord) => any,\n): Promise<T> => {\n let traceId!: string;\n try {\n return await asyncTrace.run<T>(label, (id) => {\n traceId = id;\n return logic();\n });\n } finally {\n await callback?.(asyncTrace.getRecord(traceId));\n }\n};\n"],"mappings":";;;AAqCA,IAAM,aAAN,MAAiB;CACf,UAAqC,CAAC;CAEtC,UAA6B,IAAI,kBAA0B;CAC3D,aAAuB;CAEvB,MAAM,IAAO,OAAe,UAAkD;EAC5E,MAAM,SAAS,KAAK,QAAQ,SAAS;EAErC,IAAI,EAAE,KAAK,cAAc,OAAO,kBAC9B,KAAK,aAAa;EAGpB,MAAM,QAAQ,KAAK,IAAI;EACvB,MAAM,KAAK,QAAQ,MAAM,KAAK;EAE9B,OAAO,KAAK,QAAQ,IAAI,IAAI,YAAY;GACtC,MAAM,QAAQ,QAAsB;IAClC,MAAM,MAAM,KAAK,IAAI;IACrB,KAAK,QAAQ,KAAK;KAChB;KACA;KACA;KACA,UAAU,MAAM;KAChB;KACA;KACA,UAAU,KAAK,QAAQ,QAAQ,SAAS,KAAK,WAAW,EAAE;KAC1D,OAAO;IACT,CAAC;IACD,KAAK,UAAU,KAAK,QAAQ,QAAQ,SAAS,KAAK,WAAW,EAAE;GACjE;GAEA,IAAI;IACF,MAAM,SAAS,MAAM,SAAS,EAAE;IAChC,KAAK,IAAI;IACT,OAAO;GACT,SAAS,GAAG;IACV,MAAM,MAAM,aAAa,QAAQ,IAAI,IAAI,MAAM,OAAO,CAAC,CAAC;IACxD,KAAK,GAAG;IACR,MAAM;GACR;EACF,CAAC;CACH;CAEA,UAAU,IAAY;EACpB,MAAM,QAAQ,KAAK,QAAQ,WAAW,SAAS,KAAK,OAAO,EAAE;EAC7D,MAAM,SAAS,KAAK,QAAQ;EAC5B,IAAI,UAAU,CAAC,OAAO,QACpB,KAAK,QAAQ,OAAO,OAAO,CAAC;EAE9B,OAAO;CACT;;;;;;;;;;CAWA,QAAQ,SAA6B,SAAiB,GAAG,QAAgB,GAAW;EAClF,OAAO,QACJ,KAAK,WAAW;GACf,OAAO,GAAG,IAAI,OAAO,QAAQ,MAAM,IAAI,OAAO,MAAM,IAAI,OAAO,SAAS;EAC9E,KAAK,QAAQ,OAAO,UAAU,QAAQ,QAAQ,CAAC;EAC3C,CAAC,CAAC,CACD,KAAK,EAAE;CACZ;AACF;AAEA,MAAa,aAAa,IAAI,WAAW;;;;;AChGzC,MAAa,mBACX,OACA,aACG;CACH,OAAO,WAAW,MAAiC,OAAO,KAAK,SAAS;EACtE,IAAI;EACJ,IAAI;GACF,MAAM,WAAW,IAAI,OAAO,OAAO,OAAO;IACxC,UAAU;IACV,MAAM,KAAK;GACb,CAAC;EACH,UAAU;GACR,MAAM,SAAS,WAAW,UAAU,OAAO;GAC3C,IAAI,aAAa,EAAE,OAAO;GAC1B,MAAM,WAAW,QAAQ,GAAG;EAC9B;CACF,CAAC;AACH;;;;;;;;;;;;;ACjBA,MAAa,eACX,OACA,aACG;CACH,QAAQ,gBAAmB,YAAyC;EAClE,OAAO,eAA8B,GAAG,MAAmC;GACzE,IAAI;GACJ,IAAI;IACF,OAAO,MAAM,WAAW,IACtB,UAAU,KAAA,IACN,GACE,iBAAiB,QAAQ,OAAO,KAAK,gBAAgB,WACjD,KAAK,cACL,KAAK,YAAY,KACtB,GAAG,OAAO,QAAQ,IAAI,MACvB,OAAO,UAAU,WACf,QACA,MAAM,GAAG,IAAI,IAClB,OAAO;KACN,UAAU;KACV,OAAO,eAAe,MAAM,MAAM,IAAI;IACxC,CACF;GACF,UAAU;IACR,MAAM,WAAW,WAAW,UAAU,OAAO,CAAC;GAChD;EACF;CACF;AACF;;;;;;;;;;;;;;;AC1BA,MAAa,aAAa,OACxB,OACA,OACA,aACe;CACf,IAAI;CACJ,IAAI;EACF,OAAO,MAAM,WAAW,IAAO,QAAQ,OAAO;GAC5C,UAAU;GACV,OAAO,MAAM;EACf,CAAC;CACH,UAAU;EACR,MAAM,WAAW,WAAW,UAAU,OAAO,CAAC;CAChD;AACF"}
|
package/package.json
CHANGED
|
@@ -1,23 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aomex/async-trace",
|
|
3
|
-
"version": "3.30.
|
|
3
|
+
"version": "3.30.8-alpha.62.sha-92b25bb",
|
|
4
4
|
"description": "异步逻辑链路追踪",
|
|
5
|
-
"repository":
|
|
6
|
-
"type": "git",
|
|
7
|
-
"url": "git@github.com:aomex/aomex.git"
|
|
8
|
-
},
|
|
5
|
+
"repository": "git@github.com:aomex/aomex.git",
|
|
9
6
|
"homepage": "https://aomex.js.org",
|
|
10
7
|
"license": "MIT",
|
|
11
8
|
"type": "module",
|
|
12
9
|
"sideEffects": false,
|
|
13
|
-
"
|
|
14
|
-
|
|
15
|
-
".": {
|
|
16
|
-
"types": "./dist/index.d.ts",
|
|
17
|
-
"import": "./dist/index.js"
|
|
18
|
-
},
|
|
19
|
-
"./package.json": "./package.json"
|
|
10
|
+
"scripts": {
|
|
11
|
+
"prepublishOnly": "tsdown"
|
|
20
12
|
},
|
|
13
|
+
"types": "src/index.ts",
|
|
14
|
+
"exports": "./src/index.ts",
|
|
21
15
|
"files": [
|
|
22
16
|
"dist",
|
|
23
17
|
"LICENSE",
|
|
@@ -26,15 +20,23 @@
|
|
|
26
20
|
"CHANGELOG.md"
|
|
27
21
|
],
|
|
28
22
|
"publishConfig": {
|
|
23
|
+
"types": "dist/index.d.ts",
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"import": "./dist/index.js"
|
|
28
|
+
},
|
|
29
|
+
"./package.json": "./package.json"
|
|
30
|
+
},
|
|
29
31
|
"access": "public"
|
|
30
32
|
},
|
|
31
33
|
"peerDependencies": {
|
|
32
|
-
"@aomex/common": "^
|
|
34
|
+
"@aomex/common": "^4.0.0"
|
|
33
35
|
},
|
|
34
36
|
"devDependencies": {
|
|
35
|
-
"@aomex/common": "3.30.
|
|
36
|
-
"@aomex/console": "3.30.
|
|
37
|
-
"@aomex/web": "3.30.
|
|
37
|
+
"@aomex/common": "3.30.8-alpha.62.sha-92b25bb",
|
|
38
|
+
"@aomex/console": "3.30.8-alpha.62.sha-92b25bb",
|
|
39
|
+
"@aomex/web": "3.30.8-alpha.62.sha-92b25bb"
|
|
38
40
|
},
|
|
39
|
-
"
|
|
40
|
-
}
|
|
41
|
+
"gitHead": "92b25bbcd6c3ae28160316117a74c88619b5bc8d"
|
|
42
|
+
}
|