-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCacheKeyIdentity.cs
More file actions
256 lines (218 loc) · 6.31 KB
/
CacheKeyIdentity.cs
File metadata and controls
256 lines (218 loc) · 6.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace CleverCache;
internal static class CacheKeyIdentity
{
private const string Prefix = "cck::";
private static readonly JsonSerializerOptions JsonOptions = CreateJsonOptions();
internal static string ToCanonicalKey(object key)
{
ArgumentNullException.ThrowIfNull(key);
if (key is string s && IsCanonicalKey(s))
return s;
var typeIdentity = GetTypeIdentity(key.GetType());
return ToCanonicalKey(typeIdentity, key);
}
internal static string ToCanonicalKey(string typeIdentity, object payload)
{
ArgumentException.ThrowIfNullOrWhiteSpace(typeIdentity);
ArgumentNullException.ThrowIfNull(payload);
var serializedPayload = SerializePayload(payload);
return $"{Prefix}{typeIdentity}|{serializedPayload}";
}
internal static bool TryToCanonicalKey(object? key, out string canonicalKey)
{
if (key is null)
{
canonicalKey = string.Empty;
return false;
}
try
{
canonicalKey = ToCanonicalKey(key);
return true;
}
catch (NotSupportedException)
{
canonicalKey = string.Empty;
return false;
}
catch (InvalidOperationException)
{
canonicalKey = string.Empty;
return false;
}
catch (ArgumentException)
{
canonicalKey = string.Empty;
return false;
}
}
internal static bool TryToCanonicalKey(string typeIdentity, object? payload, out string canonicalKey)
{
if (payload is null || string.IsNullOrWhiteSpace(typeIdentity))
{
canonicalKey = string.Empty;
return false;
}
try
{
canonicalKey = ToCanonicalKey(typeIdentity, payload);
return true;
}
catch (NotSupportedException)
{
canonicalKey = string.Empty;
return false;
}
catch (InvalidOperationException)
{
canonicalKey = string.Empty;
return false;
}
catch (ArgumentException)
{
canonicalKey = string.Empty;
return false;
}
}
internal static bool TryGetUnsupportedKeyShapeReason(object? key, out string? reason)
{
if (key is null)
{
reason = null;
return false;
}
var visited = new HashSet<object>(ReferenceEqualityComparer.Instance);
return TryGetUnsupportedKeyShapeReason(key, "key", 0, visited, out reason);
}
internal static bool IsCanonicalKey(string key) =>
key.StartsWith(Prefix, StringComparison.Ordinal);
internal static string GetTypeIdentity(Type type)
{
var fullName = type.FullName ?? type.Name;
var assemblyName = type.Assembly.GetName().Name ?? "UnknownAssembly";
return $"{fullName}, {assemblyName}";
}
private static string SerializePayload(object key)
{
if (key is Type typeKey)
return JsonSerializer.Serialize(GetTypeIdentity(typeKey), JsonOptions);
if (key is Delegate del)
return JsonSerializer.Serialize(del.ToString(), JsonOptions);
try
{
return JsonSerializer.Serialize(key, key.GetType(), JsonOptions);
}
catch (NotSupportedException)
{
return JsonSerializer.Serialize(key.ToString(), JsonOptions);
}
catch (InvalidOperationException)
{
return JsonSerializer.Serialize(key.ToString(), JsonOptions);
}
}
private static bool TryGetUnsupportedKeyShapeReason(object key, string path, int depth, HashSet<object> visited, out string? reason)
{
reason = null;
var type = key.GetType();
if (IsSupportedLeafType(type))
return false;
if (key is Delegate)
{
reason = $"{path} contains a delegate ({GetTypeIdentity(type)})";
return true;
}
if (key is Expression)
{
reason = $"{path} contains an expression ({GetTypeIdentity(type)})";
return true;
}
if (typeof(IQueryable).IsAssignableFrom(type))
{
reason = $"{path} contains a queryable value ({GetTypeIdentity(type)})";
return true;
}
if (depth >= 6)
return false;
if (!type.IsValueType && !visited.Add(key))
return false;
if (key is IEnumerable enumerable && key is not string)
{
var index = 0;
foreach (var item in enumerable)
{
if (item is null)
{
index++;
continue;
}
if (TryGetUnsupportedKeyShapeReason(item, $"{path}[{index}]", depth + 1, visited, out reason))
return true;
index++;
}
return false;
}
foreach (var property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
if (!property.CanRead || property.GetIndexParameters().Length > 0)
continue;
var value = property.GetValue(key);
if (value is not null &&
TryGetUnsupportedKeyShapeReason(value, $"{path}.{property.Name}", depth + 1, visited, out reason))
{
return true;
}
}
return false;
}
private static bool IsSupportedLeafType(Type type) =>
type.IsPrimitive ||
type.IsEnum ||
type == typeof(string) ||
type == typeof(decimal) ||
type == typeof(DateTime) ||
type == typeof(DateTimeOffset) ||
type == typeof(TimeSpan) ||
type == typeof(Guid) ||
type == typeof(Uri) ||
type == typeof(Type) ||
type == typeof(Version) ||
type == typeof(DateOnly) ||
type == typeof(TimeOnly) ||
type == typeof(IntPtr) ||
type == typeof(UIntPtr);
private static JsonSerializerOptions CreateJsonOptions()
{
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web);
options.Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
options.ReferenceHandler = ReferenceHandler.IgnoreCycles;
options.Converters.Add(new ExpressionJsonConverterFactory());
return options;
}
private sealed class ExpressionJsonConverterFactory : JsonConverterFactory
{
public override bool CanConvert(Type typeToConvert) =>
typeof(Expression).IsAssignableFrom(typeToConvert);
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
{
var converterType = typeof(ExpressionJsonConverter<>).MakeGenericType(typeToConvert);
return (JsonConverter)Activator.CreateInstance(converterType)!;
}
}
private sealed class ExpressionJsonConverter<TExpression> : JsonConverter<TExpression>
where TExpression : Expression
{
public override TExpression? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
throw new NotSupportedException("Cache key expressions are write-only.");
public override void Write(Utf8JsonWriter writer, TExpression value, JsonSerializerOptions options) =>
writer.WriteStringValue(value.ToString());
}
}