Skip to content

Commit

Permalink
Merge pull request #743 from jimmylewis/goalstate
Browse files Browse the repository at this point in the history
Introduce LibraryInstallationGoalState
  • Loading branch information
phil-allen-msft committed May 20, 2024
2 parents b603e16 + d53986e commit 419abd9
Show file tree
Hide file tree
Showing 15 changed files with 555 additions and 128 deletions.
23 changes: 22 additions & 1 deletion src/LibraryManager.Contracts/FileHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -374,13 +374,25 @@ public static bool IsUnderRootDirectory(string filePath, string rootDirectory)
&& normalizedFilePath.StartsWith(normalizedRootDirectory, StringComparison.OrdinalIgnoreCase);
}

internal static string NormalizePath(string path)
/// <summary>
/// Normalizes the path string so it can be easily compared.
/// </summary>
/// <remarks>
/// Result will be lowercase and have any trailing slashes removed.
/// </remarks>
public static string NormalizePath(string path)
{
if (string.IsNullOrEmpty(path))
{
return path;
}

// If the path is a URI, we don't want to normalize it
if (IsHttpUri(path))
{
return path;
}

// net451 does not have the OSPlatform apis to determine if the OS is windows or not.
// This also does not handle the fact that MacOS can be configured to be either sensitive or insenstive
// to the casing.
Expand All @@ -394,5 +406,14 @@ internal static string NormalizePath(string path)

return Path.GetFullPath(path).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
}

/// <summary>
/// Determines if the path is an HTTP or HTTPS Uri
/// </summary>
public static bool IsHttpUri(string path)
{
return Uri.TryCreate(path, UriKind.Absolute, out Uri uri)
&& (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps);
}
}
}
5 changes: 5 additions & 0 deletions src/LibraryManager.Contracts/IProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,5 +66,10 @@ public interface IProvider
/// </summary>
/// <param name="library"></param>
string GetSuggestedDestination(ILibrary library);

/// <summary>
/// Gets the goal state of the library installation. Does not imply actual installation.
/// </summary>
Task<OperationResult<LibraryInstallationGoalState>> GetInstallationGoalStateAsync(ILibraryInstallationState installationState, CancellationToken cancellationToken);
}
}
64 changes: 64 additions & 0 deletions src/LibraryManager.Contracts/LibraryInstallationGoalState.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// 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.Collections.Generic;
using System.IO;

namespace Microsoft.Web.LibraryManager.Contracts
{
/// <summary>
/// Represents a goal state of deployed files mapped to their sources from the local cache
/// </summary>
public class LibraryInstallationGoalState
{
/// <summary>
/// Initialize a new goal state from the desired installation state.
/// </summary>
public LibraryInstallationGoalState(ILibraryInstallationState installationState, Dictionary<string, string> installedFiles)
{
InstallationState = installationState;
InstalledFiles = installedFiles;
}

/// <summary>
/// The ILibraryInstallationState that this goal state was computed from.
/// </summary>
public ILibraryInstallationState InstallationState { get; }

/// <summary>
/// Mapping from destination file to source file
/// </summary>
public IDictionary<string, string> InstalledFiles { get; }

/// <summary>
/// Returns whether the goal is in an achieved state - that is, all files are up to date.
/// </summary>
/// <remarks>
/// This is intended to serve as a fast check compared to restoring the files.
/// If there isn't a faster way to verify that a file is up to date, this method should
/// return false to indicate that a restore can't be skipped.
/// </remarks>
public bool IsAchieved()
{
foreach (KeyValuePair<string, string> kvp in InstalledFiles)
{
// If the source file is a remote Uri, we have no way to determine if it matches the installed file.
// So we will always reinstall the library in this case.
if (FileHelpers.IsHttpUri(kvp.Value))
{
return false;
}

var destinationFile = new FileInfo(kvp.Key);
var cacheFile = new FileInfo(kvp.Value);

if (!destinationFile.Exists || !cacheFile.Exists || !FileHelpers.AreFilesUpToDate(destinationFile, cacheFile))
{
return false;
}
}

return true;
}
}
}
10 changes: 8 additions & 2 deletions src/LibraryManager.Contracts/PredefinedErrors.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ namespace Microsoft.Web.LibraryManager.Contracts
public static class PredefinedErrors
{
/// <summary>
/// Represents an unhandled exception that occured in the provider.
/// Represents an unhandled exception that occurred in the provider.
/// </summary>
/// <remarks>
/// An <see cref="IProvider.InstallAsync"/> should never throw and this error
/// should be used as when catching generic exeptions.
/// should be used as when catching generic exceptions.
/// </remarks>
/// <returns>The error code LIB000</returns>
public static IError UnknownException()
Expand Down Expand Up @@ -198,6 +198,12 @@ public static IError DuplicateLibrariesInManifest(string duplicateLibrary)
public static IError FileNameMustNotBeEmpty(string libraryId)
=> new Error("LIB020", string.Format(Text.ErrorFilePathIsEmpty, libraryId));

/// <summary>
/// A library mapping does not have a destination specified
/// </summary>
public static IError DestinationNotSpecified(string libraryId)
=> new Error("LIB021", string.Format(Text.ErrorDestinationNotSpecified, libraryId));

/// <summary>
/// The manifest must specify a version
/// </summary>
Expand Down
9 changes: 9 additions & 0 deletions src/LibraryManager.Contracts/Resources/Text.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

57 changes: 30 additions & 27 deletions src/LibraryManager.Contracts/Resources/Text.resx
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
Expand All @@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
Expand Down Expand Up @@ -187,6 +187,9 @@ Valid files are {2}</value>
<data name="ErrorFilePathIsEmpty" xml:space="preserve">
<value>The library "{0}" cannot specify a file with an empty name</value>
</data>
<data name="ErrorDestinationNotSpecified" xml:space="preserve">
<value>The "{0}" library is missing a destination.</value>
</data>
<data name="ErrorMissingManifestVersion" xml:space="preserve">
<value>The Library Manager manifest must specify a version.</value>
</data>
Expand Down
58 changes: 23 additions & 35 deletions src/LibraryManager/Manifest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -204,8 +204,6 @@ public Manifest Clone()
string destination,
CancellationToken cancellationToken)
{
ILibraryOperationResult result;

var desiredState = new LibraryInstallationState()
{
Name = libraryName,
Expand Down Expand Up @@ -236,14 +234,14 @@ public Manifest Clone()
return conflictResults;
}

result = await provider.InstallAsync(desiredState, cancellationToken).ConfigureAwait(false);
ILibraryOperationResult installResult = await provider.InstallAsync(desiredState, cancellationToken);

if (result.Success)
if (installResult.Success)
{
AddLibrary(desiredState);
}

return result;
return installResult;
}

