using System.Collections.Immutable;
using System.Text;
using Dpz.Core.SourceGenerator.Models;

namespace Dpz.Core.SourceGenerator;

/// <summary>
/// 根据缓存元数据生成缓存装饰器源码。
/// </summary>
/// <remarks>
/// 生成的缓存键格式为 <c>{namespace}.{className}:{method}:key1=value1&amp;key2=value2</c>。
/// </remarks>
internal static class CacheDecoratorSourceGenerator
{
    internal static string Generate(ServiceRegistration registration)
    {
        var source = new StringBuilder();
        source.AppendLine("// <auto-generated />");
        source.AppendLine("#nullable enable");
        source.AppendLine();
        source.Append("namespace ");
        source.Append(registration.ImplementationNamespace);
        source.AppendLine(";");
        source.AppendLine();
        source.Append("internal sealed class ");
        source.Append(registration.DecoratorName);
        source.Append("(");
        source.Append(registration.ImplementationType);
        source.Append(" inner, global::ZiggyCreatures.Caching.Fusion.IFusionCache fusionCache) : ");
        source.AppendLine(registration.ServiceType);
        source.AppendLine("{");

        foreach (var property in registration.InterfaceProperties)
        {
            AppendDecoratorProperty(source, property);
        }

        foreach (var @event in registration.InterfaceEvents)
        {
            AppendDecoratorEvent(source, @event);
        }

        foreach (var method in registration.InterfaceMethods)
        {
            AppendDecoratorMethod(source, registration, method);
        }

        source.AppendLine("}");
        return source.ToString();
    }

    private static void AppendDecoratorMethod(
        StringBuilder source,
        ServiceRegistration registration,
        InterfaceMethod method
    )
    {
        var cachedMethod = FindCachedMethod(registration, method);
        var invalidatedMethod = FindInvalidatedMethod(registration, method);

        source.Append("    public ");
        if (cachedMethod.HasValue || invalidatedMethod.HasValue)
        {
            source.Append("async ");
        }

        source.Append(method.ReturnType);
        source.Append(" ");
        source.Append(method.Name);
        source.Append(method.TypeParameterList);
        source.Append("(");
        AppendParameterList(source, method.Parameters);
        source.Append(")");
        source.AppendLine(method.ConstraintClauses);
        source.AppendLine("    {");

        if (cachedMethod.HasValue)
        {
            AppendCachedMethodBody(source, registration, cachedMethod.Value);
        }
        else if (invalidatedMethod.HasValue)
        {
            AppendInvalidatedMethodBody(source, registration, invalidatedMethod.Value);
        }
        else
        {
            source.Append("        return inner.");
            source.Append(method.Name);
            source.Append("(");
            AppendArgumentList(source, method.Parameters);
            source.AppendLine(");");
        }

        source.AppendLine("    }");
        source.AppendLine();
    }

    private static CachedMethod? FindCachedMethod(
        ServiceRegistration registration,
        InterfaceMethod method
    )
    {
        foreach (var cached in registration.CachedMethods)
        {
            if (
                cached.Name == method.Name
                && cached.Parameters.Length == method.Parameters.Length
                && cached
                    .Parameters.Zip(
                        method.Parameters,
                        (left, right) => left.TypeName == right.TypeName
                    )
                    .All(static match => match)
            )
            {
                return cached;
            }
        }

        return null;
    }

    private static InvalidatedMethod? FindInvalidatedMethod(
        ServiceRegistration registration,
        InterfaceMethod method
    )
    {
        foreach (var invalidated in registration.InvalidatedMethods)
        {
            if (
                invalidated.Name == method.Name
                && invalidated.Parameters.Length == method.Parameters.Length
                && invalidated
                    .Parameters.Zip(
                        method.Parameters,
                        (left, right) => left.TypeName == right.TypeName
                    )
                    .All(static match => match)
            )
            {
                return invalidated;
            }
        }

        return null;
    }

