Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions src/BuiltInTools/DotNetDeltaApplier/AgentReporter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.Extensions.HotReload;

internal sealed class AgentReporter
{
private readonly List<(string message, AgentMessageSeverity severity)> _log = [];

public void Report(string message, AgentMessageSeverity severity)
{
_log.Add((message, severity));
}

public IReadOnlyCollection<(string message, AgentMessageSeverity severity)> GetAndClearLogEntries(ResponseLoggingLevel level)
{
lock (_log)
{
var filteredLog = (level != ResponseLoggingLevel.Verbose)
? _log.Where(static entry => entry.severity != AgentMessageSeverity.Verbose)
: _log;

var log = filteredLog.ToArray();
_log.Clear();
return log;
}
}
}
237 changes: 60 additions & 177 deletions src/BuiltInTools/DotNetDeltaApplier/HotReloadAgent.cs

Large diffs are not rendered by default.

239 changes: 239 additions & 0 deletions src/BuiltInTools/DotNetDeltaApplier/MetadataUpdateHandlerInvoker.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,239 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Reflection;

namespace Microsoft.Extensions.HotReload;

/// <summary>
/// Finds and invokes metadata update handlers.
/// </summary>
internal sealed class MetadataUpdateHandlerInvoker(AgentReporter reporter)
{
internal sealed class RegisteredActions(IReadOnlyList<Action<Type[]?>> clearCache, IReadOnlyList<Action<Type[]?>> updateApplication)
{
public void Invoke(Type[] updatedTypes)
{
foreach (var action in clearCache)
{
action(updatedTypes);
}

foreach (var action in updateApplication)
{
action(updatedTypes);
}
}

/// <summary>
/// For testing.
/// </summary>
internal IEnumerable<Action<Type[]?>> ClearCache => clearCache;

/// <summary>
/// For testing.
/// </summary>
internal IEnumerable<Action<Type[]?>> UpdateApplication => updateApplication;
}

private const string ClearCacheHandlerName = "ClearCache";
private const string UpdateApplicationHandlerName = "UpdateApplication";

private RegisteredActions? _actions;

/// <summary>
/// Call when a new assembly is loaded.
/// </summary>
internal void Clear()
=> Interlocked.Exchange(ref _actions, null);

/// <summary>
/// Invokes all registerd handlers.
/// </summary>
internal void Invoke(Type[] updatedTypes)
{
try
{
// Defer discovering metadata updata handlers until after hot reload deltas have been applied.
// This should give enough opportunity for AppDomain.GetAssemblies() to be sufficiently populated.
var actions = _actions;
if (actions == null)
{
Interlocked.CompareExchange(ref _actions, GetMetadataUpdateHandlerActions(), null);
actions = _actions;
}

reporter.Report("Invoking metadata update handlers.", AgentMessageSeverity.Verbose);

actions.Invoke(updatedTypes);

reporter.Report("Deltas applied.", AgentMessageSeverity.Verbose);
}
catch (Exception e)
{
reporter.Report(e.ToString(), AgentMessageSeverity.Warning);
}
}

private IEnumerable<Type> GetHandlerTypes()
{
// We need to execute MetadataUpdateHandlers in a well-defined order. For v1, the strategy that is used is to topologically
// sort assemblies so that handlers in a dependency are executed before the dependent (e.g. the reflection cache action
// in System.Private.CoreLib is executed before System.Text.Json clears its own cache.)
// This would ensure that caches and updates more lower in the application stack are up to date
// before ones higher in the stack are recomputed.
var sortedAssemblies = TopologicalSort(AppDomain.CurrentDomain.GetAssemblies());

foreach (var assembly in sortedAssemblies)
{
foreach (var attr in TryGetCustomAttributesData(assembly))
{
// Look up the attribute by name rather than by type. This would allow netstandard targeting libraries to
// define their own copy without having to cross-compile.
if (attr.AttributeType.FullName != "System.Reflection.Metadata.MetadataUpdateHandlerAttribute")
{
continue;
}

IList<CustomAttributeTypedArgument> ctorArgs = attr.ConstructorArguments;
if (ctorArgs.Count != 1 ||
ctorArgs[0].Value is not Type handlerType)
{
reporter.Report($"'{attr}' found with invalid arguments.", AgentMessageSeverity.Warning);
continue;
}

yield return handlerType;
}
}
}

public RegisteredActions GetMetadataUpdateHandlerActions()
=> GetMetadataUpdateHandlerActions(GetHandlerTypes());

/// <summary>
/// Internal for testing.
/// </summary>
internal RegisteredActions GetMetadataUpdateHandlerActions(IEnumerable<Type> handlerTypes)
Copy link
Member Author

@tmat tmat Sep 24, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just moved and refactored.

{
var clearCacheActions = new List<Action<Type[]?>>();
var updateApplicationActions = new List<Action<Type[]?>>();

foreach (var handlerType in handlerTypes)
{
bool methodFound = false;

if (GetUpdateMethod(handlerType, ClearCacheHandlerName) is MethodInfo clearCache)
{
clearCacheActions.Add(CreateAction(clearCache));
methodFound = true;
}

if (GetUpdateMethod(handlerType, UpdateApplicationHandlerName) is MethodInfo updateApplication)
{
updateApplicationActions.Add(CreateAction(updateApplication));
methodFound = true;
}

if (!methodFound)
{
reporter.Report(
$"Expected to find a static method '{ClearCacheHandlerName}' or '{UpdateApplicationHandlerName}' on type '{handlerType.AssemblyQualifiedName}' but neither exists.",
AgentMessageSeverity.Warning);
}
}

return new RegisteredActions(clearCacheActions, updateApplicationActions);

Action<Type[]?> CreateAction(MethodInfo update)
{
var action = (Action<Type[]?>)update.CreateDelegate(typeof(Action<Type[]?>));
return types =>
{
try
{
action(types);
}
catch (Exception ex)
{
reporter.Report($"Exception from '{action}': {ex}", AgentMessageSeverity.Warning);
}
};
}

MethodInfo? GetUpdateMethod(Type handlerType, string name)
{
if (handlerType.GetMethod(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static, binder: null, new[] { typeof(Type[]) }, modifiers: null) is MethodInfo updateMethod &&
updateMethod.ReturnType == typeof(void))
{
return updateMethod;
}

foreach (MethodInfo method in handlerType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))
{
if (method.Name == name)
{
reporter.Report($"Type '{handlerType}' has method '{method}' that does not match the required signature.", AgentMessageSeverity.Warning);
break;
}
}

return null;
}
}

