Skip to content

Commit 31bd744

Browse files
authored
Send process id from the agent to the client in initial response. (#56245)
1 parent 307e75e commit 31bd744

15 files changed

Lines changed: 156 additions & 58 deletions

File tree

‎src/Dotnet.Watch/HotReloadAgent.Host/Listener.cs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
namespace Microsoft.DotNet.HotReload;
1212

13-
internal sealed class Listener(Transport transport, IHotReloadAgent agent, Action<string> log)
13+
internal sealed class Listener(Transport transport, IHotReloadAgent agent, int processId, Action<string> log)
1414
{
1515
/// <summary>
1616
/// Messages to the client sent after the initial <see cref="ClientInitializationResponse"/> is sent
@@ -72,7 +72,8 @@ private async Task InitializeAsync(CancellationToken cancellationToken)
7272
{
7373
agent.Reporter.Report("Writing capabilities: " + agent.Capabilities, AgentMessageSeverity.Verbose);
7474

75-
await transport.SendAsync(new ClientInitializationResponse(agent.Capabilities), cancellationToken).ConfigureAwait(false);
75+
var response = new ClientInitializationResponse(processId, capabilities: agent.Capabilities);
76+
await transport.SendAsync(response, cancellationToken).ConfigureAwait(false);
7677

7778
// Apply updates made before this process was launched to avoid executing unupdated versions of the affected modules.
7879

‎src/Dotnet.Watch/HotReloadAgent.Host/StartupHook.cs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,9 @@ public static void Initialize()
3636
{
3737
var processPath = Environment.GetCommandLineArgs().FirstOrDefault();
3838
var processDir = Path.GetDirectoryName(processPath)!;
39+
var processId = Environment.ProcessId;
3940

40-
Log($"Loaded into process: {processPath} ({typeof(StartupHook).Assembly.Location})");
41+
Log($"Loaded into process {processId}: {processPath} ({typeof(StartupHook).Assembly.Location})");
4142

4243
var transport = Transport.TryCreate(Log);
4344

@@ -93,7 +94,7 @@ async Task SendAndForgetAsync()
9394
}
9495
});
9596

96-
listener = new Listener(transport, agent, Log);
97+
listener = new Listener(transport, agent, processId, Log);
9798

9899
// fire and forget:
99100
_ = listener.Listen(CancellationToken.None);

‎src/Dotnet.Watch/HotReloadAgent.PipeRpc/NamedPipeContract.cs‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -144,17 +144,19 @@ public async ValueTask WriteAsync(Stream stream, CancellationToken cancellationT
144144
}
145145
}
146146

147-
internal readonly struct ClientInitializationResponse(string capabilities) : IResponse
147+
internal readonly struct ClientInitializationResponse(int processId, string capabilities) : IResponse
148148
{
149-
private const byte Version = 0;
149+
private const byte Version = 1;
150150

151151
public ResponseType Type => ResponseType.InitializationResponse;
152152

153153
public string Capabilities { get; } = capabilities;
154+
public int ProcessId { get; } = processId;
154155

155156
public async ValueTask WriteAsync(Stream stream, CancellationToken cancellationToken)
156157
{
157158
await stream.WriteAsync(Version, cancellationToken);
159+
await stream.WriteAsync(ProcessId, cancellationToken);
158160
await stream.WriteAsync(Capabilities, cancellationToken);
159161
}
160162

@@ -166,8 +168,9 @@ public static async ValueTask<ClientInitializationResponse> ReadAsync(Stream str
166168
throw new NotSupportedException($"Unsupported version {version}.");
167169
}
168170

171+
var processId = await stream.ReadInt32Async(cancellationToken);
169172
var capabilities = await stream.ReadStringAsync(cancellationToken);
170-
return new ClientInitializationResponse(capabilities);
173+
return new ClientInitializationResponse(processId, capabilities);
171174
}
172175
}
173176

‎src/Dotnet.Watch/HotReloadClient/DefaultHotReloadClient.cs‎