    private static void AppendCachedMethodBody(
        StringBuilder source,
        ServiceRegistration registration,
        CachedMethod cachedMethod
    )
    {
        var prefix = cachedMethod.Options.Prefix ?? GetCachePrefix(registration.ImplementationType);
        var cancellationToken = GetCancellationTokenArgument(cachedMethod.Parameters);

        source.Append("        var cacheKey = ");
        AppendGeneratedCacheKeyCall(source, registration, cachedMethod);
        source.AppendLine(";");
        // IPagedList<T> is an interface and does not round-trip through FusionCache serializers
        // reliably, so generated decorators cache the serializable PagedListWarp<T> DTO instead.
        if (TryGetPagedListValueType(cachedMethod.ValueType, out var pagedListItemType))
        {
            source.AppendLine("        var cached = await fusionCache.GetOrSetAsync<");
            source.Append("            global::Dpz.Core.Web.Pager.PagedListWarp<");
            source.Append(pagedListItemType);
            source.AppendLine(">>(");
            source.AppendLine("            cacheKey,");
            source.AppendLine("            async (context, factoryCancellationToken) =>");
            source.AppendLine("            {");
            AppendGeneratedCacheTags(source, registration, prefix, cachedMethod);
            source.Append("                var pagedList = await inner.");
            source.Append(cachedMethod.Name);
            source.Append("(");
            AppendArgumentList(source, cachedMethod.Parameters);
            source.AppendLine(");");
            source.AppendLine("                return pagedList.ToPagedListWarp();");
            source.AppendLine("            },");
            AppendCacheEntryOptions(source, cachedMethod);
            source.AppendLine(",");
            source.Append("            token: ");
            source.Append(cancellationToken);
            source.AppendLine();
            source.AppendLine("        );");
            source.AppendLine("        var result = cached.ToPagedList();");
            AppendPostProcessCall(source, cachedMethod, "result");
            source.AppendLine("        return result;");
            return;
        }

        source.AppendLine("        var result = await fusionCache.GetOrSetAsync<");
        source.Append("            ");
        source.Append(cachedMethod.ValueType);
        source.AppendLine(">(");
        source.AppendLine("            cacheKey,");
        source.AppendLine("            async (context, factoryCancellationToken) =>");
        source.AppendLine("            {");
        AppendGeneratedCacheTags(source, registration, prefix, cachedMethod);
        source.Append("                return await inner.");
        source.Append(cachedMethod.Name);
        source.Append("(");
        AppendArgumentList(source, cachedMethod.Parameters);
        source.AppendLine(");");
        source.AppendLine("            },");
        AppendCacheEntryOptions(source, cachedMethod);
        source.AppendLine(",");
        source.Append("            token: ");
        source.Append(cancellationToken);
        source.AppendLine();
        source.AppendLine("        );");
        AppendPostProcessCall(source, cachedMethod, "result");
        source.AppendLine("        return result;");
    }

    private static void AppendCacheEntryOptions(StringBuilder source, CachedMethod cachedMethod)
    {
        var options = cachedMethod.Options;
        source.Append(
            "            options => options.SetDuration(global::System.TimeSpan.FromSeconds("
        );
        source.Append(options.ExpirationSeconds);
        source.Append("))");

        AppendFailSafeOptions(source, options);
        AppendFactoryTimeoutOptions(source, options.Resilience);
        AppendDistributedCacheTimeoutOptions(source, options.Resilience);
    }

    private static void AppendFailSafeOptions(StringBuilder source, CacheOptions options)
    {
        var resilience = options.Resilience;
        if (!resilience.FailSafe)
        {
            // 保持历史行为:显式设置过期时间时关闭故障安全。
            if (options.HasExplicitExpirationSeconds)
            {
                source.Append(".SetFailSafe(false)");
            }

            return;
        }

        source.Append(".SetFailSafe(true");
        if (resilience.FailSafeMaxDurationSeconds > 0)
        {
            source.Append(", ");
            AppendTimeSpan(source, resilience.FailSafeMaxDurationSeconds);
        }
        else if (resilience.FailSafeThrottleDurationSeconds > 0)
        {
            source.Append(", null");
        }

        if (resilience.FailSafeThrottleDurationSeconds > 0)
        {
            source.Append(", ");
            AppendTimeSpan(source, resilience.FailSafeThrottleDurationSeconds);
        }

        source.Append(")");
    }

