@aomex/async-trace 1.0.2

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 ADDED
@@ -0,0 +1,7 @@
1
+ # @aomex/async-trace
2
+
3
+ ## 1.0.2
4
+
5
+ ### Patch Changes
6
+
7
+ - [`57683f8`](https://github.com/aomex/aomex/commit/57683f8da5c02eb07946c3fdb3d4339587d356a2) Thanks [@geekact](https://github.com/geekact)! - feat(async-trace): 异步逻辑链路追踪
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023-2024 geekact
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,81 @@
1
+ import { AsyncLocalStorage } from 'async_hooks';
2
+ import * as _aomex_core from '@aomex/core';
3
+
4
+ interface AsyncTraceRecord {
5
+ id: number;
6
+ /**
7
+ * 标签
8
+ */
9
+ label: string;
10
+ /**
11
+ * 开始时间,毫秒时间戳
12
+ */
13
+ start: number;
14
+ /**
15
+ * 结束时间,毫秒时间戳
16
+ */
17
+ end: number;
18
+ /**
19
+ * 时间周期,毫秒
20
+ */
21
+ delta: number;
22
+ /**
23
+ * 父链路
24
+ */
25
+ parent?: number;
26
+ /**
27
+ * 子链路
28
+ */
29
+ children: AsyncTraceRecord[];
30
+ }
31
+ declare class AsyncTrace {
32
+ records: AsyncTraceRecord[];
33
+ protected readonly storage: AsyncLocalStorage<number>;
34
+ protected idSequence: number;
35
+ run<T>(label: string, callback: (id: number) => Promise<T>): Promise<T>;
36
+ getRecord(id: number): AsyncTraceRecord;
37
+ }
38
+ declare const asyncTrace: AsyncTrace;
39
+
40
+ interface AsyncTraceMiddlewareProps {
41
+ /**
42
+ * 链路追踪记录,仅在中间件后面的任务结束后才会生成
43
+ */
44
+ readonly asyncTrace?: {
45
+ record: AsyncTraceRecord;
46
+ };
47
+ }
48
+ /**
49
+ * 追踪中间件从开始到结束的总链路
50
+ */
51
+ declare const traceMiddleware: (label: string, callback?: (record: AsyncTraceRecord) => any) => _aomex_core.MixinMiddleware<AsyncTraceMiddlewareProps>;
52
+
53
+ /**
54
+ * 追踪类的方法或静态方法的链路
55
+ * ```typescript
56
+ * class MyService {
57
+ * .@traceMethod('label')
58
+ * async getData() {
59
+ * return [];
60
+ * }
61
+ * }
62
+ * ```
63
+ */
64
+ 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>;
65
+
66
+ /**
67
+ * 追踪代码段的链路
68
+ * ```typescript
69
+ * const result = await traceBlock('foo', async () => {
70
+ * await ...
71
+ * return 'bar';
72
+ * }, (record)=> {
73
+ * console.log(record); // { label: 'foo', delta: 123, ... }
74
+ * });
75
+ *
76
+ * console.log(result); // 'bar'
77
+ * ```
78
+ */
79
+ declare const traceBlock: <T>(label: string, logic: () => Promise<T>, callback?: (record: AsyncTraceRecord) => any) => Promise<T>;
80
+
81
+ export { type AsyncTraceMiddlewareProps, type AsyncTraceRecord, asyncTrace, traceBlock, traceMethod, traceMiddleware };
package/dist/index.js ADDED
@@ -0,0 +1,105 @@
1
+ // src/async-trace.ts
2
+ import { AsyncLocalStorage } from "async_hooks";
3
+ var AsyncTrace = class {
4
+ records = [];
5
+ storage = new AsyncLocalStorage();
6
+ idSequence = 0;
7
+ run(label, callback) {
8
+ const parent = this.storage.getStore();
9
+ const id = ++this.idSequence;
10
+ return new Promise((resolve, reject) => {
11
+ this.storage.run(id, async () => {
12
+ const start = Date.now();
13
+ const done = () => {
14
+ const end = Date.now();
15
+ this.records.push({
16
+ id,
17
+ start,
18
+ end,
19
+ delta: end - start,
20
+ label,
21
+ parent,
22
+ children: this.records.filter((item) => item.parent === id)
23
+ });
24
+ this.records = this.records.filter((item) => item.parent !== id);
25
+ };
26
+ try {
27
+ const result = await callback(id);
28
+ done();
29
+ resolve(result);
30
+ } catch (e) {
31
+ done();
32
+ reject(e);
33
+ }
34
+ });
35
+ });
36
+ }
37
+ getRecord(id) {
38
+ const index = this.records.findIndex((item) => item.id === id);
39
+ const record = this.records[index];
40
+ if (record && !record.parent) {
41
+ this.records.splice(index, 1);
42
+ }
43
+ return record;
44
+ }
45
+ };
46
+ var asyncTrace = new AsyncTrace();
47
+
48
+ // src/trace-middleware.ts
49
+ import { middleware } from "@aomex/core";
50
+ var traceMiddleware = (label, callback) => {
51
+ return middleware.mixin(async (ctx, next) => {
52
+ let traceId;
53
+ try {
54
+ await asyncTrace.run(label, async (id) => {
55
+ traceId = id;
56
+ await next();
57
+ });
58
+ } finally {
59
+ const record = asyncTrace.getRecord(traceId);
60
+ ctx.asyncTrace = { record };
61
+ await callback?.(record);
62
+ }
63
+ });
64
+ };
65
+
66
+ // src/trace-method.ts
67
+ var traceMethod = (label, callback) => {
68
+ return (originalMethod, _context) => {
69
+ return async function(...args) {
70
+ let traceId;
71
+ try {
72
+ return await asyncTrace.run(
73
+ typeof label === "string" ? label : label(...args),
74
+ (id) => {
75
+ traceId = id;
76
+ return originalMethod.apply(this, args);
77
+ }
78
+ );
79
+ } finally {
80
+ callback?.(asyncTrace.getRecord(traceId));
81
+ }
82
+ };
83
+ };
84
+ };
85
+
86
+ // src/trace-block.ts
87
+ var traceBlock = async (label, logic, callback) => {
88
+ let traceId;
89
+ try {
90
+ return await asyncTrace.run(label, (id) => {
91
+ traceId = id;
92
+ return logic();
93
+ });
94
+ } finally {
95
+ const record = asyncTrace.getRecord(traceId);
96
+ await callback?.(record);
97
+ }
98
+ };
99
+ export {
100
+ asyncTrace,
101
+ traceBlock,
102
+ traceMethod,
103
+ traceMiddleware
104
+ };
105
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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 'async_hooks';\n\nexport interface AsyncTraceRecord {\n id: number;\n /**\n * 标签\n */\n label: string;\n /**\n * 开始时间,毫秒时间戳\n */\n start: number;\n /**\n * 结束时间,毫秒时间戳\n */\n end: number;\n /**\n * 时间周期,毫秒\n */\n delta: number;\n /**\n * 父链路\n */\n parent?: number;\n /**\n * 子链路\n */\n children: AsyncTraceRecord[];\n}\n\nclass AsyncTrace {\n public records: AsyncTraceRecord[] = [];\n\n protected readonly storage = new AsyncLocalStorage<number>();\n protected idSequence = 0;\n\n run<T>(label: string, callback: (id: number) => Promise<T>): Promise<T> {\n const parent = this.storage.getStore();\n const id = ++this.idSequence;\n\n return new Promise<T>((resolve, reject) => {\n this.storage.run(id, async () => {\n const start = Date.now();\n const done = () => {\n const end = Date.now();\n this.records.push({\n id,\n start,\n end,\n delta: end - start,\n label,\n parent,\n children: this.records.filter((item) => item.parent === id),\n });\n this.records = this.records.filter((item) => item.parent !== id);\n };\n\n try {\n const result = await callback(id);\n done();\n resolve(result);\n } catch (e) {\n done();\n reject(e);\n }\n });\n });\n }\n\n getRecord(id: number) {\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\nexport const asyncTrace = new AsyncTrace();\n","import { middleware } from '@aomex/core';\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) => any,\n) => {\n return middleware.mixin<AsyncTraceMiddlewareProps>(async (ctx, next) => {\n let traceId!: number;\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);\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!: number;\n try {\n return await asyncTrace.run<T>(\n typeof label === 'string' ? label : label(...args),\n (id) => {\n traceId = id;\n return originalMethod.apply(this, args);\n },\n );\n } finally {\n 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!: number;\n try {\n return await asyncTrace.run<T>(label, (id) => {\n traceId = id;\n return logic();\n });\n } finally {\n const record = asyncTrace.getRecord(traceId)!;\n await callback?.(record);\n }\n};\n"],"mappings":";AAAA,SAAS,yBAAyB;AA8BlC,IAAM,aAAN,MAAiB;AAAA,EACR,UAA8B,CAAC;AAAA,EAEnB,UAAU,IAAI,kBAA0B;AAAA,EACjD,aAAa;AAAA,EAEvB,IAAO,OAAe,UAAkD;AACtE,UAAM,SAAS,KAAK,QAAQ,SAAS;AACrC,UAAM,KAAK,EAAE,KAAK;AAElB,WAAO,IAAI,QAAW,CAAC,SAAS,WAAW;AACzC,WAAK,QAAQ,IAAI,IAAI,YAAY;AAC/B,cAAM,QAAQ,KAAK,IAAI;AACvB,cAAM,OAAO,MAAM;AACjB,gBAAM,MAAM,KAAK,IAAI;AACrB,eAAK,QAAQ,KAAK;AAAA,YAChB;AAAA,YACA;AAAA,YACA;AAAA,YACA,OAAO,MAAM;AAAA,YACb;AAAA,YACA;AAAA,YACA,UAAU,KAAK,QAAQ,OAAO,CAAC,SAAS,KAAK,WAAW,EAAE;AAAA,UAC5D,CAAC;AACD,eAAK,UAAU,KAAK,QAAQ,OAAO,CAAC,SAAS,KAAK,WAAW,EAAE;AAAA,QACjE;AAEA,YAAI;AACF,gBAAM,SAAS,MAAM,SAAS,EAAE;AAChC,eAAK;AACL,kBAAQ,MAAM;AAAA,QAChB,SAAS,GAAG;AACV,eAAK;AACL,iBAAO,CAAC;AAAA,QACV;AAAA,MACF,CAAC;AAAA,IACH,CAAC;AAAA,EACH;AAAA,EAEA,UAAU,IAAY;AACpB,UAAM,QAAQ,KAAK,QAAQ,UAAU,CAAC,SAAS,KAAK,OAAO,EAAE;AAC7D,UAAM,SAAS,KAAK,Q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version": "1.0.2",
4
+ "description": "异步逻辑链路追踪",
5
+ "repository": "git@github.com:aomex/aomex.git",
6
+ "homepage": "https://aomex.js.org",
7
+ "license": "MIT",
8
+ "type": "module",
9
+ "sideEffects": false,
10
+ "types": "dist/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.js"
15
+ },
16
+ "./package.json": "./package.json"
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "LICENSE",
21
+ "package.json",
22
+ "README.md",
23
+ "CHANGELOG.md"
24
+ ],
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "peerDependencies": {
29
+ "@aomex/core": "^1.0.0"
30
+ },
31
+ "devDependencies": {
32
+ "@aomex/core": "^1.0.2"
33
+ },
34
+ "scripts": {}
35
+ }