1.AI 协作文档体系重构(objections/worklines/contracts+matrix.md) 2.coord 仲裁文档(final-decisions/cross-review/final-rulings/orchestration) 3.各服务 01/02 文档补全 4.共享包初始化(shared-ts/shared-go/hooks/ui-components/ui-tokens) 5.Proto 契约补全 6.004 架构影响地图更新 7.端口分配表 8.设计规格文档
62 lines
1.5 KiB
TypeScript
62 lines
1.5 KiB
TypeScript
import { useCallback, useState } from "react";
|
||
|
||
/**
|
||
* useTraceId - 当前会话 trace_id 管理
|
||
*
|
||
* 用途:OpenTelemetry traceparent 透传,用于日志关联 + 链路追踪。
|
||
* ai13 新增(对齐 project_rules §12 可观测性规范)。
|
||
*
|
||
* @example
|
||
* const { traceId, setTraceId, withTraceId } = useTraceId();
|
||
* setTraceId("abc123");
|
||
* withTraceId(() => fetch("/api/v1/exams", { headers: { "X-Trace-Id": traceId } }));
|
||
*/
|
||
|
||
export interface UseTraceIdReturn {
|
||
/** 当前 trace_id */
|
||
traceId: string | null;
|
||
/** 设置 trace_id(从响应头 X-Trace-Id 获取) */
|
||
setTraceId: (id: string) => void;
|
||
/** 清除 trace_id */
|
||
clear: () => void;
|
||
/**
|
||
* 在 trace_id 上下文中执行回调(自动注入 header)
|
||
* 用于 fetch 包装
|
||
*/
|
||
withTraceId: <T>(
|
||
fn: (headers: Record<string, string>) => Promise<T>,
|
||
) => Promise<T>;
|
||
}
|
||
|
||
export function useTraceId(): UseTraceIdReturn {
|
||
const [traceId, setTraceIdState] = useState<string | null>(null);
|
||
|
||
const setTraceId = useCallback((id: string): void => {
|
||
setTraceIdState(id);
|
||
}, []);
|
||
|
||
const clear = useCallback((): void => {
|
||
setTraceIdState(null);
|
||
}, []);
|
||
|
||
const withTraceId = useCallback(
|
||
async <T>(
|
||
fn: (headers: Record<string, string>) => Promise<T>,
|
||
): Promise<T> => {
|
||
const headers: Record<string, string> = {};
|
||
if (traceId) {
|
||
headers["X-Trace-Id"] = traceId;
|
||
}
|
||
return fn(headers);
|
||
},
|
||
[traceId],
|
||
);
|
||
|
||
return {
|
||
traceId,
|
||
setTraceId,
|
||
clear,
|
||
withTraceId,
|
||
};
|
||
}
|