    private static void AppendFactoryTimeoutOptions(
        StringBuilder source,
        CacheResilienceOptions resilience
    )
    {
        if (resilience.FactorySoftTimeoutSeconds <= 0 && resilience.FactoryHardTimeoutSeconds <= 0)
        {
            return;
        }

        source.Append(".SetFactoryTimeouts(");
        AppendTimeSpanOrDefault(source, resilience.FactorySoftTimeoutSeconds);
        source.Append(", ");
        AppendTimeSpanOrDefault(source, resilience.FactoryHardTimeoutSeconds);
        source.Append(", ");
        source.Append(resilience.AllowTimedOutFactoryBackgroundCompletion ? "true" : "false");
        source.Append(")");
    }

    private static void AppendDistributedCacheTimeoutOptions(
        StringBuilder source,
        CacheResilienceOptions resilience
    )
    {
        if (
            resilience.DistributedCacheSoftTimeoutSeconds <= 0
            && resilience.DistributedCacheHardTimeoutSeconds <= 0
        )
        {
            return;
        }

        source.Append(".SetDistributedCacheTimeouts(");
        AppendTimeSpanOrDefault(source, resilience.DistributedCacheSoftTimeoutSeconds);
        source.Append(", ");
        AppendTimeSpanOrDefault(source, resilience.DistributedCacheHardTimeoutSeconds);
        source.Append(")");
    }

    private static void AppendTimeSpanOrDefault(StringBuilder source, int seconds)
    {
        if (seconds <= 0)
        {
            source.Append("null");
            return;
        }

        AppendTimeSpan(source, seconds);
    }

    private static void AppendTimeSpan(StringBuilder source, int seconds)
    {
        source.Append("global::System.TimeSpan.FromSeconds(");
        source.Append(seconds);
        source.Append(")");
    }

    private static void AppendInvalidatedMethodBody(
        StringBuilder source,
        ServiceRegistration registration,
        InvalidatedMethod invalidatedMethod
    )
    {
        var cancellationToken = GetCancellationTokenArgument(invalidatedMethod.Parameters);
        if (IsGenericAwaitable(invalidatedMethod.ReturnType))
        {
            source.Append("        var result = await inner.");
            source.Append(invalidatedMethod.Name);
            source.Append("(");
            AppendArgumentList(source, invalidatedMethod.Parameters);
            source.AppendLine(");");
            AppendRemoveInvalidatedCaches(
                source,
                registration,
                invalidatedMethod,
                cancellationToken
            );
            source.AppendLine("        return result;");
            return;
        }

        source.Append("        await inner.");
        source.Append(invalidatedMethod.Name);
        source.Append("(");
        AppendArgumentList(source, invalidatedMethod.Parameters);
        source.AppendLine(");");
        AppendRemoveInvalidatedCaches(source, registration, invalidatedMethod, cancellationToken);
    }

    private static bool IsGenericAwaitable(string returnType)
    {
        return returnType.StartsWith(
                "global::System.Threading.Tasks.Task<",
                StringComparison.Ordinal
            )
            || returnType.StartsWith(
                "global::System.Threading.Tasks.ValueTask<",
                StringComparison.Ordinal
            );
    }

    private static void AppendRemoveMethodTags(
        StringBuilder source,
        ServiceRegistration registration,
        InvalidatedMethod invalidatedMethod,
        string cancellationToken
    )
    {
        source.Append("        await fusionCache.RemoveByTagAsync(new[] { ");
        for (var i = 0; i < invalidatedMethod.Methods.Length; i++)
        {
            if (i > 0)
            {
                source.Append(", ");
            }

            source.Append(registration.CacheMetadataName);
            source.Append(".");
            source.Append(invalidatedMethod.Methods[i]);
            source.Append("MethodTag");
        }

        source.Append(" }, token: ");
        source.Append(cancellationToken);
        source.AppendLine(");");
    }

