-
Notifications
You must be signed in to change notification settings - Fork 1.1k
[wasm] General HotReload agent for WebAssembly in browser #49800
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
6e555e8
Add HotReloadAgent.WebAssembly.Browser
maraf 250d4a7
Update references
maraf 7b2bd56
Implicit reference
maraf 791a16d
Update src/BuiltInTools/HotReloadAgent.WebAssembly.Browser/WebAssembl…
maraf 98e0db0
Ship the package
maraf 7f74fb1
Feedback
maraf 662b494
Disable HotReload in tests, because we don't have the HotReload packa…
maraf 4ce0644
Disable HotReload in tests, because we don't have the HotReload packa…
maraf 0cc2cfe
Flip the check for configuration
maraf b15a02e
IsImplicitlyDefined and PrivateAssets attributes on the PackageReference
maraf 93abbd3
Fix usage outside of Blazor - need to set _internal object as well
maraf 2e3934e
Remove PrivateAssets becase we need the script to propagate to the re…
maraf c799096
Disable HotReload in tests, because we don't have the HotReload packa…
maraf acbf36c
Include shipping packages in HelixCorrelationPayload
maraf c724500
Revert disable HotReload in tests
maraf f503e27
Update baselines
maraf 6c93ba8
Update baselines
maraf d9b03a4
The newest runtime didn't land yet. Revert back to previous boot sche…
maraf 141a57c
Update baselines
maraf 6edb0a0
Update baselines
maraf 7ec9a3f
Exclude modules manifest
maraf 50f73fa
Disable HotReload in SWA integration tests, because of fingerprinted …
maraf File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
26 changes: 26 additions & 0 deletions
26
.../HotReloadAgent.WebAssembly.Browser/Microsoft.DotNet.HotReload.WebAssembly.Browser.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
<Project Sdk="Microsoft.NET.Sdk.Razor"> | ||
|
||
<PropertyGroup> | ||
<TargetFramework>$(SdkTargetFramework)</TargetFramework> | ||
<GenerateDocumentationFile>false</GenerateDocumentationFile> | ||
<GenerateDependencyFile>false</GenerateDependencyFile> | ||
<LangVersion>preview</LangVersion> | ||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> | ||
|
||
<!-- NuGet --> | ||
<IsPackable>true</IsPackable> | ||
<IsShipping>true</IsShipping> | ||
<IsShippingPackage>true</IsShippingPackage> | ||
<PackageId>Microsoft.DotNet.HotReload.WebAssembly.Browser</PackageId> | ||
<Description>HotReload package for WebAssembly</Description> | ||
<!-- Remove once https://github.com/NuGet/Home/issues/8583 is fixed --> | ||
<NoWarn>$(NoWarn);NU5128</NoWarn> | ||
</PropertyGroup> | ||
|
||
<Import Project="..\HotReloadAgent\Microsoft.DotNet.HotReload.Agent.projitems" Label="Shared" /> | ||
<Import Project="..\HotReloadAgent.Data\Microsoft.DotNet.HotReload.Agent.Data.projitems" Label="Shared" /> | ||
|
||
maraf marked this conversation as resolved.
Show resolved
Hide resolved
|
||
<ItemGroup> | ||
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" Key="$(MoqPublicKey)" /> | ||
</ItemGroup> | ||
</Project> |
178 changes: 178 additions & 0 deletions
178
src/BuiltInTools/HotReloadAgent.WebAssembly.Browser/WebAssemblyHotReload.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,178 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System.ComponentModel; | ||
using System.Diagnostics.CodeAnalysis; | ||
using System.Globalization; | ||
using System.Linq; | ||
using System.Net.Http; | ||
using System.Reflection.Metadata; | ||
using System.Runtime.InteropServices.JavaScript; | ||
using System.Runtime.Versioning; | ||
using System.Text.Json; | ||
using System.Text.Json.Serialization; | ||
|
||
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member | ||
|
||
namespace Microsoft.DotNet.HotReload.WebAssembly.Browser; | ||
|
||
/// <summary> | ||
/// Contains methods called by interop. Intended for framework use only, not supported for use in application | ||
/// code. | ||
/// </summary> | ||
[EditorBrowsable(EditorBrowsableState.Never)] | ||
[UnconditionalSuppressMessage( | ||
"Trimming", | ||
"IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", | ||
Justification = "Hot Reload does not support trimming")] | ||
internal static partial class WebAssemblyHotReload | ||
{ | ||
/// <summary> | ||
/// For framework use only. | ||
/// </summary> | ||
public readonly struct LogEntry | ||
{ | ||
public string Message { get; init; } | ||
public int Severity { get; init; } | ||
} | ||
|
||
/// <summary> | ||
/// For framework use only. | ||
/// </summary> | ||
internal sealed class Update | ||
{ | ||
public int Id { get; set; } | ||
public Delta[] Deltas { get; set; } = default!; | ||
} | ||
|
||
/// <summary> | ||
/// For framework use only. | ||
/// </summary> | ||
public readonly struct Delta | ||
{ | ||
public string ModuleId { get; init; } | ||
public byte[] MetadataDelta { get; init; } | ||
public byte[] ILDelta { get; init; } | ||
public byte[] PdbDelta { get; init; } | ||
public int[] UpdatedTypes { get; init; } | ||
} | ||
|
||
private static readonly JsonSerializerOptions s_jsonSerializerOptions = new(JsonSerializerDefaults.Web); | ||
|
||
private static bool s_initialized; | ||
private static HotReloadAgent? s_hotReloadAgent; | ||
|
||
[JSExport] | ||
[SupportedOSPlatform("browser")] | ||
public static async Task InitializeAsync(string baseUri) | ||
{ | ||
if (MetadataUpdater.IsSupported && Environment.GetEnvironmentVariable("__ASPNETCORE_BROWSER_TOOLS") == "true" && | ||
OperatingSystem.IsBrowser()) | ||
{ | ||
s_initialized = true; | ||
|
||
var agent = new HotReloadAgent(); | ||
|
||
var existingAgent = Interlocked.CompareExchange(ref s_hotReloadAgent, agent, null); | ||
if (existingAgent != null) | ||
{ | ||
throw new InvalidOperationException("Hot Reload agent already initialized"); | ||
} | ||
|
||
await ApplyPreviousDeltasAsync(agent, baseUri); | ||
} | ||
} | ||
|
||
private static async ValueTask ApplyPreviousDeltasAsync(HotReloadAgent agent, string baseUri) | ||
{ | ||
string errorMessage; | ||
|
||
using var client = new HttpClient() | ||
{ | ||
BaseAddress = new Uri(baseUri, UriKind.Absolute) | ||
}; | ||
|
||
try | ||
{ | ||
var response = await client.GetAsync("/_framework/blazor-hotreload"); | ||
if (response.IsSuccessStatusCode) | ||
{ | ||
var deltasJson = await response.Content.ReadAsStringAsync(); | ||
var updates = deltasJson != "" ? JsonSerializer.Deserialize<Update[]>(deltasJson, s_jsonSerializerOptions) : null; | ||
if (updates == null) | ||
{ | ||
agent.Reporter.Report($"No previous updates to apply.", AgentMessageSeverity.Verbose); | ||
return; | ||
} | ||
|
||
var i = 1; | ||
foreach (var update in updates) | ||
{ | ||
agent.Reporter.Report($"Reapplying update {i}/{updates.Length}.", AgentMessageSeverity.Verbose); | ||
|
||
agent.ApplyDeltas( | ||
update.Deltas.Select(d => new UpdateDelta(Guid.Parse(d.ModuleId, CultureInfo.InvariantCulture), d.MetadataDelta, d.ILDelta, d.PdbDelta, d.UpdatedTypes))); | ||
|
||
i++; | ||
} | ||
|
||
return; | ||
} | ||
|
||
errorMessage = $"HTTP GET '/_framework/blazor-hotreload' returned {response.StatusCode}"; | ||
} | ||
catch (Exception e) | ||
{ | ||
errorMessage = e.ToString(); | ||
} | ||
|
||
agent.Reporter.Report($"Failed to retrieve and apply previous deltas from the server: {errorMessage}", AgentMessageSeverity.Error); | ||
} | ||
|
||
private static HotReloadAgent? GetAgent() | ||
=> s_hotReloadAgent ?? (s_initialized ? throw new InvalidOperationException("Hot Reload agent not initialized") : null); | ||
|
||
private static LogEntry[] ApplyHotReloadDeltas(Delta[] deltas, int loggingLevel) | ||
{ | ||
var agent = GetAgent(); | ||
if (agent == null) | ||
{ | ||
return []; | ||
} | ||
|
||
agent.ApplyDeltas( | ||
deltas.Select(d => new UpdateDelta(Guid.Parse(d.ModuleId, CultureInfo.InvariantCulture), d.MetadataDelta, d.ILDelta, d.PdbDelta, d.UpdatedTypes))); | ||
|
||
return agent.Reporter.GetAndClearLogEntries((ResponseLoggingLevel)loggingLevel) | ||
.Select(log => new LogEntry() { Message = log.message, Severity = (int)log.severity }).ToArray(); | ||
} | ||
|
||
private static readonly WebAssemblyHotReloadJsonSerializerContext jsonContext = new(new(JsonSerializerDefaults.Web)); | ||
|
||
[JSExport] | ||
[SupportedOSPlatform("browser")] | ||
public static string GetApplyUpdateCapabilities() | ||
{ | ||
return GetAgent()?.Capabilities ?? ""; | ||
} | ||
|
||
[JSExport] | ||
[SupportedOSPlatform("browser")] | ||
public static string? ApplyHotReloadDeltas(string deltasJson, int loggingLevel) | ||
{ | ||
var deltas = JsonSerializer.Deserialize(deltasJson, jsonContext.DeltaArray); | ||
if (deltas == null) | ||
{ | ||
return null; | ||
} | ||
|
||
var result = ApplyHotReloadDeltas(deltas, loggingLevel); | ||
return result == null ? null : JsonSerializer.Serialize(result, jsonContext.LogEntryArray); | ||
} | ||
} | ||
|
||
[JsonSerializable(typeof(WebAssemblyHotReload.Delta[]))] | ||
[JsonSerializable(typeof(WebAssemblyHotReload.LogEntry[]))] | ||
internal sealed partial class WebAssemblyHotReloadJsonSerializerContext : JsonSerializerContext | ||
{ | ||
} |
36 changes: 36 additions & 0 deletions
36
....WebAssembly.Browser/wwwroot/Microsoft.DotNet.HotReload.WebAssembly.Browser.lib.module.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
export async function onRuntimeConfigLoaded(config) { | ||
// If we have 'aspnetcore-browser-refresh', configure mono runtime for HotReload. | ||
if (config.debugLevel !== 0 && globalThis.window?.document?.querySelector("script[src*='aspnetcore-browser-refresh']")) { | ||
if (!config.environmentVariables["DOTNET_MODIFIABLE_ASSEMBLIES"]) { | ||
config.environmentVariables["DOTNET_MODIFIABLE_ASSEMBLIES"] = "debug"; | ||
} | ||
if (!config.environmentVariables["__ASPNETCORE_BROWSER_TOOLS"]) { | ||
config.environmentVariables["__ASPNETCORE_BROWSER_TOOLS"] = "true"; | ||
} | ||
} | ||
|
||
// Disable HotReload built-into the Blazor WebAssembly runtime | ||
config.environmentVariables["__BLAZOR_WEBASSEMBLY_LEGACY_HOTRELOAD"] = "false"; | ||
} | ||
|
||
export async function onRuntimeReady({ getAssemblyExports }) { | ||
const exports = await getAssemblyExports("Microsoft.DotNet.HotReload.WebAssembly.Browser"); | ||
await exports.Microsoft.DotNet.HotReload.WebAssembly.Browser.WebAssemblyHotReload.InitializeAsync(document.baseURI); | ||
|
||
if (!window.Blazor) { | ||
window.Blazor = {}; | ||
|
||
if (!window.Blazor._internal) { | ||
window.Blazor._internal = {}; | ||
} | ||
} | ||
|
||
window.Blazor._internal.applyHotReloadDeltas = (deltas, loggingLevel) => { | ||
const result = exports.Microsoft.DotNet.HotReload.WebAssembly.Browser.WebAssemblyHotReload.ApplyHotReloadDeltas(JSON.stringify(deltas), loggingLevel); | ||
return result ? JSON.parse(result) : []; | ||
}; | ||
|
||
window.Blazor._internal.getApplyUpdateCapabilities = () => { | ||
return exports.Microsoft.DotNet.HotReload.WebAssembly.Browser.WebAssemblyHotReload.GetApplyUpdateCapabilities() ?? ''; | ||
}; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.