private IList<CustomAttributeData> TryGetCustomAttributesData(Assembly assembly)
{
try
{
return assembly.GetCustomAttributesData();
}
catch (Exception e)
{
// In cross-platform scenarios, such as debugging in VS through WSL, Roslyn
// runs on Windows, and the agent runs on Linux. Assemblies accessible to Windows
// may not be available or loaded on linux (such as WPF's assemblies).
// In such case, we can ignore the assemblies and continue enumerating handlers for
// the rest of the assemblies of current domain.
reporter.Report($"'{assembly.FullName}' is not loaded ({e.Message})", AgentMessageSeverity.Verbose);
return [];
}
}

/// <summary>
/// Internal for testing.
/// </summary>
internal static List<Assembly> TopologicalSort(Assembly[] assemblies)
{
var sortedAssemblies = new List<Assembly>(assemblies.Length);

var visited = new HashSet<string>(StringComparer.Ordinal);

foreach (var assembly in assemblies)
{
Visit(assemblies, assembly, sortedAssemblies, visited);
}

static void Visit(Assembly[] assemblies, Assembly assembly, List<Assembly> sortedAssemblies, HashSet<string> visited)
{
var assemblyIdentifier = assembly.GetName().Name!;
if (!visited.Add(assemblyIdentifier))
{
return;
}

foreach (var dependencyName in assembly.GetReferencedAssemblies())
{
var dependency = Array.Find(assemblies, a => a.GetName().Name == dependencyName.Name);
if (dependency is not null)
{
Visit(assemblies, dependency, sortedAssemblies, visited);
}
}

sortedAssemblies.Add(assembly);
}

return sortedAssemblies;
}
}
71 changes: 23 additions & 48 deletions src/BuiltInTools/DotNetDeltaApplier/StartupHook.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,9 @@