    private static void AppendRemoveInvalidatedCaches(
        StringBuilder source,
        ServiceRegistration registration,
        InvalidatedMethod invalidatedMethod,
        string cancellationToken
    )
    {
        AppendRemoveMethodTags(source, registration, invalidatedMethod, cancellationToken);
        AppendRemoveDeterministicMethodKeys(
            source,
            registration,
            invalidatedMethod,
            cancellationToken
        );
    }

    private static void AppendRemoveDeterministicMethodKeys(
        StringBuilder source,
        ServiceRegistration registration,
        InvalidatedMethod invalidatedMethod,
        string cancellationToken
    )
    {
        foreach (var methodName in invalidatedMethod.Methods)
        {
            var cachedMethod = registration.CachedMethods.FirstOrDefault(method =>
                method.Name == methodName
            );
            if (cachedMethod.Name is null || !CanBuildDeterministicCacheKey(cachedMethod))
            {
                continue;
            }

            source.Append("        await fusionCache.RemoveAsync(");
            AppendGeneratedCacheKeyCall(source, registration, cachedMethod);
            source.Append(", token: ");
            source.Append(cancellationToken);
            source.AppendLine(");");
        }
    }

    private static bool CanBuildDeterministicCacheKey(CachedMethod method)
    {
        return !string.IsNullOrWhiteSpace(method.Options.CacheKey)
            || method.Parameters.All(parameter =>
                parameter.TypeName == "global::System.Threading.CancellationToken"
            );
    }

    private static void AppendDecoratorProperty(StringBuilder source, InterfaceProperty property)
    {
        source.Append("    public ");
        source.Append(property.TypeName);
        source.Append(" ");
        source.Append(property.Name);
        source.AppendLine();
        source.AppendLine("    {");

        if (property.HasGetter)
        {
            source.Append("        get => inner.");
            source.Append(property.Name);
            source.AppendLine(";");
        }

        if (property.HasSetter)
        {
            source.Append("        set => inner.");
            source.Append(property.Name);
            source.AppendLine(" = value;");
        }

        source.AppendLine("    }");
        source.AppendLine();
    }

    private static void AppendDecoratorEvent(StringBuilder source, InterfaceEvent @event)
    {
        source.Append("    public event ");
        source.Append(@event.TypeName);
        source.Append(" ");
        source.Append(@event.Name);
        source.AppendLine();
        source.AppendLine("    {");
        source.Append("        add => inner.");
        source.Append(@event.Name);
        source.AppendLine(" += value;");
        source.Append("        remove => inner.");
        source.Append(@event.Name);
        source.AppendLine(" -= value;");
        source.AppendLine("    }");
        source.AppendLine();
    }

    private static void AppendParameterList(
        StringBuilder source,
        ImmutableArray<CachedParameter> parameters
    )
    {
        for (var i = 0; i < parameters.Length; i++)
        {
            if (i > 0)
            {
                source.Append(", ");
            }

            if (parameters[i].IsParams)
            {
                source.Append("params ");
            }

            AppendRefKind(source, parameters[i].RefKind);
            source.Append(parameters[i].TypeName);
            source.Append(" ");
            source.Append(parameters[i].Name);
            source.Append(parameters[i].DefaultValueLiteral);
        }
    }

    private static void AppendArgumentList(
        StringBuilder source,
        ImmutableArray<CachedParameter> parameters
    )
    {
        for (var i = 0; i < parameters.Length; i++)
        {
            if (i > 0)
            {
                source.Append(", ");
            }

            AppendRefKind(source, parameters[i].RefKind);
            source.Append(parameters[i].Name);
        }
    }

