namespace TakeoutSaaS.Shared.Abstractions.Diagnostics;

/// <summary>
/// 轻量级 TraceId/SpanId 上下文，便于跨层访问当前请求的追踪标识。
/// </summary>
public static class TraceContext
{
    private static readonly AsyncLocal<string?> TraceIdHolder = new();
    private static readonly AsyncLocal<string?> SpanIdHolder = new();

    /// <summary>
    /// 当前请求的 TraceId。
    /// </summary>
    public static string? TraceId
    {
        get => TraceIdHolder.Value;
        set => TraceIdHolder.Value = value;
    }

    /// <summary>
    /// 当前请求的 SpanId。
    /// </summary>
    public static string? SpanId
    {
        get => SpanIdHolder.Value;
        set => SpanIdHolder.Value = value;
    }

    /// <summary>
    /// 清理 TraceId，避免 AsyncLocal 污染其它请求。
    /// </summary>
    public static void Clear()
    {
        TraceIdHolder.Value = null;
        SpanIdHolder.Value = null;
    }
}
