Skip to content

Commit

Permalink
Merge pull request #600 from jimmylewis/cacheMetadata
Browse files Browse the repository at this point in the history
Add caching for provider metadata

This affects the scenarios where we need to fetch the latest library versions or the file lists for a given library. For Cdnjs, because they offer a full catalog, it also affects that.

When fetching versions (or catalog), we want to have live data if possible, as new versions (or packages) can be released. These operations will initially attempt a web request, and if it fails, fall back to the cached contents on disk (if any). Note that there is now a 1-day cache lifetime applied to the initial request, which should cut down on repetitive traffic.

When fetching file lists, we assume that released libraries are static. In this case, we first check for the information on disk, and then fallback to a web request if it's missing. There is no lifetime applied in this case. If the library is mutated, a user will have to clear the cache to get the updated metadata for the library (but, they'd have to do the same to get updated versions of any cached library assets as well).

This resolves #598, which should in turn help with some of the reliability issues reported in #370.
  • Loading branch information
jimmylewis authored Sep 15, 2020
2 parents 9243107 + 7ecebc2 commit c44defa
Show file tree
Hide file tree
Showing 13 changed files with 700 additions and 369 deletions.
17 changes: 9 additions & 8 deletions src/LibraryManager.Contracts/Caching/ICacheService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,22 @@ namespace Microsoft.Web.LibraryManager.Contracts.Caching
public interface ICacheService
{
/// <summary>
/// Returns the provider's catalog from the provided Url to cacheFile
/// Gets the contents from the specified URL, or if the request fails then from a locally cached copy
/// </summary>
/// <param name="url">Url to the provider catalog</param>
/// <param name="cacheFile">Where to store the provider catalog within the cache</param>
/// <param name="url">The URL to request</param>
/// <param name="cacheFile">The locally cached file</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns></returns>
Task<string> GetCatalogAsync(string url, string cacheFile, CancellationToken cancellationToken);
Task<string> GetContentsFromUriWithCacheFallbackAsync(string url, string cacheFile, CancellationToken cancellationToken);

/// <summary>
/// Returns library metadata from provided Url to cacheFile
/// Gets the contents of a local cache file, or if the file does not exist then requests it from the specified URL
/// </summary>
/// <param name="url">Url to the library metadata</param>
/// <param name="cacheFile">Where to store the metadata file within the cache</param>
/// <param name="cacheFile">The locally cached file</param>
/// <param name="url">The URL to request</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns></returns>
Task<string> GetMetadataAsync(string url, string cacheFile, CancellationToken cancellationToken);
/// <exception cref="ResourceDownloadException">Thrown when the file doesn't exist and the resource download fails</exception>
Task<string> GetContentsFromCachedFileWithWebRequestFallbackAsync(string cacheFile, string url, CancellationToken cancellationToken);
}
}
78 changes: 46 additions & 32 deletions src/LibraryManager/CacheService/CacheService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@ namespace Microsoft.Web.LibraryManager
/// </summary>
public class CacheService : ICacheService
{
// TO DO: Move these expirations to the provider
private const int CatalogExpiresAfterDays = 1;
private const int MetadataExpiresAfterDays = 1;
private const int DefaultCacheExpiresAfterDays = 1;
private const int MaxConcurrentDownloads = 10;

private readonly IWebRequestHandler _requestHandler;
Expand Down Expand Up @@ -52,30 +50,6 @@ public static string CacheFolder
}
}

/// <summary>
/// Returns the provider's catalog from the provided Url to cacheFile
/// </summary>
/// <param name="url"></param>
/// <param name="cacheFile"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<string> GetCatalogAsync(string url, string cacheFile, CancellationToken cancellationToken)
{
return await GetResourceAsync(url, cacheFile, CatalogExpiresAfterDays, cancellationToken);
}

/// <summary>
/// Returns library metadata from provided Url to cacheFile
/// </summary>
/// <param name="url"></param>
/// <param name="cacheFile"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<string> GetMetadataAsync(string url, string cacheFile, CancellationToken cancellationToken)
{
return await GetResourceAsync(url, cacheFile, MetadataExpiresAfterDays, cancellationToken);
}