    private static void AppendRefKind(StringBuilder source, Microsoft.CodeAnalysis.RefKind refKind)
    {
        switch (refKind)
        {
            case Microsoft.CodeAnalysis.RefKind.Ref:
                source.Append("ref ");
                break;
            case Microsoft.CodeAnalysis.RefKind.Out:
                source.Append("out ");
                break;
            case Microsoft.CodeAnalysis.RefKind.In:
                source.Append("in ");
                break;
        }
    }

    private static string GetCancellationTokenArgument(ImmutableArray<CachedParameter> parameters)
    {
        foreach (var parameter in parameters)
        {
            if (parameter.TypeName == "global::System.Threading.CancellationToken")
            {
                return parameter.Name;
            }
        }

        return "default";
    }

    private static void AppendGeneratedCacheKeyCall(
        StringBuilder source,
        ServiceRegistration registration,
        CachedMethod method
    )
    {
        source.Append(registration.CacheMetadataName);
        source.Append(".Build");
        source.Append(method.Name);
        source.Append("CacheKey(");
        AppendCacheKeyArgumentList(source, method);
        source.Append(")");
    }

    private static bool TryGetPagedListValueType(string valueType, out string itemType)
    {
        const string pagedListPrefix = "global::Dpz.Core.Web.Pager.IPagedList<";
        itemType = string.Empty;
        if (!valueType.StartsWith(pagedListPrefix, StringComparison.Ordinal))
        {
            return false;
        }

        itemType = valueType.Substring(
            pagedListPrefix.Length,
            valueType.Length - pagedListPrefix.Length - 1
        );
        return true;
    }

    private static void AppendCacheKeyArgumentList(StringBuilder source, CachedMethod method)
    {
        if (!string.IsNullOrWhiteSpace(method.Options.CacheKey))
        {
            return;
        }

        var parameters = method
            .Parameters.Where(parameter =>
                parameter.TypeName != "global::System.Threading.CancellationToken"
            )
            .ToList();

        for (var i = 0; i < parameters.Count; i++)
        {
            if (i > 0)
            {
                source.Append(", ");
            }

            source.Append(parameters[i].Name);
        }
    }

    private static void AppendGeneratedCacheTags(
        StringBuilder source,
        ServiceRegistration registration,
        string prefix,
        CachedMethod cachedMethod
    )
    {
        source.Append("                context.Tags = new[] { ");
        source.Append(ToCSharpStringLiteral(prefix));
        source.Append(", ");
        source.Append(registration.CacheMetadataName);
        source.Append(".");
        source.Append(cachedMethod.Name);
        source.Append("MethodTag");
        foreach (var tag in cachedMethod.Options.AdditionalTags)
        {
            source.Append(", ");
            source.Append(ToCSharpStringLiteral(tag));
        }
        source.AppendLine(" };");
    }

    private static void AppendPostProcessCall(
        StringBuilder source,
        CachedMethod cachedMethod,
        string valueExpression
    )
    {
        if (string.IsNullOrWhiteSpace(cachedMethod.Options.PostProcess))
        {
            return;
        }

        source.Append("        await inner.");
        source.Append(cachedMethod.Options.PostProcess);
        source.Append("(");
        source.Append(valueExpression);
        source.AppendLine(");");
    }

    private static string ToCSharpStringLiteral(string value)
    {
        return "\"" + value.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"";
    }

    private static string GetCachePrefix(string fullyQualifiedTypeName)
    {
        return fullyQualifiedTypeName.Replace("global::", string.Empty);
    }
}
⚠⚠    以下内容为AI分析的结果,请根据实际情况进行判断。

CacheDecoratorSourceGenerator.cs 技术档案

一句话定位

编译期源码拼接器:拿到一个 ServiceRegistration(接口 + 实现类 + 已解析的 [Cache]/[InvalidateCache] 元数据),用 StringBuilder 逐行拼出一个 internal sealed 的缓存装饰器类 GeneratedCached{ImplementationName},由 ServiceRegistrationGenerator.cs 以 AddSource(registration.DecoratorHintName, ...) 输出。它只负责“把已算好的元数据翻译成 C# 文本”,不做任何符号分析。

