This repository has been archived by the owner on Dec 14, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
CacheTagKey.cs
375 lines (322 loc) · 13.8 KB
/
CacheTagKey.cs
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Razor.Infrastructure;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Internal;
using Microsoft.Extensions.Primitives;
namespace Microsoft.AspNetCore.Mvc.TagHelpers.Cache
{
/// <summary>
/// An instance of <see cref="CacheTagKey"/> represents the state of <see cref="CacheTagHelper"/>
/// or <see cref="DistributedCacheTagHelper"/> keys.
/// </summary>
public class CacheTagKey : IEquatable<CacheTagKey>
{
private static readonly char[] AttributeSeparator = new[] { ',' };
private static readonly Func<IRequestCookieCollection, string, string> CookieAccessor = (c, key) => c[key];
private static readonly Func<IHeaderDictionary, string, string> HeaderAccessor = (c, key) => c[key];
private static readonly Func<IQueryCollection, string, string> QueryAccessor = (c, key) => c[key];
private static readonly Func<RouteValueDictionary, string, string> RouteValueAccessor = (c, key) =>
Convert.ToString(c[key], CultureInfo.InvariantCulture);
private const string CacheKeyTokenSeparator = "||";
private const string VaryByName = "VaryBy";
private const string VaryByHeaderName = "VaryByHeader";
private const string VaryByQueryName = "VaryByQuery";
private const string VaryByRouteName = "VaryByRoute";
private const string VaryByCookieName = "VaryByCookie";
private const string VaryByUserName = "VaryByUser";
private const string VaryByCulture = "VaryByCulture";
private readonly string _prefix;
private readonly string _varyBy;
private readonly DateTimeOffset? _expiresOn;
private readonly TimeSpan? _expiresAfter;
private readonly TimeSpan? _expiresSliding;
private readonly IList<KeyValuePair<string, string>> _headers;
private readonly IList<KeyValuePair<string, string>> _queries;
private readonly IList<KeyValuePair<string, string>> _routeValues;
private readonly IList<KeyValuePair<string, string>> _cookies;
private readonly bool _varyByUser;
private readonly bool _varyByCulture;
private readonly string _username;
private readonly CultureInfo _requestCulture;
private readonly CultureInfo _requestUICulture;
private string _generatedKey;
private int? _hashcode;
/// <summary>
/// Creates an instance of <see cref="CacheTagKey"/> for a specific <see cref="CacheTagHelper"/>.
/// </summary>
/// <param name="tagHelper">The <see cref="CacheTagHelper"/>.</param>
/// <param name="context">The <see cref="TagHelperContext"/>.</param>
/// <returns>A new <see cref="CacheTagKey"/>.</returns>
public CacheTagKey(CacheTagHelper tagHelper, TagHelperContext context)
: this(tagHelper)
{
Key = context.UniqueId;
_prefix = nameof(CacheTagHelper);
}
/// <summary>
/// Creates an instance of <see cref="CacheTagKey"/> for a specific <see cref="DistributedCacheTagHelper"/>.
/// </summary>
/// <param name="tagHelper">The <see cref="DistributedCacheTagHelper"/>.</param>
/// <returns>A new <see cref="CacheTagKey"/>.</returns>
public CacheTagKey(DistributedCacheTagHelper tagHelper)
: this((CacheTagHelperBase)tagHelper)
{
Key = tagHelper.Name;
_prefix = nameof(DistributedCacheTagHelper);
}
private CacheTagKey(CacheTagHelperBase tagHelper)
{
var httpContext = tagHelper.ViewContext.HttpContext;
var request = httpContext.Request;
_expiresAfter = tagHelper.ExpiresAfter;
_expiresOn = tagHelper.ExpiresOn;
_expiresSliding = tagHelper.ExpiresSliding;
_varyBy = tagHelper.VaryBy;
_cookies = ExtractCollection(tagHelper.VaryByCookie, request.Cookies, CookieAccessor);
_headers = ExtractCollection(tagHelper.VaryByHeader, request.Headers, HeaderAccessor);
_queries = ExtractCollection(tagHelper.VaryByQuery, request.Query, QueryAccessor);
_routeValues = ExtractCollection(
tagHelper.VaryByRoute,
tagHelper.ViewContext.RouteData.Values,
RouteValueAccessor);
_varyByUser = tagHelper.VaryByUser;
_varyByCulture = tagHelper.VaryByCulture;
if (_varyByUser)
{
_username = httpContext.User?.Identity?.Name;
}
if (_varyByCulture)
{
_requestCulture = CultureInfo.CurrentCulture;
_requestUICulture = CultureInfo.CurrentUICulture;
}
}
// Internal for unit testing.
internal string Key { get; }
/// <summary>
/// Creates a <see cref="string"/> representation of the key.
/// </summary>
/// <returns>A <see cref="string"/> uniquely representing the key.</returns>
public string GenerateKey()
{
// Caching as the key is immutable and it can be called multiple times during a request.
if (_generatedKey != null)
{
return _generatedKey;
}
var builder = new StringBuilder(_prefix);
builder
.Append(CacheKeyTokenSeparator)
.Append(Key);
if (!string.IsNullOrEmpty(_varyBy))
{
builder
.Append(CacheKeyTokenSeparator)
.Append(VaryByName)
.Append(CacheKeyTokenSeparator)
.Append(_varyBy);
}
AddStringCollection(builder, VaryByCookieName, _cookies);
AddStringCollection(builder, VaryByHeaderName, _headers);
AddStringCollection(builder, VaryByQueryName, _queries);
AddStringCollection(builder, VaryByRouteName, _routeValues);
if (_varyByUser)
{
builder
.Append(CacheKeyTokenSeparator)
.Append(VaryByUserName)
.Append(CacheKeyTokenSeparator)
.Append(_username);
}
if (_varyByCulture)
{
builder
.Append(CacheKeyTokenSeparator)
.Append(VaryByCulture)
.Append(CacheKeyTokenSeparator)
.Append(_requestCulture)
.Append(CacheKeyTokenSeparator)
.Append(_requestUICulture);
}
_generatedKey = builder.ToString();
return _generatedKey;
}
/// <summary>
/// Creates a hashed value of the key.
/// </summary>
/// <returns>A cryptographic hash of the key.</returns>
public string GenerateHashedKey()
{
var key = GenerateKey();
// The key is typically too long to be useful, so we use a cryptographic hash
// as the actual key (better randomization and key distribution, so small vary
// values will generate dramatically different keys).
using (var sha256 = CryptographyAlgorithms.CreateSHA256())
{
var contentBytes = Encoding.UTF8.GetBytes(key);
var hashedBytes = sha256.ComputeHash(contentBytes);
return Convert.ToBase64String(hashedBytes);
}
}
/// <inheritdoc />
public override bool Equals(object obj)
{
if (obj is CacheTagKey other)
{
return Equals(other);
}
return false;
}
/// <inheritdoc />
public bool Equals(CacheTagKey other)
{
return string.Equals(other.Key, Key, StringComparison.Ordinal) &&
other._expiresAfter == _expiresAfter &&
other._expiresOn == _expiresOn &&
other._expiresSliding == _expiresSliding &&
string.Equals(other._varyBy, _varyBy, StringComparison.Ordinal) &&
AreSame(_cookies, other._cookies) &&
AreSame(_headers, other._headers) &&
AreSame(_queries, other._queries) &&
AreSame(_routeValues, other._routeValues) &&
(_varyByUser == other._varyByUser &&
(!_varyByUser || string.Equals(other._username, _username, StringComparison.Ordinal))) &&
CultureEquals();
bool CultureEquals()
{
if (_varyByCulture != other._varyByCulture)
{
return false;
}
if (!_varyByCulture)
{
// Neither has culture set.
return true;
}
return _requestCulture.Equals(other._requestCulture) &&
_requestUICulture.Equals(other._requestUICulture);
}
}
/// <inheritdoc />
public override int GetHashCode()
{
// The hashcode is intentionally not using the computed
// stringified key in order to prevent string allocations
// in the common case where it's not explicitly required.
// Caching as the key is immutable and it can be called
// multiple times during a request.
if (_hashcode.HasValue)
{
return _hashcode.Value;
}
var hashCodeCombiner = new HashCodeCombiner();
hashCodeCombiner.Add(Key, StringComparer.Ordinal);
hashCodeCombiner.Add(_expiresAfter);
hashCodeCombiner.Add(_expiresOn);
hashCodeCombiner.Add(_expiresSliding);
hashCodeCombiner.Add(_varyBy, StringComparer.Ordinal);
hashCodeCombiner.Add(_username, StringComparer.Ordinal);
hashCodeCombiner.Add(_requestCulture);
hashCodeCombiner.Add(_requestUICulture);
CombineCollectionHashCode(hashCodeCombiner, VaryByCookieName, _cookies);
CombineCollectionHashCode(hashCodeCombiner, VaryByHeaderName, _headers);
CombineCollectionHashCode(hashCodeCombiner, VaryByQueryName, _queries);
CombineCollectionHashCode(hashCodeCombiner, VaryByRouteName, _routeValues);
_hashcode = hashCodeCombiner.CombinedHash;
return _hashcode.Value;
}
private static IList<KeyValuePair<string, string>> ExtractCollection<TSourceCollection>(
string keys,
TSourceCollection collection,
Func<TSourceCollection, string, string> accessor)
{
if (string.IsNullOrEmpty(keys))
{
return null;
}
var tokenizer = new StringTokenizer(keys, AttributeSeparator);
var result = new List<KeyValuePair<string, string>>();
foreach (var item in tokenizer)
{
var trimmedValue = item.Trim();
if (trimmedValue.Length != 0)
{
var value = accessor(collection, trimmedValue.Value);
result.Add(new KeyValuePair<string, string>(trimmedValue.Value, value ?? string.Empty));
}
}
return result;
}
private static void AddStringCollection(
StringBuilder builder,
string collectionName,
IList<KeyValuePair<string, string>> values)
{
if (values == null || values.Count == 0)
{
return;
}
// keyName(param1=value1|param2=value2)
builder
.Append(CacheKeyTokenSeparator)
.Append(collectionName)
.Append("(");
for (var i = 0; i < values.Count; i++)
{
var item = values[i];
if (i > 0)
{
builder.Append(CacheKeyTokenSeparator);
}
builder
.Append(item.Key)
.Append(CacheKeyTokenSeparator)
.Append(item.Value);
}
builder.Append(")");
}
private static void CombineCollectionHashCode(
HashCodeCombiner hashCodeCombiner,
string collectionName,
IList<KeyValuePair<string, string>> values)
{
if (values != null)
{
hashCodeCombiner.Add(collectionName, StringComparer.Ordinal);
for (var i = 0; i < values.Count; i++)
{
var item = values[i];
hashCodeCombiner.Add(item.Key);
hashCodeCombiner.Add(item.Value);
}
}
}
private static bool AreSame(IList<KeyValuePair<string, string>> values1, IList<KeyValuePair<string, string>> values2)
{
if (values1 == values2)
{
return true;
}
if (values1 == null || values2 == null || values1.Count != values2.Count)
{
return false;
}
for (var i = 0; i < values1.Count; i++)
{
if (!string.Equals(values1[i].Key, values2[i].Key, StringComparison.Ordinal) ||
!string.Equals(values1[i].Value, values2[i].Value, StringComparison.Ordinal))
{
return false;
}
}
return true;
}
}
}