/// <summary>
/// Downloads a resource from specified url to a destination file
/// </summary>
Expand All @@ -94,9 +68,9 @@ private async Task DownloadToFileAsync(string url, string fileName, int attempts
{
try
{
using (Stream libraryStream = await _requestHandler.GetStreamAsync(url, cancellationToken))
using (Stream libraryStream = await _requestHandler.GetStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
await FileHelpers.SafeWriteToFileAsync(fileName, libraryStream, cancellationToken);
await FileHelpers.SafeWriteToFileAsync(fileName, libraryStream, cancellationToken).ConfigureAwait(false);
break;
}
}
Expand All @@ -109,7 +83,7 @@ private async Task DownloadToFileAsync(string url, string fileName, int attempts
}
}

await Task.Delay(200);
await Task.Delay(200).ConfigureAwait(false);
}
}

Expand All @@ -130,16 +104,56 @@ private async Task<string> GetResourceAsync(string url, string localFile, int ex
/// </summary>
public async Task RefreshCacheAsync(IEnumerable<CacheFileMetadata> librariesCacheMetadata, ILogger logger, CancellationToken cancellationToken)
{
await ParallelUtility.ForEachAsync(DownloadFileIfNecessaryAsync, MaxConcurrentDownloads, librariesCacheMetadata, cancellationToken);
await ParallelUtility.ForEachAsync(DownloadFileIfNecessaryAsync, MaxConcurrentDownloads, librariesCacheMetadata, cancellationToken).ConfigureAwait(false);

async Task DownloadFileIfNecessaryAsync(CacheFileMetadata metadata)
{
if (!File.Exists(metadata.DestinationPath))
{
logger.Log(string.Format(Resources.Text.DownloadingFile, metadata.Source), LogLevel.Operation);
await DownloadToFileAsync(metadata.Source, metadata.DestinationPath, attempts: 5, cancellationToken: cancellationToken);
await DownloadToFileAsync(metadata.Source, metadata.DestinationPath, attempts: 5, cancellationToken: cancellationToken).ConfigureAwait(false);
}
}
}

/// <inheritdoc />
public async Task<string> GetContentsFromUriWithCacheFallbackAsync(string url, string cacheFile, CancellationToken cancellationToken)
{
string contents;
try
{
contents = await GetResourceAsync(url, cacheFile, DefaultCacheExpiresAfterDays, cancellationToken).ConfigureAwait(false);
}
catch (ResourceDownloadException)
{
// TODO: Log telemetry
if (File.Exists(cacheFile))
{
contents = await FileHelpers.ReadFileAsTextAsync(cacheFile, cancellationToken).ConfigureAwait(false);
}
else
{
throw;
}
}

return contents;
}

/// <inheritdoc />
public async Task<string> GetContentsFromCachedFileWithWebRequestFallbackAsync(string cacheFile, string url, CancellationToken cancellationToken)
{
string contents;
if (File.Exists(cacheFile))
{
contents = await FileHelpers.ReadFileAsTextAsync(cacheFile, cancellationToken).ConfigureAwait(false);
}
else
{
contents = await GetResourceAsync(url, cacheFile, DefaultCacheExpiresAfterDays, cancellationToken).ConfigureAwait(false);
}

return contents;
}
}
}
17 changes: 4 additions & 13 deletions src/LibraryManager/Providers/Cdnjs/CdnjsCatalog.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ internal class CdnjsCatalog : ILibraryCatalog
{
// TO DO: These should become Provider properties to be passed to CacheService
private const string FileName = "cache.json";
private const string RemoteApiUrl = "https://aka.ms/g8irvu";
private const string MetaPackageUrlFormat = "https://api.cdnjs.com/libraries/{0}"; // https://aka.ms/goycwu/{0}
public const string CatalogUrl = "https://api.cdnjs.com/libraries?fields=name,description,version";
public const string MetaPackageUrlFormat = "https://api.cdnjs.com/libraries/{0}"; // https://aka.ms/goycwu/{0}

private readonly string _cacheFile;
private readonly CdnjsProvider _provider;
Expand Down Expand Up @@ -245,7 +245,7 @@ private async Task<bool> EnsureCatalogAsync(CancellationToken cancellationToken)

try
{
string json = await _cacheService.GetCatalogAsync(RemoteApiUrl, _cacheFile, cancellationToken).ConfigureAwait(false);
string json = await _cacheService.GetContentsFromUriWithCacheFallbackAsync(CatalogUrl, _cacheFile, cancellationToken).ConfigureAwait(false);

if (string.IsNullOrWhiteSpace(json))
{
Expand All @@ -256,11 +256,6 @@ private async Task<bool> EnsureCatalogAsync(CancellationToken cancellationToken)

return _libraryGroups != null;
}
catch (ResourceDownloadException)
{
_provider.HostInteraction.Logger.Log(string.Format(Resources.Text.FailedToDownloadCatalog, _provider.Id), LogLevel.Operation);
return false;
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex);
Expand All @@ -283,7 +278,7 @@ private async Task<IEnumerable<Asset>> GetAssetsAsync(string groupName, Cancella

try
{
string json = await _cacheService.GetMetadataAsync(url, localFile, cancellationToken).ConfigureAwait(false);
string json = await _cacheService.GetContentsFromUriWithCacheFallbackAsync(url, localFile, cancellationToken).ConfigureAwait(false);

if (!string.IsNullOrEmpty(json))
{
Expand All @@ -295,10 +290,6 @@ private async Task<IEnumerable<Asset>> GetAssetsAsync(string groupName, Cancella
}
}
}
catch (ResourceDownloadException)
{
throw;
}
catch (Exception)
{
throw new InvalidLibraryException(groupName, _provider.Id);
Expand Down
37 changes: 26 additions & 11 deletions src/LibraryManager/Providers/Unpkg/UnpkgCatalog.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Web.LibraryManager.Contracts;
using Microsoft.Web.LibraryManager.Helpers;
using Microsoft.Web.LibraryManager.Contracts.Caching;
using Microsoft.Web.LibraryManager.LibraryNaming;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Microsoft.Web.LibraryManager.Providers.Unpkg
Expand All @@ -25,16 +27,18 @@ internal class UnpkgCatalog : ILibraryCatalog
private readonly string _providerId;
private readonly ILibraryNamingScheme _libraryNamingScheme;
private readonly ILogger _logger;
private readonly IWebRequestHandler _webRequestHandler;
private readonly ICacheService _cacheService;
private readonly string _cacheFolder;

public UnpkgCatalog(string providerId, ILibraryNamingScheme namingScheme, ILogger logger, IWebRequestHandler webRequestHandler, INpmPackageInfoFactory packageInfoFactory, INpmPackageSearch packageSearch)
public UnpkgCatalog(string providerId, ILibraryNamingScheme namingScheme, ILogger logger, INpmPackageInfoFactory packageInfoFactory, INpmPackageSearch packageSearch, ICacheService cacheService, string cacheFolder)
{
_packageInfoFactory = packageInfoFactory;
_packageSearch = packageSearch;
_providerId = providerId;
_libraryNamingScheme = namingScheme;
_logger = logger;
_webRequestHandler = webRequestHandler;
_cacheService = cacheService;
_cacheFolder = cacheFolder;
}

public async Task<string> GetLatestVersion(string libraryName, bool includePreReleases, CancellationToken cancellationToken)
Expand All @@ -44,8 +48,13 @@ public async Task<string> GetLatestVersion(string libraryName, bool includePreRe
try
{
string latestLibraryVersionUrl = string.Format(LatestLibraryVersonUrl, libraryName);
string latestCacheFile = Path.Combine(_cacheFolder, libraryName, $"{LatestVersionTag}.json");

JObject packageObject = await _webRequestHandler.GetJsonObjectViaGetAsync(latestLibraryVersionUrl, cancellationToken);
string latestJson = await _cacheService.GetContentsFromUriWithCacheFallbackAsync(latestLibraryVersionUrl,
latestCacheFile,
cancellationToken).ConfigureAwait(false);

var packageObject = (JObject)JsonConvert.DeserializeObject(latestJson);

if (packageObject != null)
{
Expand All @@ -71,13 +80,13 @@ public async Task<ILibrary> GetLibraryAsync(string libraryName, string version,
string libraryId = _libraryNamingScheme.GetLibraryId(libraryName, version);
if (string.Equals(version, LatestVersionTag, StringComparison.Ordinal))
{
string latestVersion = await GetLatestVersion(libraryId, includePreReleases: false, cancellationToken);
string latestVersion = await GetLatestVersion(libraryId, includePreReleases: false, cancellationToken).ConfigureAwait(false);
libraryId = _libraryNamingScheme.GetLibraryId(libraryName, latestVersion);
}

try
{
IEnumerable<string> libraryFiles = await GetLibraryFilesAsync(libraryName, version, cancellationToken);
IEnumerable<string> libraryFiles = await GetLibraryFilesAsync(libraryName, version, cancellationToken).ConfigureAwait(false);

return new UnpkgLibrary
{
Expand All @@ -98,7 +107,13 @@ private async Task<IEnumerable<string>> GetLibraryFilesAsync(string libraryName,
var result = new List<string>();

string libraryFileListUrl = string.Format(LibraryFileListUrlFormat, libraryName, version);
JObject fileListObject = await _webRequestHandler.GetJsonObjectViaGetAsync(libraryFileListUrl, cancellationToken).ConfigureAwait(false);
string libraryFileListCacheFile = Path.Combine(_cacheFolder, libraryName, $"{version}-filelist.json");

string fileList = await _cacheService.GetContentsFromCachedFileWithWebRequestFallbackAsync(libraryFileListCacheFile,
libraryFileListUrl,
cancellationToken).ConfigureAwait(false);

var fileListObject = (JObject)JsonConvert.DeserializeObject(fileList);

if (fileListObject != null)
{
Expand Down Expand Up @@ -197,7 +212,7 @@ public async Task<CompletionSet> GetLibraryCompletionSetAsync(string libraryName
// library name completion
if (caretPosition < name.Length + 1)
{
IEnumerable<NpmPackageInfo> packages = await _packageSearch.GetPackageNamesAsync(libraryNameStart, CancellationToken.None);
IEnumerable<NpmPackageInfo> packages = await _packageSearch.GetPackageNamesAsync(libraryNameStart, CancellationToken.None).ConfigureAwait(false);

foreach (NpmPackageInfo packageInfo in packages)
{
Expand All @@ -219,7 +234,7 @@ public async Task<CompletionSet> GetLibraryCompletionSetAsync(string libraryName
completionSet.Start = name.Length + 1;
completionSet.Length = version.Length;

NpmPackageInfo npmPackageInfo = await _packageInfoFactory.GetPackageInfoAsync(name, CancellationToken.None);
NpmPackageInfo npmPackageInfo = await _packageInfoFactory.GetPackageInfoAsync(name, CancellationToken.None).ConfigureAwait(false);

IList<SemanticVersion> versions = npmPackageInfo.Versions.OrderByDescending(v => v).ToList();

Expand Down Expand Up @@ -259,7 +274,7 @@ public async Task<IReadOnlyList<ILibraryGroup>> SearchAsync(string term, int max

try
{
IEnumerable<NpmPackageInfo> packages = await _packageSearch.GetPackageNamesAsync(term, CancellationToken.None);
IEnumerable<NpmPackageInfo> packages = await _packageSearch.GetPackageNamesAsync(term, CancellationToken.None).ConfigureAwait(false);
IEnumerable<string> packageNames = packages.Select(p => p.Name);
libraryGroups = packageNames.Select(packageName => new UnpkgLibraryGroup(_packageInfoFactory, packageName)).ToList<ILibraryGroup>();
}
Expand Down
3 changes: 1 addition & 2 deletions src/LibraryManager/Providers/Unpkg/UnpkgProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,7 @@ public UnpkgProvider(IHostInteraction hostInteraction, CacheService cacheService

public override ILibraryCatalog GetCatalog()
{
// TODO: sort out the WebRequestHandler dependency
return _catalog ?? (_catalog = new UnpkgCatalog(Id, LibraryNamingScheme, HostInteraction.Logger, WebRequestHandler.Instance, _infoFactory, _packageSearch));
return _catalog ?? (_catalog = new UnpkgCatalog(Id, LibraryNamingScheme, HostInteraction.Logger, _infoFactory, _packageSearch, _cacheService, CacheFolder));
}

public override string LibraryIdHintText => Resources.Text.UnpkgProviderHintText;
Expand Down
Loading

0 comments on commit c44defa

Please sign in to comment.