Lines changed: 51 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,25 @@
1616

1717
namespace Microsoft.DotNet.HotReload;
1818

19-
internal sealed class DefaultHotReloadClient(ILogger logger, ILogger agentLogger, string startupHookPath, bool handlesStaticAssetUpdates, ClientTransport transport)
19+
/// <summary>
20+
/// Default Hot Reload client. Used for local app or an app running on a device.
21+
/// </summary>
22+
/// <param name="logger">Logger for client messages.</param>
23+
/// <param name="agentLogger">Logger for messages received from the agent.</param>
24+
/// <param name="startupHookPath">Path to the startup hook to be loaded to the target process.</param>
25+
/// <param name="transport">Transport layer (e.g. named pipe or web socket)</param>
26+
/// <param name="handlesStaticAssetUpdates">True if the agent handles static asset updates. False if static assets are updated via browser refresh server.</param>
27+
/// <param name="hasRemoteAgent">True if the agent runs on a remote machine (device).</param>
28+
internal sealed class DefaultHotReloadClient(
29+
ILogger logger,
30+
ILogger agentLogger,
31+
string startupHookPath,
32+
ClientTransport transport,
33+
bool handlesStaticAssetUpdates,
34+
bool hasRemoteAgent)
2035
: HotReloadClient(logger, agentLogger)
2136
{
22-
private Task<ImmutableArray<string>>? _capabilitiesTask;
37+
private Task<HotReloadAgentInfo>? _connectedAgentTask;
2338
private bool _managedCodeUpdateFailedOrCancelled;
2439

2540
// The status of the last update response.
@@ -40,9 +55,9 @@ public override void InitiateConnection(IReadOnlyCollection<(string name, string
4055
// It is important to establish the connection (WaitForConnectionAsync) before we return,
4156
// otherwise the client wouldn't be able to connect.
4257
// However, we don't want to wait for the task to complete, so that we can start the client process.
43-
_capabilitiesTask = ConnectAsync();
58+
_connectedAgentTask = ConnectAsync();
4459

45-
async Task<ImmutableArray<string>> ConnectAsync()
60+
async Task<HotReloadAgentInfo> ConnectAsync()
4661
{
4762
try
4863
{
@@ -52,34 +67,49 @@ async Task<ImmutableArray<string>> ConnectAsync()
5267
var initResponse = await transport.ReadAsync(cancellationToken);
5368
if (initResponse == null)
5469
{
55-
return [];
70+
// connection dropped before we could read the initialization response.
71+
return HotReloadAgentInfo.Unavailable;
5672
}
5773

5874
using var r = initResponse.Value;
5975
if (r.Type != ResponseType.InitializationResponse)
6076
{
6177
Logger.LogError("Expected initialization response, got: {ResponseType}", r.Type);
62-
return [];
78+
return HotReloadAgentInfo.Unavailable;
6379
}
6480

65-
var capabilities = (await ClientInitializationResponse.ReadAsync(r.Data, cancellationToken)).Capabilities;
81+
var response = await ClientInitializationResponse.ReadAsync(r.Data, cancellationToken);
6682

67-
if (string.IsNullOrEmpty(capabilities))
83+
// Remote process id has no meaning on the client's machine:
84+
var localProcessId = hasRemoteAgent ? (int?)null : response.ProcessId;
85+
86+
if (response.Capabilities is "")
6887
{
69-
return [];
88+
// Hot Reload not supported by the runtime:
89+
Logger.Log(LogEvents.Capabilities, "");
90+
91+
return new HotReloadAgentInfo
92+
{
93+
ManagedCodeUpdateCapabilities = [],
94+
LocalProcessId = localProcessId
95+
};
7096
}
7197

72-
var result = AddImplicitCapabilities(capabilities.Split(' '));
98+
var effectiveCapabilities = AddImplicitCapabilities(response.Capabilities.Split(' '));
7399

74-
Logger.Log(LogEvents.Capabilities, string.Join(" ", result));
100+
Logger.Log(LogEvents.Capabilities, string.Join(" ", effectiveCapabilities));
75101

76102
// Initialize process:
77103
await SetEnvironmentVariablesAsync(environmentVariables, cancellationToken);
78104

79105
// fire and forget:
80106
_ = ListenForResponsesAsync(cancellationToken);
81107

82-
return result;
108+
return new HotReloadAgentInfo
109+
{
110+
ManagedCodeUpdateCapabilities = effectiveCapabilities,
111+
LocalProcessId = localProcessId
112+
};
83113
}
84114
catch (Exception e) when (e is not OperationCanceledException)
85115
{
@@ -90,7 +120,7 @@ async Task<ImmutableArray<string>> ConnectAsync()
90120
Logger.LogError("Failed to read capabilities: {Message}", e.Message);
91121
}
92122

93-
return [];
123+
return HotReloadAgentInfo.Unavailable;
94124
}
95125
}
96126
}
@@ -137,15 +167,15 @@ private async Task ListenForResponsesAsync(CancellationToken cancellationToken)
137167
}
138168
}
139169

