refactor(tracer-context): 改进 scope 状态管理以支持嵌套检测

- 引入 SCOPE_STATE 枚举明确区分初始、执行中和已完成状态
- 将 scoping 布尔标志替换为 state 枚举,支持检测嵌套调用
- 分离同步和异步错误处理流程,确保状态正确更新
- 修复 flush 方法中 commands 和 error 的清理逻辑
This commit is contained in:
2026-02-23 02:05:58 +08:00
parent 8894458f4c
commit 134d4e2b19

View File

@@ -1,5 +1,13 @@
import type { TracerCommand } from '../types';
const SCOPE_STATE = {
INITIAL: 'initial',
SCOPING: 'scoping',
SCOPED: 'scoped',
} as const;
type ScopeState = (typeof SCOPE_STATE)[keyof typeof SCOPE_STATE];
type Error = {
stack?: string;
};
@@ -9,15 +17,15 @@ type ScopeResult = {
commands: TracerCommand[];
// 记录错误信息
error: Error;
// 检查是否多次调用scope
scoping: boolean;
// 检查scope的执行状态
state: ScopeState;
};
const createTracerContext = () => {
const scopeResult: ScopeResult = {
commands: [],
error: {},
scoping: false,
state: SCOPE_STATE.INITIAL,
};
const command = (command: TracerCommand) => {
@@ -26,11 +34,15 @@ const createTracerContext = () => {
// TODO: 输出指令序列和错误信息
const flush = () => {
console.log('输出指令序列');
const { commands, error } = scopeResult;
// if (commands.length > 0 || !!error.stack) {
// console.log('输出指令序列');
// console.log(JSON.stringify({ commands, error }, null, 2));
// }
console.log('输出指令序列');
console.log(JSON.stringify({ commands, error }, null, 2));
scopeResult.commands.length = 0;
scopeResult.error.stack = undefined;
scopeResult.commands = [];
scopeResult.error = {};
};
const getTracerContext = () => {
@@ -40,27 +52,39 @@ const createTracerContext = () => {
};
};
const scope = (routine: () => void | PromiseLike<void>) => {
if (scopeResult.scoping) {
const scope = (routine: () => void | Promise<void>) => {
if (scopeResult.state === SCOPE_STATE.SCOPED) {
console.error('多次调用scope方法');
throw new Error('[TracerContext] Detect multiple scope.');
}
scopeResult.scoping = true;
if (scopeResult.state === SCOPE_STATE.SCOPING) {
console.error('嵌套调用scope方法');
throw new Error('[TracerContext] Detect nested scope.');
}
scopeResult.state = SCOPE_STATE.SCOPING;
// 如果routine是同步函数那可能会抛出同步错误所以需要用try-catch包裹
try {
const promise = Promise.resolve(routine());
promise
.catch((err) => {
console.log('异步错误');
console.error(err);
scopeResult.error.stack = (err as Error).stack;
})
.finally(() => {
flush();
});
const result = routine();
if (result instanceof Promise) {
result
.catch((err) => {
console.log('异步错误');
console.error(err);
scopeResult.error.stack = (err as Error).stack;
})
.finally(() => {
scopeResult.state = SCOPE_STATE.SCOPED;
flush();
});
} else {
scopeResult.state = SCOPE_STATE.SCOPED;
flush();
}
} catch (err) {
console.log('同步错误');
console.error(err);
scopeResult.error.stack = (err as Error).stack;
scopeResult.state = SCOPE_STATE.SCOPED;
flush();
}
};