private ILibraryInstallationState SetDefaultProviderIfNeeded(LibraryInstallationState desiredState)
Expand Down Expand Up @@ -510,7 +508,7 @@ private async Task<IEnumerable<FileIdentifier>> GetAllManifestFilesWithVersionsA
return allFiles.SelectMany(f => f).Distinct();
}

return new List<FileIdentifier>();
return new List<FileIdentifier>();
}

private async Task<IEnumerable<FileIdentifier>> GetFilesWithVersionsAsync(ILibraryInstallationState state)
Expand Down Expand Up @@ -567,41 +565,31 @@ private async Task<IEnumerable<FileIdentifier>> GetFilesWithVersionsAsync(ILibra
try
{
IProvider provider = _dependencies.GetProvider(state.ProviderId);
ILibraryOperationResult updatedStateResult = await provider.UpdateStateAsync(state, CancellationToken.None).ConfigureAwait(false);

if (updatedStateResult.Success)
OperationResult<LibraryInstallationGoalState> getGoalState = await provider.GetInstallationGoalStateAsync(state, cancellationToken).ConfigureAwait(false);
if (!getGoalState.Success)
{
List<string> filesToDelete = new List<string>();
state = updatedStateResult.InstallationState;

foreach (string file in state.Files)
return new LibraryOperationResult(state, [.. getGoalState.Errors])
{
var url = new Uri(file, UriKind.RelativeOrAbsolute);

if (!url.IsAbsoluteUri)
{
string relativePath = Path.Combine(state.DestinationPath, file).Replace('\\', '/');
filesToDelete.Add(relativePath);
}
}
Cancelled = getGoalState.Cancelled,
};
}

bool success = true;
if (deleteFilesFunction != null)
{
success = await deleteFilesFunction.Invoke(filesToDelete).ConfigureAwait(false);
}
LibraryInstallationGoalState goalState = getGoalState.Result;

if (success)
{
return LibraryOperationResult.FromSuccess(updatedStateResult.InstallationState);
}
else
{
return LibraryOperationResult.FromError(PredefinedErrors.CouldNotDeleteLibrary(libraryId));
}
bool success = true;
if (deleteFilesFunction != null)
{
success = await deleteFilesFunction.Invoke(goalState.InstalledFiles.Keys).ConfigureAwait(false);
}

return updatedStateResult;
if (success)
{
return LibraryOperationResult.FromSuccess(goalState.InstallationState);
}
else
{
return LibraryOperationResult.FromError(PredefinedErrors.CouldNotDeleteLibrary(libraryId));
}
}
catch (OperationCanceledException)
{
Expand Down

0 comments on commit 419abd9

Please sign in to comment.