140-
[MemberNotNull(nameof(_capabilitiesTask))]
141-
private Task<ImmutableArray<string>> GetCapabilitiesTask()
142-
=> _capabilitiesTask ?? throw new InvalidOperationException();
170+
[MemberNotNull(nameof(_connectedAgentTask))]
171+
private Task<HotReloadAgentInfo> GetAgentConnectedTask()
172+
=> _connectedAgentTask ?? throw new InvalidOperationException();
143173

144-
[MemberNotNull(nameof(_capabilitiesTask))]
174+
[MemberNotNull(nameof(_connectedAgentTask))]
145175
private void RequireReadyForUpdates()
146176
{
147177
// should only be called after connection has been created:
148-
_ = GetCapabilitiesTask();
178+
_ = GetAgentConnectedTask();
149179
}
150180

151181
public override void ConfigureLaunchEnvironment(IDictionary<string, string> environmentBuilder)
@@ -159,10 +189,10 @@ public override void ConfigureLaunchEnvironment(IDictionary<string, string> envi
159189
}
160190

161191
public override Task WaitForConnectionEstablishedAsync(CancellationToken cancellationToken)
162-
=> GetCapabilitiesTask();
192+
=> GetAgentConnectedTask();
163193

164-
public override Task<ImmutableArray<string>> GetUpdateCapabilitiesAsync(CancellationToken cancellationToken)
165-
=> GetCapabilitiesTask();
194+
public override Task<HotReloadAgentInfo> GetConnectedAgentInfoAsync(CancellationToken cancellationToken)
195+
=> GetAgentConnectedTask();
166196

167197
private ResponseLoggingLevel ResponseLoggingLevel
168198
=> Logger.IsEnabled(LogLevel.Debug) ? ResponseLoggingLevel.Verbose : ResponseLoggingLevel.WarningsAndErrors;
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
4+
using System;
5+
using System.Collections.Generic;
6+
using System.Collections.Immutable;
7+
using System.Text;
8+
9+
namespace Microsoft.DotNet.HotReload;
10+
11+
/// <summary>
12+
/// Information
13+
/// </summary>
14+
internal readonly struct HotReloadAgentInfo
15+
{
16+
internal static readonly HotReloadAgentInfo Unavailable = new() { ManagedCodeUpdateCapabilities = [] };
17+
18+
/// <summary>
19+
/// Capabilities of the runtime the agent is loaded to.
20+
/// </summary>
21+
public required ImmutableArray<string> ManagedCodeUpdateCapabilities { get; init; }
22+
23+
/// <summary>
24+
/// The id of the process the agent is loaded to, if available and the agent runs on the same machine as the client.
25+
/// Null if the agent runs on a device or in the browser.
26+
/// </summary>
27+
public int? LocalProcessId { get; init; }
28+
}