internal sealed class StartupHook
{
private static readonly bool s_logDeltaClientMessages = Environment.GetEnvironmentVariable(EnvironmentVariables.Names.HotReloadDeltaClientLogMessages) == "1";
private static readonly bool s_logToStandardOutput = Environment.GetEnvironmentVariable(EnvironmentVariables.Names.HotReloadDeltaClientLogMessages) == "1";
private static readonly string s_namedPipeName = Environment.GetEnvironmentVariable(EnvironmentVariables.Names.DotnetWatchHotReloadNamedPipeName);
private static readonly string s_targetProcessPath = Environment.GetEnvironmentVariable(EnvironmentVariables.Names.DotnetWatchHotReloadTargetProcessPath);
#if DEBUG
private static readonly string s_logFile = Path.Combine(Path.GetTempPath(), $"HotReload_{s_namedPipeName}.log");
#endif

/// <summary>
/// Invoked by the runtime when the containing assembly is listed in DOTNET_STARTUP_HOOKS.
Expand All @@ -36,22 +33,37 @@ public static void Initialize()

Log($"Loaded into process: {processPath}");

#if DEBUG
Log($"Log path: {s_logFile}");
#endif
ClearHotReloadEnvironmentVariables();

Task.Run(async () =>
_ = Task.Run(async () =>
{
using var hotReloadAgent = new HotReloadAgent(Log);
Log($"Connecting to hot-reload server");

const int TimeOutMS = 5000;

using var pipeClient = new NamedPipeClientStream(".", s_namedPipeName, PipeDirection.InOut, PipeOptions.CurrentUserOnly | PipeOptions.Asynchronous);
try
{
await ReceiveDeltas(hotReloadAgent);
await pipeClient.ConnectAsync(TimeOutMS);
Log("Connected.");
}
catch (TimeoutException)
{
Log($"Failed to connect in {TimeOutMS}ms.");
return;
}

using var agent = new HotReloadAgent(pipeClient, Log);
try
{
await agent.ReceiveDeltasAsync();
}
catch (Exception ex)
{
Log(ex.Message);
}

Log("Stopped received delta updates. Server is no longer connected.");
});
}

Expand Down Expand Up @@ -81,50 +93,13 @@ internal static string RemoveCurrentAssembly(string environment)
return string.Join(Path.PathSeparator, updatedValues);
}

public static async Task ReceiveDeltas(HotReloadAgent hotReloadAgent)
{
Log($"Connecting to hot-reload server");

const int TimeOutMS = 5000;

using var pipeClient = new NamedPipeClientStream(".", s_namedPipeName, PipeDirection.InOut, PipeOptions.CurrentUserOnly | PipeOptions.Asynchronous);
try
{
await pipeClient.ConnectAsync(TimeOutMS);
Log("Connected.");
}
catch (TimeoutException)
{
Log($"Failed to connect in {TimeOutMS}ms.");
return;
}

var initPayload = new ClientInitializationPayload(hotReloadAgent.Capabilities);
Log("Writing capabilities: " + initPayload.Capabilities);
initPayload.Write(pipeClient);

while (pipeClient.IsConnected)
{
var update = await UpdatePayload.ReadAsync(pipeClient, default);
Log("Attempting to apply deltas.");

hotReloadAgent.ApplyDeltas(update.Deltas);
pipeClient.WriteByte(UpdatePayload.ApplySuccessValue);
}

Log("Stopped received delta updates. Server is no longer connected.");
}

private static void Log(string message)
{
if (s_logDeltaClientMessages)
if (s_logToStandardOutput)
{
Console.ForegroundColor = ConsoleColor.DarkGray;
Console.WriteLine($"dotnet watch 🕵️ [{s_namedPipeName}] {message}");
Console.ResetColor();
#if DEBUG
File.AppendAllText(s_logFile, message + Environment.NewLine);
#endif
}
}
}
6 changes: 6 additions & 0 deletions src/BuiltInTools/dotnet-watch/EnvironmentOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics;
using Microsoft.Extensions.Tools.Internal;

namespace Microsoft.DotNet.Watcher
{
Expand All @@ -11,6 +12,11 @@ internal enum TestFlags
None = 0,
RunningAsTest = 1 << 0,
MockBrowser = 1 << 1,

/// <summary>
/// Elevates the severity of <see cref="MessageDescriptor.WaitingForChanges"/> from <see cref="MessageSeverity.Output"/>.
/// </summary>
ElevateWaitingForChangesMessageSeverity = 1 << 2,
}

internal sealed record EnvironmentOptions(
Expand Down
Loading
Loading