关键方法与行为

Generate:固定模板 —— // <auto-generated /> + #nullable enable + namespace {ImplementationNamespace}; + 类声明。 类使用 C# 12 主构造函数:(实现类 inner, global::ZiggyCreatures.Caching.Fusion.IFusionCache fusionCache) : 接口。之所以能这样写,是因为 ServiceRegistrationSourceBuilder.cs 会先把具体实现类按同生命周期单独注册一次,装饰器才能构造注入 inner。生成物放在实现类同一命名空间下,因此引用 Generated{...}CacheMetadata 时无需限定名。

方法三分支(AppendDecoratorMethod):

  • 命中 CachedMethods(按方法名 + 参数类型名逐项比对,FindCachedMethod)→ 加 async,包一层 fusionCache.GetOrSetAsync<TValue>;
  • 否则命中 InvalidatedMethods → 加 async,先 await inner.X(...),成功后清缓存;
  • 都不命中 → 原样转发 return inner.X(args);,不加 async。

缓存体生成(AppendCachedMethodBody):cacheKey 由 metadata 类的 Build{Method}CacheKey(...) 生成(参数列表剔除 CancellationToken,显式 CacheKey 时为空参);工厂内先写 context.Tags,再调 inner。标签固定是“前缀 + {Method}MethodTag + AdditionalTags”。最后按需追加一次 PostProcess 调用(await inner.{PostProcess}(result)),每次调用都执行,包括缓存命中,属于刻意的“缓存基础数据 + 运行时叠加动态字段”设计。

选项链生成(AppendCacheEntryOptions / AppendFailSafeOptions 等):SetDuration(...) 之后按需串 .SetFailSafe(...)、.SetFactoryTimeouts(...)、.SetDistributedCacheTimeouts(...)。这里有一处刻意保留的历史语义:没有显式 FailSafe = true 但显式设了 ExpirationSeconds 时,生成 .SetFailSafe(false),即默认关闭故障安全,让逻辑过期必须等工厂返回。

失效体生成(AppendInvalidatedMethodBody):用 IsGenericAwaitable(字符串 StartsWith 判断 Task< / ValueTask<)决定是否需要暂存返回值。清理动作是两步:RemoveByTagAsync(new[]{ ...MethodTag }),再对“能构造确定性键”的被缓存方法逐个 RemoveAsync(BuildXxxCacheKey(...))。CanBuildDeterministicCacheKey 的判定条件是“显式 CacheKey”或“参数全是 CancellationToken”——也就是说,只有无参/纯取消令牌的方法才做按键删除。

IPagedList<T> 特判(TryGetPagedListValueType):对 global::Dpz.Core.Web.Pager.IPagedList<T> 前缀做字符串匹配,把缓存载荷换成可序列化的 PagedListWarp<T>(工厂内 pagedList.ToPagedListWarp(),取出后 cached.ToPagedList())。替代类型是硬编码的 PagedListWarp.cs,ToPagedList() 返回 PagedList.cs 的 PagedList<T> 实例。

成员转发:属性统一写成 get => inner.X; set => inner.X = value;,事件写成 add/remove 转发。签名重建支持 params、ref/out/in、默认值字面量和泛型约束(约束文本来自 InterfaceContractInspector.cs)。

依赖与协作

运行时时序(生成物行为)

sequenceDiagram
    participant Caller as 调用方
    participant D as GeneratedCachedXxx
    participant FC as IFusionCache
    participant Inner as 实现类 inner

    Caller->>D: 接口方法(参数, ct)
    D->>D: cacheKey = BuildXxxCacheKey(非 ct 参数)
    D->>FC: GetOrSetAsync<T>(cacheKey, factory, options, token: ct)

    alt 缓存命中
        FC-->>D: 缓存值
    else 未命中或过期
        FC->>Inner: factory: inner.Xxx(参数...)
        Inner-->>FC: Task<T>
        FC->>FC: 写入并打 tags(前缀 / MethodTag / AdditionalTags)
        FC-->>D: 新值
    end

    opt 配置了 PostProcess
        D->>Inner: await inner.PostProcess(result)
    end
    D-->>Caller: result