‎src/Dotnet.Watch/HotReloadClient/HotReloadClient.cs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -64,10 +64,10 @@ protected static ImmutableArray<string> AddImplicitCapabilities(IEnumerable<stri
6464
public abstract Task WaitForConnectionEstablishedAsync(CancellationToken cancellationToken);
6565

6666
/// <summary>
67-
/// Returns update capabilities of the target process.
67+
/// Returns information about the connected agent.
6868
/// </summary>
6969
/// <param name="cancellationToken">Cancellation token. The cancellation should trigger on process terminatation.</param>
70-
public abstract Task<ImmutableArray<string>> GetUpdateCapabilitiesAsync(CancellationToken cancellationToken);
70+
public abstract Task<HotReloadAgentInfo> GetConnectedAgentInfoAsync(CancellationToken cancellationToken);
7171

7272
/// <summary>
7373
/// Returns a task that applies managed code updates to the target process.
@@ -111,7 +111,7 @@ public static void ReportLogEntry(ILogger logger, string message, AgentMessageSe
111111

112112
protected async Task<IReadOnlyList<HotReloadManagedCodeUpdate>> FilterApplicableUpdatesAsync(ImmutableArray<HotReloadManagedCodeUpdate> updates, CancellationToken cancellationToken)
113113
{
114-
var availableCapabilities = await GetUpdateCapabilitiesAsync(cancellationToken);
114+
var agentInfo = await GetConnectedAgentInfoAsync(cancellationToken);
115115
var applicableUpdates = new List<HotReloadManagedCodeUpdate>();
116116

117117
foreach (var update in updates)
@@ -122,7 +122,7 @@ protected async Task<IReadOnlyList<HotReloadManagedCodeUpdate>> FilterApplicable
122122
continue;
123123
}
124124

125-
if (update.RequiredCapabilities.Except(availableCapabilities).Any())
125+
if (update.RequiredCapabilities.Except(agentInfo.ManagedCodeUpdateCapabilities).Any())
126126
{
127127
// required capability not available:
128128
_frozenModules.Add(update.ModuleId);

‎src/Dotnet.Watch/HotReloadClient/HotReloadClients.cs‎

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -110,24 +110,19 @@ internal async ValueTask WaitForConnectionEstablishedAsync(CancellationToken can
110110
}
111111

112112
/// <param name="cancellationToken">Cancellation token. The cancellation should trigger on process terminatation.</param>
113-
public async ValueTask<ImmutableArray<string>> GetUpdateCapabilitiesAsync(CancellationToken cancellationToken)
113+
public async ValueTask<ImmutableArray<HotReloadAgentInfo>> GetConnectedAgentsInfoAsync(CancellationToken cancellationToken)
114114
{
115115
if (!IsManagedAgentSupported)
116116
{
117-
// empty capabilities will cause rude edit ENC0097: NotSupportedByRuntime.
118117
return [];
119118
}
120119

121120
if (clients is [var singleClient])
122121
{
123-
return await singleClient.GetUpdateCapabilitiesAsync(cancellationToken);
122+
return [await singleClient.GetConnectedAgentInfoAsync(cancellationToken)];
124123
}
125124

126-
var results = await Task.WhenAll(clients.Select(c => c.GetUpdateCapabilitiesAsync(cancellationToken)));
127-
128-
// Allow updates that are supported by at least one process.
129-
// When applying changes we will filter updates applied to a specific process based on their required capabilities.
130-
return [.. results.SelectMany(r => r).Distinct(StringComparer.Ordinal).OrderBy(c => c)];
125+
return [.. await Task.WhenAll(clients.Select(c => c.GetConnectedAgentInfoAsync(cancellationToken)))];
131126
}
132127

133128
/// <summary>
@@ -225,4 +220,13 @@ public async ValueTask<Task> ApplyStaticAssetUpdatesAsync(ImmutableArray<HotRelo
225220
/// <param name="cancellationToken">Cancellation token. The cancellation should trigger on process terminatation.</param>
226221
public ValueTask ReportCompilationErrorsInApplicationAsync(ImmutableArray<string> compilationErrors, CancellationToken cancellationToken)
227222
=> browserRefreshServer?.ReportCompilationErrorsInBrowserAsync(compilationErrors, cancellationToken) ?? ValueTask.CompletedTask;
223+
224+
/// <summary>
225+
/// Returns union of capabilities reported by each agent.
226+
/// When applying changes the updates applied to a specific process will be filtered based on their required capabilities.
227+
/// </summary>
228+
public static ImmutableArray<string> UnionCapabilities(ImmutableArray<HotReloadAgentInfo> agentInfos)
229+
=> agentInfos is [var singleInfo]
230+
? singleInfo.ManagedCodeUpdateCapabilities
231+
: [.. agentInfos.SelectMany(r => r.ManagedCodeUpdateCapabilities).Distinct(StringComparer.Ordinal).OrderBy(c => c)];
228232
}

‎src/Dotnet.Watch/HotReloadClient/Web/WebAssemblyHotReloadClient.cs‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -90,8 +90,12 @@ public override async Task WaitForConnectionEstablishedAsync(CancellationToken c
9090
// Wait for the browser connection to be established. Currently we need the browser to be running in order to apply changes.
9191
=> await browserRefreshServer.WaitForClientConnectionAsync(cancellationToken);
9292

93-
public override Task<ImmutableArray<string>> GetUpdateCapabilitiesAsync(CancellationToken cancellationToken)
94-
=> Task.FromResult(_capabilities);
93+
public override Task<HotReloadAgentInfo> GetConnectedAgentInfoAsync(CancellationToken cancellationToken)
94+
=> Task.FromResult(new HotReloadAgentInfo
95+
{
96+
ManagedCodeUpdateCapabilities = _capabilities,
97+
LocalProcessId = null
98+
});
9599

96100
public override async Task<Task<bool>> ApplyManagedCodeUpdatesAsync(ImmutableArray<HotReloadManagedCodeUpdate> updates, CancellationToken applyOperationCancellationToken, CancellationToken cancellationToken)
97101
{

‎src/Dotnet.Watch/Watch/AppModels/BlazorWebAssemblyHostedAppModel.cs‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,13 @@ protected override ImmutableArray<HotReloadClient> CreateManagedClients(ILogger
2727
return
2828
[
2929
CreateWebAssemblyClient(clientLogger, agentLogger, browserRefreshServer, clientProject),
30-
new DefaultHotReloadClient(clientLogger, agentLogger, GetStartupHookPath(serverProject), handlesStaticAssetUpdates: false, new NamedPipeClientTransport(clientLogger))
30+
new DefaultHotReloadClient(
31+
clientLogger,
32+
agentLogger,
33+
GetStartupHookPath(serverProject),
34+
new NamedPipeClientTransport(clientLogger),
35+
handlesStaticAssetUpdates: false,
36+
hasRemoteAgent: false)
3137
];
3238
}
3339
}

‎src/Dotnet.Watch/Watch/AppModels/DefaultAppModel.cs‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,13 @@ internal sealed class DefaultAppModel(ProjectGraphNode project) : HotReloadAppMo
1515
public override ValueTask<HotReloadClients> CreateClientsAsync(ILogger clientLogger, ILogger agentLogger, CancellationToken cancellationToken)
1616
=> new(new HotReloadClients(
1717
clients: IsManagedAgentSupported(project, clientLogger)
18-
? [new DefaultHotReloadClient(clientLogger, agentLogger, GetStartupHookPath(project), handlesStaticAssetUpdates: true, new NamedPipeClientTransport(clientLogger))]
18+
? [new DefaultHotReloadClient(
19+
clientLogger,
20+
agentLogger,
21+
GetStartupHookPath(project),
22+
new NamedPipeClientTransport(clientLogger),
23+
handlesStaticAssetUpdates: true,
24+
hasRemoteAgent: false)]
1925
: [],
2026
browserRefreshServer: null,
2127
useRefreshServerToApplyStaticAssets: false));

0 commit comments

Comments
 (0)