Skip to content
This repository was archived by the owner on Nov 22, 2018. It is now read-only.

Commit 5c3dd5c

Browse files
committed
Refactor to remove duplication
1 parent 5ee36d0 commit 5c3dd5c

File tree

3 files changed

+37
-94
lines changed

3 files changed

+37
-94
lines changed

src/Microsoft.AspNetCore.ResponseCaching/Internal/Interfaces/IResponseCache.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,9 @@ namespace Microsoft.AspNetCore.ResponseCaching.Internal
99
public interface IResponseCache
1010
{
1111
IResponseCacheEntry Get(string key);
12-
void Set(string key, IResponseCacheEntry entry, TimeSpan validFor);
1312
Task<IResponseCacheEntry> GetAsync(string key);
13+
14+
void Set(string key, IResponseCacheEntry entry, TimeSpan validFor);
1415
Task SetAsync(string key, IResponseCacheEntry entry, TimeSpan validFor);
1516
}
1617
}

src/Microsoft.AspNetCore.ResponseCaching/ResponseCachingMiddleware.cs

Lines changed: 34 additions & 87 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,6 @@ public class ResponseCachingMiddleware
2525
private readonly IResponseCachingPolicyProvider _policyProvider;
2626
private readonly IResponseCache _cache;
2727
private readonly IResponseCachingKeyProvider _keyProvider;
28-
private readonly Action<object> _onStartingCallback;
29-
private readonly Func<object, Task> _onStartingCallbackAsync;
3028

3129
public ResponseCachingMiddleware(
3230
RequestDelegate next,
@@ -67,8 +65,6 @@ public ResponseCachingMiddleware(
6765
_policyProvider = policyProvider;
6866
_cache = cache;
6967
_keyProvider = keyProvider;
70-
_onStartingCallback = state => OnResponseStarting((ResponseCachingContext)state);
71-
_onStartingCallbackAsync = state => OnResponseStartingAsync((ResponseCachingContext)state);
7268
}
7369

7470
public async Task Invoke(HttpContext httpContext)
@@ -218,10 +214,11 @@ internal async Task<bool> TryServeFromCacheAsync(ResponseCachingContext context)
218214
return false;
219215
}
220216

221-
internal void FinalizeCacheHeaders(ResponseCachingContext context)
217+
private bool FinalizeCacheHeadersShouldStoreVaryByEntry(ResponseCachingContext context)
222218
{
223219
if (_policyProvider.IsResponseCacheable(context))
224220
{
221+
var storeVaryByEntry = false;
225222
context.ShouldCacheResponse = true;
226223

227224
// Create the cache entry now
@@ -261,7 +258,7 @@ internal void FinalizeCacheHeaders(ResponseCachingContext context)
261258

262259
// Always overwrite the CachedVaryByRules to update the expiry information
263260
_logger.LogVaryByRulesUpdated(normalizedVaryHeaders, normalizedVaryQueryKeys);
264-
_cache.Set(context.BaseKey, context.CachedVaryByRules, context.CachedResponseValidFor);
261+
storeVaryByEntry = true;
265262

266263
context.StorageVaryKey = _keyProvider.CreateStorageVaryByKey(context);
267264
}
@@ -289,89 +286,31 @@ internal void FinalizeCacheHeaders(ResponseCachingContext context)
289286
context.CachedResponse.Headers.Add(header);
290287
}
291288
}
289+
290+
return storeVaryByEntry;
292291
}
293292
else
294293
{
295294
context.ResponseCachingStream.DisableBuffering();
295+
return false;
296296
}
297297
}
298298