失效方法则是“先执行写操作,再 RemoveByTagAsync(+ 命中时 RemoveAsync 确定性键)”,全部使用调用方传入的 CancellationToken。

需要注意的点

  • 前缀计算有两份独立实现:本文件 GetCachePrefix 与 CacheMetadataSourceGenerator.cs 内的同名私有方法各自算一次,装饰器把前缀写成字面量、metadata 写成常量。任何一侧的前缀规则变更(例如加版本号)都会让 tag 与 key 悄悄错位。ToCSharpStringLiteral 也是与 SymbolDisplay.cs 完全重复的一份;且两者都只转义 \ 和 ",AdditionalTags 里若有换行会生成非法源码。
  • 确定性键删除与 tag 删除重复:所有被缓存方法的工厂都会写 {Method}MethodTag,RemoveByTagAsync 已经能覆盖这些条目,之后的 RemoveAsync 是同一次失效里的冗余往返;README.md 里“失效生成代码只调用 RemoveByTagAsync”的描述也已与现状不符。
  • 成对方法名匹配过粗:AppendRemoveDeterministicMethodKeys 用 CachedMethods.FirstOrDefault(m => m.Name == methodName) 定位,同名重载时只看第一个;若第一个恰好是带普通参数的重载,CanBuildDeterministicCacheKey 为假,本可确定性删除的那个重载就被跳过,失效逻辑静默降级为只删 tag。
  • FindCachedMethod / FindInvalidatedMethod 只比对名字与参数类型字符串,不比较类型参数个数,泛型重载存在错配可能;而 CacheMethodInspector 也并未禁止 [Cache] 标在泛型方法上——缓存键里不含类型参数,不同 T 会命中同一个 key。这条风险不在本文件内闭合,但在本文件的键生成逻辑里体现。
  • IPagedList<T> 判定是字符串前缀 + 末尾字符裁剪,只对 global::...IPagedList<T> 这种“以 > 结尾”的形式成立。若返回值写成 Task<IPagedList<T>?>(SymbolDisplay 会保留 nullable 标记),裁剪会削掉 ? 而不是 >,生成 PagedListWarp<T>> 这类非法代码,而且没有任何诊断兜底。此外缓存命中后返回的运行时类型被固定成 PagedList<T>,不再是最初服务返回的具体分页类型。
  • 工厂丢弃了 factoryCancellationToken:lambda 形参声明了却未使用,内部把调用方 cancellationToken 传给 inner,GetOrSetAsync 又用同一个 token: 参数。调用方取消时,AllowTimedOutFactoryBackgroundCompletion 想要的后台完成也会被连带取消;同样地,失效路径用调用方 token 调 RemoveByTagAsync,请求取消就意味着“写成功但缓存没清”。
  • 显式 ExpirationSeconds 会隐式关闭 fail-safe(SetFailSafe(false)),只有 FailSafe = true 才显式打开。这是刻意保留的兼容行为,但对中间件/限流这类热路径来说是容易踩的性能坑,改动时需要连同语义一起考虑。
  • 同时标注 [Cache] 和 [InvalidateCache] 的方法会走缓存分支(else if 的次序决定),失效逻辑不执行也不报警。
  • 属性转发只判断 SetMethod is not null,接口里的 init 属性会生成非法的 set => ...;InterfaceContractInspector.GetMembers 对继承成员不做签名去重,若某接口从两个父接口继承了同名同签名方法,装饰器会重复声明同一方法。
  • 生成类为 internal sealed,且命名固定 GeneratedCached{ImplName}:实现类同命名空间内若已有同名类型(或两个同短名的实现类落进同一命名空间),会直接编译冲突,本文件不做任何唯一性检查。
评论加载中...