internal AssetResponse ParseJson(string json) { if (string.IsNullOrEmpty(json)) { return(null); } try { using (JsonDocument document = JsonDocument.Parse(json)) { var ck = document.RootElement.GetProperty("CacheKey").GetString(); var b = document.RootElement.GetProperty("Body").GetString(); var bytes = JsonSerializer.Deserialize <byte[]>("\"" + b + "\""); var ar = new AssetResponse(bytes, ck); var headersString = document.RootElement.GetProperty("Headers").GetRawText(); if (!string.IsNullOrEmpty(headersString)) { var headers = JsonSerializer.Deserialize <Dictionary <string, string> >(headersString); foreach (var d in headers) { ar.Headers.Add(d.Key, d.Value); } } return(ar); } } catch (Exception ex) { _logger.LogError(ex, "An error occurred parsing the AssetResponse"); return(null); } }
/// <summary> /// Builds an asset by running it through all the processors. /// </summary> public async Task<IAssetResponse> BuildAsync(IAsset asset, HttpContext context, IWebOptimizerOptions options) { string cacheKey; try { cacheKey = asset.GenerateCacheKey(context); } catch (FileNotFoundException) { _logger.LogFileNotFound(context.Request.Path); return null; } if (options.EnableMemoryCache == true && _cache.TryGetValue(cacheKey, out AssetResponse value)) { _logger.LogServedFromMemoryCache(context.Request.Path); return value; } else if (options.EnableDiskCache == true && _assetResponseCache.TryGet(asset.Route, cacheKey, out value)) { AddToCache(cacheKey, value, asset, options); return value; } else { byte[] bytes = await asset.ExecuteAsync(context, options).ConfigureAwait(false); var response = new AssetResponse(bytes, cacheKey); foreach (string name in context.Response.Headers.Keys) { response.Headers.Add(name, context.Response.Headers[name]); } if (options.AllowEmptyBundle == false && (bytes == null || bytes.Length == 0)) { return null; } AddToCache(cacheKey, response, asset, options); if (options.EnableDiskCache == true) { await _assetResponseCache.AddAsync(asset.Route, cacheKey, response).ConfigureAwait(false); } _logger.LogGeneratedOutput(context.Request.Path); return response; } }
private void AddToCache(string cacheKey, AssetResponse value, IAsset asset, IWebOptimizerOptions options) { if (options.EnableMemoryCache == true) { var cacheOptions = new MemoryCacheEntryOptions(); cacheOptions.SetSlidingExpiration(TimeSpan.FromHours(24)); foreach (string file in asset.SourceFiles) { cacheOptions.AddExpirationToken(asset.GetFileProvider(_env).Watch(file)); } _cache.Set(cacheKey, value, cacheOptions); } }
public async Task AddAsync(string bucket, string cachekey, AssetResponse assetResponse) { string name = CleanName(bucket); Directory.CreateDirectory(_options.CacheDirectory); // First delete old cached files IEnumerable <string> oldCachedFiles = Directory.EnumerateFiles(_options.CacheDirectory, name + "__*.cache"); foreach (string oldFile in oldCachedFiles) { await DeleteFileAsync(oldFile).ConfigureAwait(false); } // Then serialize to disk string json = JsonSerializer.Serialize(assetResponse); string filePath = GetPath(bucket, cachekey); await WriteFileAsync(filePath, json).ConfigureAwait(false); }
public bool TryGet(string bucket, string cachekey, out AssetResponse assetResponse) { assetResponse = null; string filePath = GetPath(bucket, cachekey); if (File.Exists(filePath)) { try { string json = File.ReadAllText(filePath); assetResponse = JsonConvert.DeserializeObject <AssetResponse>(json); } catch (Exception ex) { System.Diagnostics.Debug.Write(ex); DeleteFileAsync(filePath).GetAwaiter().GetResult(); } } return(assetResponse != null); }
/// <summary> /// Builds an asset by running it through all the processors. /// </summary> public async Task <IAssetResponse> BuildAsync(IAsset asset, HttpContext context, IWebOptimizerOptions options) { options.EnsureDefaults(_env); string cacheKey = asset.GenerateCacheKey(context); if (_cache.TryGetValue(cacheKey, out AssetResponse value)) { _logger.LogServedFromMemoryCache(context.Request.Path); return(value); } else if (AssetResponse.TryGetFromDiskCache(context.Request.Path, cacheKey, _cacheDir, out value)) { AddToCache(cacheKey, value, asset, options); return(value); } else { byte[] bytes = await asset.ExecuteAsync(context, options).ConfigureAwait(false); var response = new AssetResponse(bytes, cacheKey); foreach (string name in context.Response.Headers.Keys) { response.Headers.Add(name, context.Response.Headers[name]); } if (bytes == null || bytes.Length == 0) { return(null); } AddToCache(cacheKey, response, asset, options); await response.CacheToDiskAsync(context.Request.Path, cacheKey, _cacheDir).ConfigureAwait(false); _logger.LogGeneratedOutput(context.Request.Path); return(response); } }
public bool TryGet(string bucket, string cachekey, out AssetResponse assetResponse) { assetResponse = null; string filePath = GetPath(bucket, cachekey); if (File.Exists(filePath)) { try { string json = File.ReadAllText(filePath); assetResponse = ParseJson(json); //TODO: Simplify this when System.Text.Json is fully baked //assetResponse = JsonSerializer.Deserialize<AssetResponse>(json); } catch (Exception ex) { System.Diagnostics.Debug.Write(ex); DeleteFileAsync(filePath).GetAwaiter().GetResult(); } } return(assetResponse != null); }
public static bool TryGetFromDiskCache(string route, string cacheKey, string cacheDir, out AssetResponse response) { response = null; string name = CleanRouteName(route); string filePath = GetPath(name, cacheKey, cacheDir); if (File.Exists(filePath)) { try { string json = File.ReadAllText(filePath); response = JsonConvert.DeserializeObject <AssetResponse>(json); } catch (Exception ex) { System.Diagnostics.Debug.Write(ex); DeleteFileAsync(filePath).GetAwaiter().GetResult(); } } return(response != null); }