Repository navigation
Expand file tree
/
Copy pathFileCache.cs
More file actions
575 lines (500 loc) · 20.2 KB
/
Copy pathFileCache.cs
File metadata and controls
575 lines (500 loc) · 20.2 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
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
using System.IO;
using System.Net;
using System.Reflection;
namespace HttpClientCache.Files;
/// <summary>
/// Provides a file-based implementation of <see cref="IHttpCache"/> for persistent HTTP response caching on disk.
/// </summary>
public class FileCache : IHttpCache
{
private readonly DirectoryInfo _rootDirectory;
private readonly DirectoryInfo _tempDirectory;
private readonly ICacheKeyComputer _cacheKeyComputer;
private readonly TimeProvider _timeProvider;
private readonly ITimer _timer;
public static FileCache Default { get; } = new();
public DirectoryInfo RootDirectory => _rootDirectory;
/// <summary>
/// Gets or sets the maximum number of cache entries allowed in the cache directory.
/// Note that this is a soft limit, and the actual number of entries may exceed this value temporarily during purging.
/// </summary>
public int MaxEntries { get; set; } = 1000;
/// <summary>
/// The default duration for which a cached entry remains valid <i>after it is first seen</i> if no explicit expiration is set in the response.
/// </summary>
public TimeSpan DefaultInitialExpiration { get; set; } = TimeSpan.FromDays(2);
/// <summary>
/// The default duration for which a cached entry remains valid <i>when it is seen again</i> if no explicit expiration is set in the response.
/// </summary>
public TimeSpan DefaultRefreshExpiration { get; set; } = TimeSpan.FromDays(2);
/// <summary>
/// Creates a new instance of <see cref="FileCache"/> with the default root directory.
/// </summary>
public FileCache()
: this(GetDefaultRootDirectory()) { }
private static string GetDefaultRootDirectory()
{
// GetEntryAssembly() can return null when hosted by unmanaged code or some test runners,
// so fall back to the executing assembly and finally to a constant name.
var appName =
Assembly.GetEntryAssembly()?.GetName().Name
?? Assembly.GetExecutingAssembly().GetName().Name
?? "HttpClient.Cache";
return Path.Combine(Path.GetTempPath(), "HttpClient.FileCache", appName);
}
/// <summary>
/// Creates a new instance of <see cref="FileCache"/> with the specified root directory.
/// </summary>
/// <param name="rootDirectory">The directory where cache files are stored.</param>
public FileCache(string rootDirectory)
: this(rootDirectory, new CacheKeyComputer(), TimeProvider.System) { }
/// <summary>
/// Creates a new instance of <see cref="FileCache"/>.
/// </summary>
/// <param name="rootDirectory">The directory where cache files are stored</param>
/// <param name="cacheKeyComputer">The mechanism used to provide cache keys for a given request</param>
/// <param name="timeProvider">The time provider</param>
public FileCache(
string rootDirectory,
ICacheKeyComputer cacheKeyComputer,
TimeProvider timeProvider
)
{
_cacheKeyComputer = cacheKeyComputer;
_timeProvider = timeProvider;
_rootDirectory = new(rootDirectory);
if (!_rootDirectory.Exists)
{
_rootDirectory.Create();
}
// 1) Ensure temp directory is separate to avoid conflicts
// 2) Let temp files be on the same file system for performance and atomicity during file moves
// 3) Allow for easier cleanup as the temp directory can be traversed when recursively deleting files in the root directory
_tempDirectory = new(Path.Combine(rootDirectory, "temp"));
if (!_tempDirectory.Exists)
{
_tempDirectory.Create();
}
_timer = timeProvider.CreateTimer(
_ => Purge(),
null,
TimeSpan.FromMinutes(5),
TimeSpan.FromMinutes(5)
);
}
public async ValueTask<HttpResponseMessage?> GetResponseAsync(
HttpRequestMessage request,
CancellationToken cancellationToken = default
)
{
var response = await GetResponseWithVariationAsync(request, cancellationToken);
return response?.Response;
}
public async ValueTask<ResponseWithVariation?> GetResponseWithVariationAsync(
HttpRequestMessage request,
CancellationToken cancellationToken = default
)
{
var responseKey = _cacheKeyComputer.ComputeKey(request, new(CacheType.Shared));
if (responseKey is null)
{
return null;
}
var fileInfo = FindJsonFile(responseKey);
if (fileInfo is null)
{
return null;
}
var filename = FileName.FromFileInfo(fileInfo);
if (filename.IsMetadataFile)
{
// A response was found directly from the response key without a variation
var filePair = ResponseFilePair.FromMetadataFileInfo(fileInfo);
var response = await filePair.GetResponseAsync(_timeProvider.GetUtcNow());
if (response is null)
{
// Response is expired
filePair.TryDelete();
return null;
}
response.RequestMessage = request;
return new(response, new Variation(CacheType.Shared));
}
else if (filename.IsVariationFile)
{
// A variation file was found, so we need to read the variation to find the response
var file = VariationFile.FromVariationFileInfo(fileInfo);
// Indicate that we have used the variation file
filename.Refresh(fileInfo, _timeProvider.GetUtcNow());
var variation = await file.GetVariationAsync(_timeProvider.GetUtcNow());
if (variation is null)
{
return null;
}
// Recompute the response key using the variation
responseKey = _cacheKeyComputer.ComputeKey(request, variation);
if (responseKey is null)
{
return null;
}
fileInfo = FindJsonFile(responseKey, filename.EtagHash);
if (fileInfo is null)
{
return null;
}
filename = FileName.FromFileInfo(fileInfo);
if (filename.IsMetadataFile)
{
var filePair = ResponseFilePair.FromMetadataFileInfo(fileInfo);
var response = await filePair.GetResponseAsync(_timeProvider.GetUtcNow());
if (response is null)
{
// Response is expired
filePair.TryDelete();
return null;
}
response.RequestMessage = request;
return new(response, variation);
}
}
return null;
}
public async ValueTask<HttpResponseMessage?> SetResponseAsync(
HttpResponseMessage response,
CancellationToken cancellationToken = default
)
{
var variation = Variation.FromResponseMessage(response);
if (variation.CacheType == CacheType.None)
{
// Response is not cacheable
return null;
}
var request =
response.RequestMessage
?? throw new ArgumentNullException(
nameof(response),
"Response must have a RequestMessage set."
);
var responseKey = _cacheKeyComputer.ComputeKey(request, new(CacheType.Shared));
if (responseKey is null)
{
// Response cannot be cached as the cache key could not be computed
return null;
}
if (variation.CacheType == CacheType.Shared && variation.NormalizedVaryHeaders.Count == 0)
{
// No Vary header, cache the response directly in the shared cache using the entry key
var now = _timeProvider.GetUtcNow();
var cachedResponse = await SetResponseImplAsync(
responseKey,
response,
now,
cancellationToken
);
cachedResponse.RequestMessage = request;
return cachedResponse;
}
else
{
// The response is private or has a Vary header, so we need to cache both the response and the variation
// Let the computed response key be the key for the variation,
// and compute a new response key using the variation
var variationKey = responseKey;
responseKey = _cacheKeyComputer.ComputeKey(request, variation);
if (responseKey is null)
{
// Response cannot be cached as the variation key could not be computed
return null;
}
var now = _timeProvider.GetUtcNow();
var modified = response.GetModified() ?? now;
var expiration = response.GetExpiration(now) ?? (now + DefaultInitialExpiration);
// Write the response
var cachedResponse = await SetResponseImplAsync(
responseKey,
response,
now,
cancellationToken
);
cachedResponse.RequestMessage = request;
var variationFileName = FileName.Variation(
variationKey,
modified,
response.Headers.ETag
);
var variationFile = VariationFile.CreateTemp(_tempDirectory);
await variationFile.WriteAsync(request.RequestUri!, variation);
// Let the variation file have the same (possibly updated) expiration as the response
variationFileName.SetExpiration(variationFile.Info, expiration);
variationFile.TryMakePermanent(_rootDirectory, variationFileName);
return cachedResponse;
}
}
private async Task<HttpResponseMessage> SetResponseImplAsync(
string responseKey,
HttpResponseMessage response,
DateTimeOffset now,
CancellationToken cancellationToken
)
{
var modified = response.GetModified() ?? now;
var expiration = response.GetExpiration(now) ?? (now + DefaultInitialExpiration);
var metadata = new MetadataModel()
{
Url = response.RequestMessage!.RequestUri!,
Version = response.Version,
StatusCode = response.StatusCode,
ReasonPhrase = response.ReasonPhrase,
ResponseHeaders = response
.Headers.Select(x => new KeyValuePair<string, List<string>>(
x.Key,
x.Value.ToList()
))
.ToList(),
ContentHeaders = response
.Content.Headers.Select(x => new KeyValuePair<string, List<string>>(
x.Key,
x.Value.ToList()
))
.ToList(),
TrailingHeaders = response
.TrailingHeaders.Select(x => new KeyValuePair<string, List<string>>(
x.Key,
x.Value.ToList()
))
.ToList(),
};
var metadataFileName = FileName.Metadata(responseKey, modified, response.Headers.ETag);
var filePair = ResponseFilePair.CreateTemp(_tempDirectory);
await using (var responseFile = filePair.ResponseInfo.OpenWrite())
{
// Generate the cached response from the response
await using var httpStream = await response.Content.ReadAsStreamAsync(
cancellationToken
);
await httpStream.CopyToAsync(responseFile, cancellationToken);
}
await filePair.WriteMetadataAsync(metadata);
// Set the expiration on the metadata file
metadataFileName.SetExpiration(filePair.MetadataInfo, expiration);
// Try and make the file pair permanent
// If it fails then it really does not matter, as we will then just serve the temporary file and clean up later
filePair.TryMakePermanent(_rootDirectory, metadataFileName);
// Allow expired responses to be returned in case that the expiration was immediate
var cachedResponse = await filePair.GetResponseAsync(now, allowExpired: true);
return cachedResponse!;
}
public ValueTask RefreshResponseAsync(
HttpResponseMessage cachedResponse,
CancellationToken cancellationToken = default
)
{
var now = _timeProvider.GetUtcNow();
RefreshResponseImpl(cachedResponse, now, expiration: now + DefaultRefreshExpiration);
return ValueTask.CompletedTask;
}
public ValueTask RefreshResponseAsync(
HttpResponseMessage cachedResponse,
HttpResponseMessage notModifiedResponse,
CancellationToken cancellationToken = default
)
{
if (notModifiedResponse.StatusCode != HttpStatusCode.NotModified)
{
throw new ArgumentException(
"The response must be a 304 NOT MODIFIED response.",
nameof(notModifiedResponse)
);
}
var now = _timeProvider.GetUtcNow();
var expiration = notModifiedResponse.GetExpiration(now) ?? (now + DefaultRefreshExpiration);
RefreshResponseImpl(cachedResponse, now, expiration);
return ValueTask.CompletedTask;
}
private void RefreshResponseImpl(
HttpResponseMessage cachedResponse,
DateTimeOffset now,
DateTimeOffset expiration
)
{
var request = cachedResponse.RequestMessage!;
var responseKey = _cacheKeyComputer.ComputeKey(request, new(CacheType.Shared));
if (responseKey is null)
{
return;
}
var fileInfo = FindJsonFile(responseKey);
if (fileInfo is null)
{
return;
}
var filename = FileName.FromFileInfo(fileInfo);
filename.Refresh(fileInfo, now);
filename.SetExpiration(fileInfo, expiration);
if (filename.IsVariationFile)
{
// If the file is a variation file, we need to refresh the actual response as well
var variation = Variation.FromResponseMessage(cachedResponse);
responseKey = _cacheKeyComputer.ComputeKey(request, variation);
if (responseKey is null)
{
return;
}
fileInfo = FindJsonFile(responseKey, filename.EtagHash);
if (fileInfo is null)
{
return;
}
filename = FileName.FromFileInfo(fileInfo);
if (!filename.IsMetadataFile)
{
return;
}
filename.Refresh(fileInfo, now);
filename.SetExpiration(fileInfo, expiration);
}
}
private FileInfo? FindJsonFile(string key)
{
var hash = Hash.ComputeHash(key);
// Rely on that the file name includes the "modified" timestamp right after the hash
return _rootDirectory.EnumerateFiles($"{hash}_*.json").MaxBy(x => x.Name);
}
private FileInfo? FindJsonFile(string key, string? etagHash)
{
var hash = Hash.ComputeHash(key);
// Rely on that the file name includes the "modified" timestamp right after the hash
return _rootDirectory
.EnumerateFiles($"{hash}_*_{etagHash ?? ""}.*.json")
.MaxBy(x => x.Name);
}
public void Clear()
{
foreach (var fileInfo in _rootDirectory.GetFiles("*.json", SearchOption.AllDirectories))
{
var fileName = FileName.FromFileInfo(fileInfo);
if (fileName.IsMetadataFile)
{
var filePair = ResponseFilePair.FromMetadataFileInfo(fileInfo);
filePair.TryDelete();
}
else if (fileName.IsVariationFile)
{
var variationFile = VariationFile.FromVariationFileInfo(fileInfo);
variationFile.TryDelete();
}
}
RemoveOrphanedResponseFiles(force: true);
}
public void Purge()
{
// Only sweep temp files that are old enough that they cannot still be part of an in-flight
// SetResponse/MakePermanent operation. Without this guard the timer could delete a temp file
// while it is being written or moved into place.
var staleTempBefore = _timeProvider.GetUtcNow().AddMinutes(-30).UtcDateTime;
var files = Enumerable.Concat(
_rootDirectory
.GetFiles("*.json")
.OrderByDescending(x => x.LastAccessTimeUtc)
.Skip(MaxEntries),
_tempDirectory.GetFiles("*.json").Where(x => x.CreationTimeUtc < staleTempBefore)
);
foreach (var fileInfo in files)
{
var fileName = FileName.FromFileInfo(fileInfo);
if (fileName.IsMetadataFile)
{
var filePair = ResponseFilePair.FromMetadataFileInfo(fileInfo);
filePair.TryDelete();
}
else if (fileName.IsVariationFile)
{
var variationFile = VariationFile.FromVariationFileInfo(fileInfo);
variationFile.TryDelete();
}
}
RemoveOrphanedResponseFiles(force: false);
}
private void RemoveOrphanedResponseFiles(bool force)
{
var removeBefore = force ? DateTime.MaxValue : _timeProvider.GetUtcNow().AddMinutes(-30);
// Track unpaired files: response FileName -> (metadataFileInfo, responseFileInfo)
// When a metadata file is seen first, we store (metadataFileInfo, null).
// When a response file is seen first, we store (null, responseFileInfo).
// When the pair is matched, the entry is removed.
var unpaired =
new Dictionary<FileName, (FileInfo? MetadataFileInfo, FileInfo? ResponseFileInfo)>();
foreach (var fileInfo in _rootDirectory.GetFiles("*.*", SearchOption.AllDirectories))
{
var fileName = FileName.FromFileInfo(fileInfo);
if (fileName.IsMetadataFile)
{
var responseFileName = fileName.ToResponseFileName();
if (
unpaired.TryGetValue(responseFileName, out var existing)
&& existing.ResponseFileInfo is not null
)
{
// Response file was already iterated - pair is complete
unpaired.Remove(responseFileName);
}
else
{
// Response file is not yet iterated
unpaired[responseFileName] = (fileInfo, null);
}
}
else if (fileName.IsResponseFile)
{
if (
unpaired.TryGetValue(fileName, out var existing)
&& existing.MetadataFileInfo is not null
)
{
// Metadata file was already iterated - pair is complete
unpaired.Remove(fileName);
}
else
{
unpaired[fileName] = (null, fileInfo);
}
}
}
foreach (var (metadataFileInfo, responseFileInfo) in unpaired.Values)
{
// It may be that we have just moved the response from temp to here, and that the
// metadata is about to follow, see ResponseFilePair.TryMakePermanent().
// In that case, we must not consider the file as orphaned if it was created recently.
var fileInfo = metadataFileInfo ?? responseFileInfo!;
if (fileInfo.CreationTimeUtc >= removeBefore)
{
continue;
}
try
{
if (responseFileInfo is not null)
{
responseFileInfo.Delete();
}
else if (metadataFileInfo is not null)
{
// Metadata file exists without its response file - clean it up
var filePair = ResponseFilePair.FromMetadataFileInfo(metadataFileInfo);
filePair.TryDelete();
}
}
catch { }
}
}
public virtual ValueTask DisposeAsync()
{
GC.SuppressFinalize(this);
return _timer.DisposeAsync();
}
public virtual void Dispose()
{
GC.SuppressFinalize(this);
_timer.Dispose();
}
}