ForcePilot/backend/package/yuxi/utils/trace_context.py
Kris 2c190b2a5c refactor(utils): 统一敏感字段脱敏逻辑,新增trace_id上下文工具
1.  新增请求级trace_id上下文共享模块,通过ContextVar存储trace_id供跨层使用
2.  重构gRPC和SOAP执行器的脱敏逻辑,统一使用crypto模块的敏感头集合
3.  扩展crypto模块的敏感字段匹配规则,新增全量遮蔽的强敏感字段类型
4.  新增mask_full和mask_partial两种脱敏模式,完善脱敏工具链
5.  定义SENSITIVE_HTTP_HEADERS作为HTTP敏感头的单一事实源
2026-07-01 19:48:25 +08:00

41 lines
1.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""请求级 trace_id 上下文(共享模块)。
通过 ContextVar 存储每个请求的 trace_id供异常处理器、日志适配器
等跨层读取。中间件入口生成(或从 X-Request-Id header 读取)。
本模块为 server 层与 channels 层共享的 trace_id 机制,确保两套
ContextVarserver 层 ``_trace_id_var`` 与 channels 层 ``_current_span``
保持同步。
"""
from __future__ import annotations
import uuid
from contextvars import ContextVar
_trace_id_var: ContextVar[str | None] = ContextVar(
"yuxi_request_trace_id", default=None
)
def set_trace_id(trace_id: str) -> None:
"""设置当前请求的 trace_id。"""
_trace_id_var.set(trace_id)
def get_trace_id() -> str | None:
"""获取当前请求的 trace_id未设置时返回 None。"""
return _trace_id_var.get()
def generate_trace_id() -> str:
"""生成新的 trace_iduuid4 十六进制)。"""
return uuid.uuid4().hex
def reset_trace_id() -> None:
"""请求结束时重置 trace_id。
ContextVar 在请求结束后自动回收,显式重置作为保险。
"""
_trace_id_var.set(None)