using System.Collections.Immutable;
using Dpz.Core.SourceGenerator.Models;
using Microsoft.CodeAnalysis;
namespace Dpz.Core.SourceGenerator;
/// <summary>
/// 从服务实现方法上读取缓存特性,并转换为缓存装饰器生成所需的元数据。
/// </summary>
/// <remarks>
/// 缓存属于实现策略,因此这里只读取实现类方法上的 <c>CacheAttribute</c>,
/// 不读取接口方法上的同名特性。
/// </remarks>
internal static class CacheMethodInspector
{
#pragma warning disable RS2008
private static readonly DiagnosticDescriptor UnsupportedCacheMethodDescriptor = new(
"DPZ_CACHE001",
"Unsupported cacheable service method",
"Cannot generate cache decorator for '{0}.{1}': {2}",
"Dpz.Core.Cache",
DiagnosticSeverity.Error,
true
);
private static readonly DiagnosticDescriptor InvalidPostProcessDescriptor = new(
"DPZ_CACHE003",
"Invalid cache post-process method",
"Cannot generate cache decorator for '{0}.{1}': {2}",
"Dpz.Core.Cache",
DiagnosticSeverity.Error,
true
);
private static readonly DiagnosticDescriptor InvalidInvalidateCacheDescriptor = new(
"DPZ_CACHE004",
"Invalid cache invalidation method",
"Cannot generate cache invalidation for '{0}.{1}': {2}",
"Dpz.Core.Cache",
DiagnosticSeverity.Error,
true
);
#pragma warning restore RS2008
internal static ImmutableArray<CachedMethod> GetCachedMethods(
INamedTypeSymbol interfaceType,
INamedTypeSymbol implementationType,
SourceProductionContext sourceProductionContext
)
{
var methods = ImmutableArray.CreateBuilder<CachedMethod>();
var interfaceMethods = GetInterfaceMethods(interfaceType);
foreach (var implementationMethod in GetCacheAttributedMethods(implementationType))
{
var attribute = GetAttribute(
implementationMethod,
SourceGeneratorAttributeNames.CacheAttributeFullName
);
var interfaceMethod = FindInterfaceMethod(
implementationType,
interfaceMethods,
implementationMethod
);
if (interfaceMethod is null)
{
sourceProductionContext.ReportDiagnostic(
Diagnostic.Create(
UnsupportedCacheMethodDescriptor,
implementationMethod.Locations.FirstOrDefault(),
implementationType.ToDisplayString(),
implementationMethod.Name,
"method is not part of the registered service interface"
)
);
continue;
}
if (
!TryCreateCachedMethod(
interfaceMethod,
implementationType,
attribute!,
out var cachedMethod,
out var message
)
)
{
sourceProductionContext.ReportDiagnostic(
Diagnostic.Create(
message.StartsWith("post-process", StringComparison.Ordinal)
? InvalidPostProcessDescriptor
: UnsupportedCacheMethodDescriptor,
implementationMethod?.Locations.FirstOrDefault()
?? interfaceMethod.Locations.FirstOrDefault(),
interfaceType.ToDisplayString(),
interfaceMethod.Name,
message
)
);
continue;
}
methods.Add(cachedMethod);
}
return methods.ToImmutable();
}
internal static ImmutableArray<InvalidatedMethod> GetInvalidatedMethods(
INamedTypeSymbol interfaceType,
INamedTypeSymbol implementationType,
ImmutableArray<CachedMethod> cachedMethods,
SourceProductionContext sourceProductionContext
)
{
var methods = ImmutableArray.CreateBuilder<InvalidatedMethod>();
var interfaceMethods = GetInterfaceMethods(interfaceType);
var cachedMethodNames = new HashSet<string>(
cachedMethods.Select(static method => method.Name)
);
foreach (var implementationMethod in GetInvalidateAttributedMethods(implementationType))
{
var attribute = GetAttribute(
implementationMethod,
SourceGeneratorAttributeNames.InvalidateCacheAttributeFullName
);
var interfaceMethod = FindInterfaceMethod(
implementationType,
interfaceMethods,
implementationMethod
);
if (interfaceMethod is null)
{
sourceProductionContext.ReportDiagnostic(
Diagnostic.Create(
InvalidInvalidateCacheDescriptor,
implementationMethod.Locations.FirstOrDefault(),
implementationType.ToDisplayString(),
implementationMethod.Name,
"method is not part of the registered service interface"
)
);
continue;
}
if (
!TryCreateInvalidatedMethod(
interfaceMethod,
attribute!,
cachedMethodNames,
out var invalidatedMethod,
out var message
)
)
{
sourceProductionContext.ReportDiagnostic(
Diagnostic.Create(
InvalidInvalidateCacheDescriptor,
implementationMethod.Locations.FirstOrDefault(),
interfaceType.ToDisplayString(),
interfaceMethod.Name,
message
)
);
continue;
}
methods.Add(invalidatedMethod);
}
return methods.ToImmutable();
}
private static ImmutableArray<IMethodSymbol> GetInterfaceMethods(INamedTypeSymbol interfaceType)
{
return
[
.. interfaceType
.AllInterfaces.SelectMany(type => type.GetMembers())
.Concat(interfaceType.GetMembers())
.OfType<IMethodSymbol>()
.Where(method => method.MethodKind == MethodKind.Ordinary),
];
}
private static ImmutableArray<IMethodSymbol> GetCacheAttributedMethods(
INamedTypeSymbol implementationType
)
{
return
[
.. implementationType
.GetMembers()
.OfType<IMethodSymbol>()
.Where(method =>
method.MethodKind == MethodKind.Ordinary
&& GetAttribute(method, SourceGeneratorAttributeNames.CacheAttributeFullName)
is not null
),
];
}
private static ImmutableArray<IMethodSymbol> GetInvalidateAttributedMethods(
INamedTypeSymbol implementationType
)
{
return
[
.. implementationType
.GetMembers()
.OfType<IMethodSymbol>()
.Where(method =>
method.MethodKind == MethodKind.Ordinary
&& GetAttribute(
method,
SourceGeneratorAttributeNames.InvalidateCacheAttributeFullName
)
is not null
),
];
}
private static IMethodSymbol? FindInterfaceMethod(
INamedTypeSymbol implementationType,
ImmutableArray<IMethodSymbol> interfaceMethods,
IMethodSymbol implementationMethod
)
{
foreach (var interfaceMethod in interfaceMethods)
{
var mappedMethod = implementationType.FindImplementationForInterfaceMember(
interfaceMethod
);
if (
mappedMethod is IMethodSymbol method
&& SymbolEqualityComparer.Default.Equals(method, implementationMethod)
)
{
return interfaceMethod;
}
if (HasSameSignature(interfaceMethod, implementationMethod))
{
return interfaceMethod;
}
}
return null;
}
private static bool HasSameSignature(
IMethodSymbol interfaceMethod,
IMethodSymbol implementationMethod
)
{
return implementationMethod.Name == interfaceMethod.Name
&& implementationMethod.TypeParameters.Length == interfaceMethod.TypeParameters.Length
&& implementationMethod.Parameters.Length == interfaceMethod.Parameters.Length
&& implementationMethod
.Parameters.Zip(
interfaceMethod.Parameters,
(left, right) =>
left.RefKind == right.RefKind
&& SymbolEqualityComparer.Default.Equals(left.Type, right.Type)
)
.All(static match => match);
}
private static bool TryCreateCachedMethod(
IMethodSymbol method,
INamedTypeSymbol implementationType,
AttributeData attribute,
out CachedMethod cachedMethod,
out string message
)
{
cachedMethod = default;
message = string.Empty;
if (!IsTaskOfT(method.ReturnType, out var valueType))
{
message = "only Task<T> return types are supported";
return false;
}
var cacheOptions = GetCacheOptions(attribute);
if (cacheOptions.ExpirationSeconds <= 0)
{
message = "ExpirationSeconds must be greater than 0";
return false;
}
var resilienceMessage = cacheOptions.Resilience.Validate(cacheOptions.ExpirationSeconds);
if (resilienceMessage is not null)
{
message = resilienceMessage;
return false;
}
var parameters = ImmutableArray.CreateBuilder<CachedParameter>();
foreach (var parameter in method.Parameters)
{
if (parameter.RefKind != RefKind.None)
{
message = $"parameter '{parameter.Name}' uses unsupported ref kind";
return false;
}
if (
!TryCreateCachedParameter(
parameter,
cacheOptions.CacheKey is not null,
out var cachedParameter,
out message
)
)
{
return false;
}
parameters.Add(cachedParameter);
}
if (
!string.IsNullOrWhiteSpace(cacheOptions.PostProcess)
&& !HasValidPostProcessMethod(
implementationType,
cacheOptions.PostProcess!,
valueType,
out message
)
)
{
return false;
}
cachedMethod = new CachedMethod(
method.Name,
SymbolDisplay.ToFullyQualifiedTypeName(method.ReturnType),
SymbolDisplay.ToFullyQualifiedTypeName(valueType),
parameters.ToImmutable(),
cacheOptions
);
return true;
}
private static bool TryCreateInvalidatedMethod(
IMethodSymbol method,
AttributeData attribute,
HashSet<string> cachedMethodNames,
out InvalidatedMethod invalidatedMethod,
out string message
)
{
invalidatedMethod = default;
message = string.Empty;
if (!IsAwaitableServiceMethod(method.ReturnType))
{
message = "only Task, Task<T>, ValueTask and ValueTask<T> return types are supported";
return false;
}
var methods = ImmutableArray.CreateBuilder<string>();
foreach (var namedArgument in attribute.NamedArguments)
{
if (
namedArgument.Key != "Methods"
|| namedArgument.Value.Kind != TypedConstantKind.Array
)
{
continue;
}
foreach (var value in namedArgument.Value.Values)
{
if (value.Value is string methodName && !string.IsNullOrWhiteSpace(methodName))
{
methods.Add(methodName);
}
}
}
if (methods.Count == 0)
{
message = "Methods must contain at least one cached method name";
return false;
}
foreach (var methodName in methods)
{
if (!cachedMethodNames.Contains(methodName))
{
message =
$"method '{methodName}' is not a cacheable method on the same implementation";
return false;
}
}
invalidatedMethod = new InvalidatedMethod(
method.Name,
SymbolDisplay.ToFullyQualifiedTypeName(method.ReturnType),
[
.. method.Parameters.Select(parameter => new CachedParameter(
parameter.Name,
SymbolDisplay.ToFullyQualifiedTypeName(parameter.Type),
parameter.RefKind,
parameter.HasExplicitDefaultValue,
SymbolDisplay.ToDefaultValueLiteral(parameter),
parameter.IsParams
)),
],
methods.ToImmutable()
);
return true;
}
private static bool IsTaskOfT(ITypeSymbol returnType, out ITypeSymbol valueType)
{
valueType = returnType;
if (
returnType is not INamedTypeSymbol namedReturnType
|| namedReturnType.ConstructedFrom.ToDisplayString()
!= "System.Threading.Tasks.Task<TResult>"
|| namedReturnType.TypeArguments.Length != 1
)
{
return false;
}
valueType = namedReturnType.TypeArguments[0];
return true;
}
private static bool IsAwaitableServiceMethod(ITypeSymbol returnType)
{
var fullName = returnType.ToDisplayString();
if (fullName is "System.Threading.Tasks.Task" or "System.Threading.Tasks.ValueTask")
{
return true;
}
return returnType is INamedTypeSymbol namedReturnType
&& namedReturnType.TypeArguments.Length == 1
&& namedReturnType.ConstructedFrom.ToDisplayString()
is "System.Threading.Tasks.Task<TResult>"
or "System.Threading.Tasks.ValueTask<TResult>";
}
private static CacheOptions GetCacheOptions(AttributeData attribute)
{
var prefix = default(string);
var cacheKey = default(string);
var expirationSeconds = 3600;
var hasExplicitExpirationSeconds = false;
var postProcess = default(string);
var additionalTags = ImmutableArray.CreateBuilder<string>();
var failSafe = false;
var failSafeMaxDurationSeconds = 0;
var failSafeThrottleDurationSeconds = 0;
var factorySoftTimeoutSeconds = 0;
var factoryHardTimeoutSeconds = 0;
var allowTimedOutFactoryBackgroundCompletion = true;
var distributedCacheSoftTimeoutSeconds = 0;
var distributedCacheHardTimeoutSeconds = 0;
foreach (var namedArgument in attribute.NamedArguments)
{
switch (namedArgument.Key)
{
case "Prefix":
prefix = namedArgument.Value.Value as string;
break;
case "CacheKey":
cacheKey = namedArgument.Value.Value as string;
break;
case "ExpirationSeconds" when namedArgument.Value.Value is int configured:
expirationSeconds = configured;
hasExplicitExpirationSeconds = true;
break;
case "PostProcess":
postProcess = namedArgument.Value.Value as string;
break;
case "AdditionalTags" when namedArgument.Value.Kind == TypedConstantKind.Array:
foreach (var value in namedArgument.Value.Values)
{
if (value.Value is string tag && !string.IsNullOrWhiteSpace(tag))
{
additionalTags.Add(tag);
}
}
break;
case "FailSafe" when namedArgument.Value.Value is bool configuredFailSafe:
failSafe = configuredFailSafe;
break;
case "FailSafeMaxDurationSeconds"
when namedArgument.Value.Value is int configuredFailSafeMaxDuration:
failSafeMaxDurationSeconds = configuredFailSafeMaxDuration;
break;
case "FailSafeThrottleDurationSeconds"
when namedArgument.Value.Value is int configuredFailSafeThrottleDuration:
failSafeThrottleDurationSeconds = configuredFailSafeThrottleDuration;
break;
case "FactorySoftTimeoutSeconds"
when namedArgument.Value.Value is int configuredFactorySoftTimeout:
factorySoftTimeoutSeconds = configuredFactorySoftTimeout;
break;
case "FactoryHardTimeoutSeconds"
when namedArgument.Value.Value is int configuredFactoryHardTimeout:
factoryHardTimeoutSeconds = configuredFactoryHardTimeout;
break;
case "AllowTimedOutFactoryBackgroundCompletion"
when namedArgument.Value.Value is bool configuredBackgroundCompletion:
allowTimedOutFactoryBackgroundCompletion = configuredBackgroundCompletion;
break;
case "DistributedCacheSoftTimeoutSeconds"
when namedArgument.Value.Value is int configuredDistributedSoftTimeout:
distributedCacheSoftTimeoutSeconds = configuredDistributedSoftTimeout;
break;
case "DistributedCacheHardTimeoutSeconds"
when namedArgument.Value.Value is int configuredDistributedHardTimeout:
distributedCacheHardTimeoutSeconds = configuredDistributedHardTimeout;
break;
}
}
return new CacheOptions(
prefix,
cacheKey,
expirationSeconds,
hasExplicitExpirationSeconds,
postProcess,
additionalTags.ToImmutable(),
new CacheResilienceOptions(
failSafe,
failSafeMaxDurationSeconds,
failSafeThrottleDurationSeconds,
factorySoftTimeoutSeconds,
factoryHardTimeoutSeconds,
allowTimedOutFactoryBackgroundCompletion,
distributedCacheSoftTimeoutSeconds,
distributedCacheHardTimeoutSeconds
)
);
}
private static bool HasValidPostProcessMethod(
INamedTypeSymbol implementationType,
string methodName,
ITypeSymbol valueType,
out string message
)
{
foreach (var method in implementationType.GetMembers(methodName).OfType<IMethodSymbol>())
{
if (method.IsStatic)
{
continue;
}
if (method.Parameters.Length != 1)
{
continue;
}
if (!CanPassValueTo(valueType, method.Parameters[0].Type))
{
continue;
}
if (!IsPostProcessReturnType(method.ReturnType))
{
message =
$"post-process method '{methodName}' must return Task, ValueTask, Task<T> or ValueTask<T>";
return false;
}
message = string.Empty;
return true;
}
message =
$"post-process method '{methodName}' was not found or its first parameter is not compatible with '{valueType.ToDisplayString()}'";
return false;
}
private static bool IsPostProcessReturnType(ITypeSymbol returnType)
{
return IsAwaitableServiceMethod(returnType);
}
private static bool CanPassValueTo(ITypeSymbol valueType, ITypeSymbol parameterType)
{
if (SymbolEqualityComparer.Default.Equals(valueType, parameterType))
{
return true;
}
if (
valueType.AllInterfaces.Any(@interface =>
SymbolEqualityComparer.Default.Equals(@interface, parameterType)
)
)
{
return true;
}
var baseType = valueType.BaseType;
while (baseType is not null)
{
if (SymbolEqualityComparer.Default.Equals(baseType, parameterType))
{
return true;
}
baseType = baseType.BaseType;
}
return false;
}
private static bool TryCreateCachedParameter(
IParameterSymbol parameter,
bool hasExplicitCacheKey,
out CachedParameter cachedParameter,
out string message
)
{
cachedParameter = new CachedParameter(
parameter.Name,
SymbolDisplay.ToFullyQualifiedTypeName(parameter.Type),
parameter.RefKind,
parameter.HasExplicitDefaultValue,
SymbolDisplay.ToDefaultValueLiteral(parameter),
parameter.IsParams
);
message = string.Empty;
if (IsCancellationToken(parameter.Type) || hasExplicitCacheKey)
{
return true;
}
if (CanGenerateSingleValueKeyFor(parameter.Type))
{
return true;
}
var segments = ImmutableArray.CreateBuilder<CachedKeySegment>();
if (
!TryAppendObjectKeySegments(
parameter.Type,
parameter.Name,
parameter.Name,
[parameter.Name],
segments,
new HashSet<ITypeSymbol>(SymbolEqualityComparer.Default),
out message
)
)
{
return false;
}
cachedParameter = new CachedParameter(
parameter.Name,
SymbolDisplay.ToFullyQualifiedTypeName(parameter.Type),
parameter.RefKind,
parameter.HasExplicitDefaultValue,
SymbolDisplay.ToDefaultValueLiteral(parameter),
parameter.IsParams,
segments.ToImmutable()
);
return true;
}
private static bool TryAppendObjectKeySegments(
ITypeSymbol type,
string expression,
string keyPrefix,
ImmutableArray<string> nullCheckExpressions,
ImmutableArray<CachedKeySegment>.Builder segments,
HashSet<ITypeSymbol> visitedTypes,
out string message
)
{
message = string.Empty;
if (!CanTreatAsComplexKeyType(type))
{
message = $"parameter '{keyPrefix}' has unsupported type '{type.ToDisplayString()}'";
return false;
}
if (!visitedTypes.Add(type))
{
message =
$"parameter '{keyPrefix}' contains a recursive type '{type.ToDisplayString()}'";
return false;
}
var initialCount = segments.Count;
foreach (var property in GetPublicReadableProperties(type))
{
var propertyExpression = expression + "." + property.Name;
var propertyKey = keyPrefix + "." + property.Name;
var propertyNullChecks = nullCheckExpressions;
if (CanCheckForNull(property.Type))
{
propertyNullChecks = propertyNullChecks.Add(propertyExpression);
}
if (CanGenerateSingleValueKeyFor(property.Type))
{
segments.Add(
new CachedKeySegment(
propertyKey,
BuildValueExpression(propertyExpression, nullCheckExpressions)
)
);
continue;
}
if (
TryGetEnumerableElementType(property.Type, out var elementType)
&& CanTreatAsComplexKeyType(elementType)
)
{
segments.Add(
new CachedKeySegment(
propertyKey,
BuildValueExpression(
BuildComplexCollectionExpression(propertyExpression, elementType),
propertyNullChecks
)
)
);
continue;
}
if (
!TryAppendObjectKeySegments(
property.Type,
propertyExpression,
propertyKey,
propertyNullChecks,
segments,
visitedTypes,
out message
)
)
{
return false;
}
}
visitedTypes.Remove(type);
if (segments.Count == initialCount)
{
message =
$"parameter '{keyPrefix}' has no public readable properties that can be used as a cache key";
return false;
}
return true;
}
private static bool CanGenerateSingleValueKeyFor(ITypeSymbol type)
{
if (IsCancellationToken(type))
{
return true;
}
if (IsNullableValueType(type, out var underlyingType))
{
return CanGenerateSingleValueKeyFor(underlyingType);
}
if (type is IArrayTypeSymbol arrayType)
{
return CanGenerateSingleValueKeyFor(arrayType.ElementType);
}
if (TryGetEnumerableElementType(type, out var elementType))
{
return CanGenerateSingleValueKeyFor(elementType);
}
return IsScalarKeyType(type);
}
private static string BuildValueExpression(
string valueExpression,
ImmutableArray<string> nullCheckExpressions
)
{
var formattedExpression = "FormatCacheKeyValue(" + valueExpression + ")";
if (nullCheckExpressions.Length == 0)
{
return formattedExpression;
}
return "("
+ string.Join(" || ", nullCheckExpressions.Select(static item => item + " is null"))
+ ") ? string.Empty : "
+ formattedExpression;
}
private static string BuildComplexCollectionExpression(
string expression,
ITypeSymbol elementType
)
{
var segments = ImmutableArray.CreateBuilder<string>();
foreach (var property in GetPublicReadableProperties(elementType))
{
if (!CanGenerateSingleValueKeyFor(property.Type))
{
continue;
}
segments.Add(
"string.Concat("
+ SymbolDisplay.ToCSharpStringLiteral(property.Name + "=")
+ ", FormatCacheKeyValue(value."
+ property.Name
+ "))"
);
}
if (segments.Count == 0)
{
return "FormatCacheKeyValue(" + expression + ")";
}
return "FormatCacheKeyCollection("
+ expression
+ ", value => value is null ? string.Empty : string.Concat("
+ string.Join(", \"&\", ", segments)
+ "))";
}
private static bool CanTreatAsComplexKeyType(ITypeSymbol type)
{
if (type is not INamedTypeSymbol namedType)
{
return false;
}
if (namedType.TypeKind is not (TypeKind.Class or TypeKind.Struct))
{
return false;
}
var namespaceName = namedType.ContainingNamespace?.ToDisplayString() ?? string.Empty;
return !namespaceName.StartsWith("System", StringComparison.Ordinal);
}
private static bool CanCheckForNull(ITypeSymbol type)
{
if (type.IsReferenceType)
{
return true;
}
return IsNullableValueType(type, out _);
}
private static ImmutableArray<IPropertySymbol> GetPublicReadableProperties(ITypeSymbol type)
{
var properties = new Dictionary<string, IPropertySymbol>(StringComparer.Ordinal);
var currentType = type;
while (currentType is not null)
{
foreach (var property in currentType.GetMembers().OfType<IPropertySymbol>())
{
if (
property.DeclaredAccessibility != Accessibility.Public
|| property.IsStatic
|| property.GetMethod is null
|| property.GetMethod.DeclaredAccessibility != Accessibility.Public
|| property.Parameters.Length > 0
|| properties.ContainsKey(property.Name)
)
{
continue;
}
properties.Add(property.Name, property);
}
currentType = currentType.BaseType;
}
return
[
.. properties.Values.OrderBy(static property => property.Name, StringComparer.Ordinal),
];
}
private static bool IsScalarKeyType(ITypeSymbol type)
{
if (type.TypeKind == TypeKind.Enum)
{
return true;
}
if (
type.SpecialType
is SpecialType.System_Boolean
or SpecialType.System_Char
or SpecialType.System_SByte
or SpecialType.System_Byte
or SpecialType.System_Int16
or SpecialType.System_UInt16
or SpecialType.System_Int32
or SpecialType.System_UInt32
or SpecialType.System_Int64
or SpecialType.System_UInt64
or SpecialType.System_Decimal
or SpecialType.System_Single
or SpecialType.System_Double
or SpecialType.System_String
)
{
return true;
}
var fullName = type.ToDisplayString();
return fullName
is "System.Guid"
or "System.DateTime"
or "System.DateTimeOffset"
or "System.DateOnly"
or "System.TimeOnly";
}
private static bool IsNullableValueType(ITypeSymbol type, out ITypeSymbol underlyingType)
{
underlyingType = type;
if (
type is not INamedTypeSymbol namedType
|| namedType.ConstructedFrom.ToDisplayString() != "System.Nullable<T>"
|| namedType.TypeArguments.Length != 1
)
{
return false;
}
underlyingType = namedType.TypeArguments[0];
return true;
}
private static bool TryGetEnumerableElementType(ITypeSymbol type, out ITypeSymbol elementType)
{
elementType = type;
if (type.SpecialType == SpecialType.System_String)
{
return false;
}
if (
type is INamedTypeSymbol namedType
&& namedType.ConstructedFrom.ToDisplayString()
== "System.Collections.Generic.IEnumerable<T>"
&& namedType.TypeArguments.Length == 1
)
{
elementType = namedType.TypeArguments[0];
return true;
}
foreach (var implementedInterface in type.AllInterfaces)
{
if (
implementedInterface.ConstructedFrom.ToDisplayString()
!= "System.Collections.Generic.IEnumerable<T>"
)
{
continue;
}
elementType = implementedInterface.TypeArguments[0];
return true;
}
return false;
}
private static bool IsCancellationToken(ITypeSymbol type)
{
return type.ToDisplayString() == "System.Threading.CancellationToken";
}
private static AttributeData? GetAttribute(ISymbol symbol, string attributeFullName)
{
return symbol
.GetAttributes()
.FirstOrDefault(attribute =>
attribute.AttributeClass?.ToDisplayString() == attributeFullName
);
}
}
一句话定位
CacheMethodInspector.cs 是源生成器的“准入检查与元数据提取”层:把实现类方法上的 [Cache] / [InvalidateCache] 转成 CachedMethod / InvalidatedMethod,并在不满足生成前提时抛出 Error 级诊断(DPZ_CACHE001/003/004)。它是整条生成管线里唯一会拒绝生成的位置,装饰器源码生成器默认拿到的数据都“已经合法”。
关键类型与方法
两个入口 GetCachedMethods / GetInvalidatedMethods(均 internal static)
- 只扫描实现类型自身声明的成员(
implementationType.GetMembers()不返回继承成员),因此 [Cache] 写在基类方法上不会生效,也没有诊断提示。这是隐含约束,代码注释未说明。 - 每个带特性的实现方法都必须能映射回“当前注册的那个接口”的方法,否则报错(
001/004,消息为 “method is not part of the registered service interface”)。这条校验是为了避免“标了缓存但外部调用走不到装饰器”。 - 参数
attribute!的空容忍是安全的:方法进列表前已用GetAttribute过滤过。 - 注意两条分支的诊断参数不一致:同一个方法里,“不属于接口”分支把
implementationType作为{0},而TryCreate*失败分支把interfaceType作为{0}却把 Location 指向实现方法。看报错时要意识到{0}有时是接口名、有时是实现类名。
FindInterfaceMethod
先用 FindImplementationForInterfaceMember 做符号级精确匹配,再退化为 HasSameSignature(名字 + 类型参数个数 + 参数 RefKind/类型逐一相等)。退化匹配的代价:
- 泛型接口方法基本匹配不上(接口 T 与实现 T 不是同一符号),会落到“不属于接口”的错误;
- 只要类上有同名同参数的方法,即使它并不是该接口的实现,也会被认为是匹配,后续生成的装饰器调用
inner.Xxx(...)可能编译不过——错误从“诊断”退化为“生成代码报错”。
TryCreateCachedMethod
- 只接受
Task<T>(ValueTask<T>会被拒绝,尽管失效方法侧支持ValueTask); ExpirationSeconds必须 > 0(由于特性本身默认 3600,只有在显式写 0/负数时才触发);- 参数不允许
ref/out/in; - 返回
(bool, out string message)而不是直接报诊断,descriptor 的选择由调用方完成——见下面的坑。
TryCreateInvalidatedMethod
- 返回值允许
Task/Task<T>/ValueTask/ValueTask<T>; - 从
NamedArguments手写解析Methods数组,逐项校验是否在cachedMethods的名字集合里,且只比较方法名。
键表达式构建(TryCreateCachedParameter / TryAppendObjectKeySegments / BuildValueExpression / BuildComplexCollectionExpression)
这是本文件最重的一块,实际产出的是C# 源码表达式字符串(如 (query.Range is null || query is null) ? string.Empty : FormatCacheKeyValue(query.Range.Start)),最终由 CacheMetadataSourceGenerator.cs 原样拼进 Build{Method}CacheKey。因此这里的字符串格式与键助手方法名(FormatCacheKeyValue、FormatCacheKeyCollection)是跨文件的隐式契约,改动一处会静默破坏另一端;字符串没有编译期校验,写错只能在生成代码编译时暴露。
- 有
CancellationToken参数时视为“可格式化”并在 metadata 侧被过滤; - 显式设置了
CacheKey时跳过所有参数的类型合法性检查(这是特性文档给出的“绕开不支持类型”的正规手段); - 复杂 DTO 递归展开为
参数.属性.子属性片段,用visitedTypes(按路径加入/移除)检测自引用并报 “contains a recursive type”; - 集合中元素为复杂类型时走
BuildComplexCollectionExpression,只保留元素的可单值格式化属性,其余属性走continue被静默丢弃——不同的集合入参可能生成相同缓存键,是会串数据的隐患; CanTreatAsComplexKeyType把命名空间以System开头的类型一律排除,IsScalarKeyType白名单里也没有TimeSpan/Uri,所以TimeSpan参数会直接得到DPZ_CACHE001。
HasValidPostProcessMethod
检查非 static、恰好一个参数、参数能接收被缓存值、返回 awaitable,但不检查可访问性:private 的后处理方法会通过校验,而生成的装饰器是另一个类,inner.PostProcess(...) 会编译失败(CS0122),诊断 DPZ_CACHE003 不会出现。README 只写“推荐 internal”,即规则并未强制。
CanPassValueTo 是手写的类型关系判断(同一符号 / 接口 / 基类链),不是 Compilation.ClassifyConversion,因此隐式数值转换、T → Nullable<T>、泛型协变(IEnumerable<Derived> → IEnumerable<Base>)都会误判为不兼容。
GetCacheOptions
手写 switch 解析所有命名参数,默认值与 CacheAttribute 的默认值重复维护了一份(3600、AllowTimedOutFactoryBackgroundCompletion = true)。未识别的参数(属性被改名/拼错)会被静默忽略,没有诊断。hasExplicitExpirationSeconds 只为复现“显式设过期时间就关闭 fail-safe”的历史行为,具体消费点在 CacheDecoratorSourceGenerator.cs 的 AppendFailSafeOptions。
依赖与协作
- 上游:ServiceRegistrationProvider.cs 的
CreateRegistration先调GetCachedMethods,再把结果作为cachedMethodNames来源传给GetInvalidatedMethods(顺序不能反)。 - 下游元数据:结果进入 ServiceRegistration.cs,被三处消费——
RequiresDecorator(任一列表非空即注册装饰器)、ServiceRegistrationSourceBuilder.cs、CacheDecoratorSourceGenerator.cs、CacheMetadataSourceGenerator.cs。 - 依赖项:特性全名常量 SourceGeneratorAttributeNames.cs、类型名/默认值字面量 SymbolDisplay.cs、容错参数交叉校验 CacheResilienceOptions.cs 的
Validate。 - 诊断通过
SourceProductionContext.ReportDiagnostic直出,文件内用#pragma warning disable RS2008压制规则发布追踪(与 README 的说明一致)。 - 装饰器方法签名不来自本文件,而是 InterfaceContractInspector.cs(接口方法/属性/事件),本文件只按“名字 + 参数类型名”与之匹配。
流程/时序
flowchart TD
A[ServiceRegistrationGenerator] --> B[ServiceRegistrationProvider.CreateRegistration]
B --> C[GetCachedMethods]
C --> D[枚举实现类自身带 Cache 的方法]
D --> E{能映射到接口方法?}
E -- 否 --> E1[报告 DPZ_CACHE001]
E -- 是 --> F[TryCreateCachedMethod]
F --> F1[返回 Task<T> / 过期时间 / ref 检查]
F1 --> F2[解析 CacheOptions + 容错校验]
F2 --> F3[生成参数缓存键片段或接受显式 CacheKey]
F3 --> F4[校验 PostProcess 方法]
F4 -->|失败| F5[DPZ_CACHE001 或 003]
F4 -->|成功| G[CachedMethod]
G --> H[GetInvalidatedMethods]
H --> I[枚举实现类自身带 InvalidateCache 的方法]
I --> I1{Methods 非空且均命中已缓存方法名?}
I1 -- 否 --> I2[报告 DPZ_CACHE004]
I1 -- 是 --> J[InvalidatedMethod]
G --> K[ServiceRegistration]
J --> K
需要注意的点
- 诊断 ID 靠字符串前缀分派:
message.StartsWith("post-process", StringComparison.Ordinal)决定用003还是001。改一句错误文案就会静默切换诊断编号,这条隐式契约没有任何测试保护。 - 编号缺
DPZ_CACHE002:全仓库搜索无该 ID,001/003/004之间有一个空档,说明曾有一条规则被移除或从未实现,README 也只列了三条。 - 重载方法按名字混用:失效链路(
cachedMethodNames、装饰器里的AppendRemoveMethodTags、metadata 的GetDistinctCachedMethods按Name分组取第一)全部以方法名为键。接口上存在同名重载时,[InvalidateCache]的命中判断、prefix/method tag 常量都会张冠李戴。 - 集合元素属性被静默丢弃:
BuildComplexCollectionExpression跳过非标量属性,既不报诊断也不参与键,等价于把不同入参折叠成同一键。与“不支持就报DPZ_CACHE001”的既有策略不一致。 - 后处理方法可访问性未校验:会产生“生成代码编译失败”而不是
DPZ_CACHE003,与“尽量把错误前移到诊断”的设计目标相反。 CanPassValueTo过于保守:隐式转换/协变场景会被误判为不兼容,实际报错信息会误导开发者以为方法签名不匹配。GetInterfaceMethods不去重:AllInterfaces+ 自身成员的简单拼接,菱形继承下同一签名可能出现两次;FindInterfaceMethod取首个命中,通常无害但语义不确定。- 继承来的缓存方法不识别:
GetMembers()只取自身声明,抽象基类/父类上的[Cache]会被完全忽略;而ServiceRegistrationProvider只要求实现类是非抽象类,两者组合成一个静默失效场景。 - 本文件内的默认值(
ExpirationSeconds = 3600、AllowTimedOutFactoryBackgroundCompletion = true)与 CacheAttribute 的属性初始化器重复,改特性默认值时必须同步这里,否则生成代码与文档约定不一致。