299-
internal async Task FinalizeCacheHeadersAsync(ResponseCachingContext context)
299+
internal void FinalizeCacheHeaders(ResponseCachingContext context)
300300
{
301-
if (_policyProvider.IsResponseCacheable(context))
301+
if (FinalizeCacheHeadersShouldStoreVaryByEntry(context))
302302
{
303-
context.ShouldCacheResponse = true;
304-
305-
// Create the cache entry now
306-
var response = context.HttpContext.Response;
307-
var varyHeaders = new StringValues(response.Headers.GetCommaSeparatedValues(HeaderNames.Vary));
308-
var varyQueryKeys = new StringValues(context.HttpContext.Features.Get<IResponseCachingFeature>()?.VaryByQueryKeys);
309-
context.CachedResponseValidFor = context.ResponseSharedMaxAge ??
310-
context.ResponseMaxAge ??
311-
(context.ResponseExpires - context.ResponseTime.Value) ??
312-
DefaultExpirationTimeSpan;
313-
314-
// Generate a base key if none exist
315-
if (string.IsNullOrEmpty(context.BaseKey))
316-
{
317-
context.BaseKey = _keyProvider.CreateBaseKey(context);
318-
}
319-
320-
// Check if any vary rules exist
321-
if (!StringValues.IsNullOrEmpty(varyHeaders) || !StringValues.IsNullOrEmpty(varyQueryKeys))
322-
{
323-
// Normalize order and casing of vary by rules
324-
var normalizedVaryHeaders = GetOrderCasingNormalizedStringValues(varyHeaders);
325-
var normalizedVaryQueryKeys = GetOrderCasingNormalizedStringValues(varyQueryKeys);
326-
327-
// Update vary rules if they are different
328-
if (context.CachedVaryByRules == null ||
329-
!StringValues.Equals(context.CachedVaryByRules.QueryKeys, normalizedVaryQueryKeys) ||
330-
!StringValues.Equals(context.CachedVaryByRules.Headers, normalizedVaryHeaders))
331-
{
332-
context.CachedVaryByRules = new CachedVaryByRules
333-
{
334-
VaryByKeyPrefix = FastGuid.NewGuid().IdString,
335-
Headers = normalizedVaryHeaders,
336-
QueryKeys = normalizedVaryQueryKeys
337-
};
338-
}
339-
340-
// Always overwrite the CachedVaryByRules to update the expiry information
341-
_logger.LogVaryByRulesUpdated(normalizedVaryHeaders, normalizedVaryQueryKeys);
342-
await _cache.SetAsync(context.BaseKey, context.CachedVaryByRules, context.CachedResponseValidFor);
343-
344-
context.StorageVaryKey = _keyProvider.CreateStorageVaryByKey(context);
345-
}
346-
347-
// Ensure date header is set
348-
if (!context.ResponseDate.HasValue)
349-
{
350-
context.ResponseDate = context.ResponseTime.Value;
351-
// Setting the date on the raw response headers.
352-
context.HttpContext.Response.Headers[HeaderNames.Date] = HeaderUtilities.FormatDate(context.ResponseDate.Value);
353-
}
354-
355-
// Store the response on the state
356-
context.CachedResponse = new CachedResponse
357-
{
358-
Created = context.ResponseDate.Value,
359-
StatusCode = context.HttpContext.Response.StatusCode,
360-
Headers = new HeaderDictionary()
361-
};
362-
363-
foreach (var header in context.HttpContext.Response.Headers)
364-
{
365-
if (!string.Equals(header.Key, HeaderNames.Age, StringComparison.OrdinalIgnoreCase))
366-
{
367-
context.CachedResponse.Headers.Add(header);
368-
}
369-
}
303+
_cache.Set(context.BaseKey, context.CachedVaryByRules, context.CachedResponseValidFor);
370304
}
371-
else
305+
}
306+
307+
internal Task FinalizeCacheHeadersAsync(ResponseCachingContext context)
308+
{
309+
if (FinalizeCacheHeadersShouldStoreVaryByEntry(context))
372310
{
373-
context.ResponseCachingStream.DisableBuffering();
311+
return _cache.SetAsync(context.BaseKey, context.CachedVaryByRules, context.CachedResponseValidFor);
374312
}
313+
return TaskCache.CompletedTask;
375314
}
376315

377316
internal async Task FinalizeCacheBodyAsync(ResponseCachingContext context)
@@ -404,30 +343,33 @@ internal async Task FinalizeCacheBodyAsync(ResponseCachingContext context)
404343
}
405344
}
406345

407-
internal void OnResponseStarting(ResponseCachingContext context)
346+
private bool OnResponseStartingShouldFinalizeHeaders(ResponseCachingContext context)
408347
{
409348
if (!context.ResponseStarted)
410349
{
411350
context.ResponseStarted = true;
412351
context.ResponseTime = _options.SystemClock.UtcNow;
413352

353+
return true;
354+
}
355+
return false;
356+
}
357+
358+
internal void OnResponseStarting(ResponseCachingContext context)
359+
{
360+
if (OnResponseStartingShouldFinalizeHeaders(context))
361+
{
414362
FinalizeCacheHeaders(context);
415363
}
416364
}
417365

418366
internal Task OnResponseStartingAsync(ResponseCachingContext context)
419367
{
420-
if (!context.ResponseStarted)
368+
if (OnResponseStartingShouldFinalizeHeaders(context))
421369
{
422-
context.ResponseStarted = true;
423-
context.ResponseTime = _options.SystemClock.UtcNow;
424-
425370
return FinalizeCacheHeadersAsync(context);
426371
}
427-
else
428-
{
429-
return TaskCache.CompletedTask;
430-
}
372+
return TaskCache.CompletedTask;
431373
}
432374

433375
internal static void AddResponseCachingFeature(HttpContext context)
@@ -443,7 +385,12 @@ internal void ShimResponseStream(ResponseCachingContext context)
443385
{
444386
// Shim response stream
445387
context.OriginalResponseStream = context.HttpContext.Response.Body;
446-
context.ResponseCachingStream = new ResponseCachingStream(context.OriginalResponseStream, _options.MaximumBodySize, StreamUtilities.BodySegmentSize, () => OnResponseStarting(context), async () => await OnResponseStartingAsync(context));
388+
context.ResponseCachingStream = new ResponseCachingStream(
389+
context.OriginalResponseStream,
390+
_options.MaximumBodySize,
391+
StreamUtilities.BodySegmentSize,
392+
() => OnResponseStarting(context),
393+
async () => await OnResponseStartingAsync(context));
447394
context.HttpContext.Response.Body = context.ResponseCachingStream;
448395

449396
// Shim IHttpSendFileFeature

src/Microsoft.AspNetCore.ResponseCaching/Streams/ResponseCachingStream.cs

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -47,11 +47,6 @@ public override long Position
4747
}
4848
}
4949

50-
private async Task OnWriteAsync()
51-
{
52-
await _onStartingCallbackAsync();
53-
}
54-
5550
internal Stream GetBufferStream()
5651
{
5752
if (!BufferingEnabled)
@@ -115,7 +110,7 @@ public override void Write(byte[] buffer, int offset, int count)
115110
{
116111
try
117112
{
118-
_onStartingCallbackAsync().Wait();
113+
_onStartingCallback();
119114
_innerStream.Write(buffer, offset, count);
120115
}
121116
catch

0 commit comments

Comments
 (0)