Skip to content
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

Browser refresh and WASM delta applier refactoring #44539

Merged
merged 7 commits into from
Nov 6, 2024
Merged
Show file tree
Hide file tree
Changes from 6 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
2 changes: 2 additions & 0 deletions src/BuiltInTools/BrowserRefresh/.editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[*.js]
indent_size = 2
11 changes: 8 additions & 3 deletions src/BuiltInTools/BrowserRefresh/BlazorHotReload.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
// Used by older versions of Microsoft.AspNetCore.Components.WebAssembly.
// For back compat only until updated ASP.NET is inserted into the SDK.

export function receiveHotReload() {
return BINDING.js_to_mono_obj(new Promise((resolve) => receiveHotReloadAsync().then(resolve(0))));
}

export async function receiveHotReloadAsync() {
const response = await fetch('/_framework/blazor-hotreload');
Copy link
Member

Choose a reason for hiding this comment

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

Can you think of any way in which the implementor of _framework/blazor-hotreload is from a different SDK version but this injected JS code?

Copy link
Member Author

@tmat tmat Nov 5, 2024

Choose a reason for hiding this comment

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

I don't think that will be a problem. We can remove this once we migrate ASP.NET to the newer API and insert it into the SDK. This is temporary so that we can make the changes incrementally.

if (response.status === 200) {
const deltas = await response.json();
if (deltas) {
const updates = await response.json();
if (updates) {
try {
deltas.forEach(d => window.Blazor._internal.applyHotReload(d.moduleId, d.metadataDelta, d.ilDelta, d.pdbDelta, d.updatedTypes));
updates.forEach(u => {
u.deltas.forEach(d => window.Blazor._internal.applyHotReload(d.moduleId, d.metadataDelta, d.ilDelta, d.pdbDelta, d.updatedTypes));
})
} catch (error) {
console.warn(error);
return;
Expand Down
95 changes: 27 additions & 68 deletions src/BuiltInTools/BrowserRefresh/BlazorWasmHotReloadMiddleware.cs
Original file line number Diff line number Diff line change
@@ -1,23 +1,36 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Globalization;
using System.Text.Json;
using Microsoft.AspNetCore.Http;
using Microsoft.Net.Http.Headers;

namespace Microsoft.AspNetCore.Watch.BrowserRefresh
{
/// <summary>
/// A middleware that manages receiving and sending deltas from a BlazorWebAssembly app.
/// This assembly is shared between Visual Studio and dotnet-watch. By putting some of the complexity
/// in here, we can avoid duplicating work in watch and VS.
///
/// Mapped to <see cref="ApplicationPaths.BlazorHotReloadMiddleware"/>.
/// </summary>
internal sealed class BlazorWasmHotReloadMiddleware
{
private readonly object @lock = new();
private readonly string EtagDiscriminator = Guid.NewGuid().ToString();
private readonly JsonSerializerOptions _jsonSerializerOptions = new()
internal sealed class Update
{
public int Id { get; set; }
public Delta[] Deltas { get; set; } = default!;
}

internal sealed class Delta
{
public string ModuleId { get; set; } = default!;
public string MetadataDelta { get; set; } = default!;
public string ILDelta { get; set; } = default!;
public string PdbDelta { get; set; } = default!;
public int[] UpdatedTypes { get; set; } = default!;
}

private static readonly JsonSerializerOptions s_jsonSerializerOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
};
Expand All @@ -26,13 +39,13 @@ public BlazorWasmHotReloadMiddleware(RequestDelegate next)
{
}

internal List<UpdateDelta> Deltas { get; } = new();
internal List<Update> Updates { get; } = [];

public Task InvokeAsync(HttpContext context)
{
// Multiple instances of the BlazorWebAssembly app could be running (multiple tabs or multiple browsers).
// We want to avoid serialize reads and writes between then
lock (@lock)
lock (Updates)
{
if (HttpMethods.IsGet(context.Request.Method))
{
Expand All @@ -54,85 +67,31 @@ public Task InvokeAsync(HttpContext context)

private async Task OnGet(HttpContext context)
{
if (Deltas.Count == 0)
if (Updates.Count == 0)
{
context.Response.StatusCode = StatusCodes.Status204NoContent;
return;
}

if (EtagMatches(context))
{
context.Response.StatusCode = StatusCodes.Status304NotModified;
return;
}

WriteETag(context);
await JsonSerializer.SerializeAsync(context.Response.Body, Deltas, _jsonSerializerOptions);
}

private bool EtagMatches(HttpContext context)
{
if (context.Request.Headers[HeaderNames.IfNoneMatch] is not { Count: 1 } ifNoneMatch)
{
return false;
}

var expected = GetETag();
return string.Equals(expected, ifNoneMatch[0], StringComparison.Ordinal);
await JsonSerializer.SerializeAsync(context.Response.Body, Updates, s_jsonSerializerOptions);
}

private async Task OnPost(HttpContext context)
{
var updateDeltas = await JsonSerializer.DeserializeAsync<UpdateDelta[]>(context.Request.Body, _jsonSerializerOptions);
AppendDeltas(updateDeltas);

WriteETag(context);
}

private void WriteETag(HttpContext context)
{
var etag = GetETag();
if (etag is not null)
{
context.Response.Headers[HeaderNames.ETag] = etag;
}
}

private string? GetETag()
{
if (Deltas.Count == 0)
{
return null;
}

return string.Format(CultureInfo.InvariantCulture, "W/\"{0}{1}\"", EtagDiscriminator, Deltas[^1].SequenceId);
}

private void AppendDeltas(UpdateDelta[]? updateDeltas)
{
if (updateDeltas == null || updateDeltas.Length == 0)
var update = await JsonSerializer.DeserializeAsync<Update>(context.Request.Body, s_jsonSerializerOptions);
if (update == null)
{
context.Response.StatusCode = StatusCodes.Status400BadRequest;
return;
}

// It's possible that multiple instances of the BlazorWasm are simultaneously executing and could be posting the same deltas
// We'll use the sequence id to ensure that we're not recording duplicate entries. Replaying duplicated values would cause
// ApplyDelta to fail.
// It's currently not possible to receive different ranges of sequences from different clients (for e.g client 1 sends deltas 1 - 3,
// and client 2 sends deltas 2 - 4, client 3 sends 1 - 5 etc), so we only need to verify that the first item in the sequence has not already been seen.
if (Deltas.Count == 0 || Deltas[^1].SequenceId < updateDeltas[0].SequenceId)
if (Updates is [] || Updates[^1].Id < update.Id)
{
Deltas.AddRange(updateDeltas);
Updates.Add(update);
}
}

internal class UpdateDelta
{
public int SequenceId { get; set; }
public string ModuleId { get; set; } = default!;
public string MetadataDelta { get; set; } = default!;
public string ILDelta { get; set; } = default!;
public int[]? UpdatedTypes { get; set; } = default!;
}
}
}
50 changes: 25 additions & 25 deletions src/BuiltInTools/BrowserRefresh/BrowserRefreshMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,39 +9,33 @@

namespace Microsoft.AspNetCore.Watch.BrowserRefresh
{
public class BrowserRefreshMiddleware
public sealed class BrowserRefreshMiddleware(RequestDelegate next, ILogger<BrowserRefreshMiddleware> logger)
{
private static readonly MediaTypeHeaderValue _textHtmlMediaType = new("text/html");
private static readonly MediaTypeHeaderValue _applicationJsonMediaType = new("application/json");
private readonly string? _dotnetModifiableAssemblies = GetNonEmptyEnvironmentVariableValue("DOTNET_MODIFIABLE_ASSEMBLIES");
private readonly string? _aspnetcoreBrowserTools = GetNonEmptyEnvironmentVariableValue("__ASPNETCORE_BROWSER_TOOLS");

private readonly RequestDelegate _next;
private readonly ILogger _logger;
private static readonly MediaTypeHeaderValue s_textHtmlMediaType = new("text/html");
private static readonly MediaTypeHeaderValue s_applicationJsonMediaType = new("application/json");
private string? _dotnetModifiableAssemblies = GetNonEmptyEnvironmentVariableValue("DOTNET_MODIFIABLE_ASSEMBLIES");
private string? _aspnetcoreBrowserTools = GetNonEmptyEnvironmentVariableValue("__ASPNETCORE_BROWSER_TOOLS");

private static string? GetNonEmptyEnvironmentVariableValue(string name)
=> Environment.GetEnvironmentVariable(name) is { Length: > 0 } value ? value : null;

public BrowserRefreshMiddleware(RequestDelegate next, ILogger<BrowserRefreshMiddleware> logger) =>
(_next, _logger) = (next, logger);

public async Task InvokeAsync(HttpContext context)
{
if (IsWebAssemblyBootRequest(context))
{
AttachWebAssemblyHeaders(context);
await _next(context);
await next(context);
}
else if (IsBrowserDocumentRequest(context))
{
// Use a custom StreamWrapper to rewrite output on Write/WriteAsync
using var responseStreamWrapper = new ResponseStreamWrapper(context, _logger);
using var responseStreamWrapper = new ResponseStreamWrapper(context, logger);
var originalBodyFeature = context.Features.Get<IHttpResponseBodyFeature>();
context.Features.Set<IHttpResponseBodyFeature>(new StreamResponseBodyFeature(responseStreamWrapper));

try
{
await _next(context);
await next(context);
}
finally
{
Expand All @@ -52,21 +46,21 @@ public async Task InvokeAsync(HttpContext context)
{
if (responseStreamWrapper.ScriptInjectionPerformed)
{
Log.BrowserConfiguredForRefreshes(_logger);
Log.BrowserConfiguredForRefreshes(logger);
}
else if (context.Response.Headers.TryGetValue(HeaderNames.ContentEncoding, out var contentEncodings))
{
Log.ResponseCompressionDetected(_logger, contentEncodings);
Log.ResponseCompressionDetected(logger, contentEncodings);
}
else
{
Log.FailedToConfiguredForRefreshes(_logger);
Log.FailedToConfiguredForRefreshes(logger);
}
}
}
else
{
await _next(context);
await next(context);
}
}

Expand All @@ -76,18 +70,18 @@ private void AttachWebAssemblyHeaders(HttpContext context)
{
if (!context.Response.Headers.ContainsKey("DOTNET-MODIFIABLE-ASSEMBLIES"))
{
if(_dotnetModifiableAssemblies != null)
if (_dotnetModifiableAssemblies != null)
{
context.Response.Headers.Add("DOTNET-MODIFIABLE-ASSEMBLIES", _dotnetModifiableAssemblies);
}
else
{
_logger.LogDebug("DOTNET_MODIFIABLE_ASSEMBLIES environment variable is not set, likely because hot reload is not enabled. The browser refresh feature may not work as expected.");
logger.LogDebug("DOTNET_MODIFIABLE_ASSEMBLIES environment variable is not set, likely because hot reload is not enabled. The browser refresh feature may not work as expected.");
}
}
else
{
_logger.LogDebug("DOTNET-MODIFIABLE-ASSEMBLIES header is already set.");
logger.LogDebug("DOTNET-MODIFIABLE-ASSEMBLIES header is already set.");
}

if (!context.Response.Headers.ContainsKey("ASPNETCORE-BROWSER-TOOLS"))
Expand All @@ -98,12 +92,12 @@ private void AttachWebAssemblyHeaders(HttpContext context)
}
else
{
_logger.LogDebug("__ASPNETCORE_BROWSER_TOOLS environment variable is not set. The browser refresh feature may not work as expected.");
logger.LogDebug("__ASPNETCORE_BROWSER_TOOLS environment variable is not set. The browser refresh feature may not work as expected.");
}
}
else
{
_logger.LogDebug("ASPNETCORE-BROWSER-TOOLS header is already set.");
logger.LogDebug("ASPNETCORE-BROWSER-TOOLS header is already set.");
}

return Task.CompletedTask;
Expand Down Expand Up @@ -141,7 +135,7 @@ internal static bool IsWebAssemblyBootRequest(HttpContext context)

for (var i = 0; i < acceptHeaders.Count; i++)
{
if (acceptHeaders[i].MatchesAllTypes || acceptHeaders[i].IsSubsetOf(_applicationJsonMediaType))
if (acceptHeaders[i].MatchesAllTypes || acceptHeaders[i].IsSubsetOf(s_applicationJsonMediaType))
{
return true;
}
Expand Down Expand Up @@ -175,7 +169,7 @@ internal static bool IsBrowserDocumentRequest(HttpContext context)

for (var i = 0; i < acceptHeaders.Count; i++)
{
if (acceptHeaders[i].IsSubsetOf(_textHtmlMediaType))
if (acceptHeaders[i].IsSubsetOf(s_textHtmlMediaType))
{
return true;
}
Expand All @@ -184,6 +178,12 @@ internal static bool IsBrowserDocumentRequest(HttpContext context)
return false;
}

internal void Test_SetEnvironment(string dotnetModifiableAssemblies, string aspnetcoreBrowserTools)
{
_dotnetModifiableAssemblies = dotnetModifiableAssemblies;
_aspnetcoreBrowserTools = aspnetcoreBrowserTools;
}

internal static class Log
{
private static readonly Action<ILogger, Exception?> _setupResponseForBrowserRefresh = LoggerMessage.Define(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public async Task InvokeAsync(HttpContext context)
await context.Response.Body.WriteAsync(_scriptBytes.AsMemory(), context.RequestAborted);
}

// for backwards compat only
internal static byte[] GetBlazorHotReloadJS()
{
var jsFileName = "Microsoft.AspNetCore.Watch.BrowserRefresh.BlazorHotReload.js";
Expand Down
1 change: 1 addition & 0 deletions src/BuiltInTools/BrowserRefresh/HostingStartup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
app.Map(ApplicationPaths.BrowserRefreshJS,
static app => app.UseMiddleware<BrowserScriptMiddleware>(BrowserScriptMiddleware.GetBrowserRefreshJS()));

// backwards compat only:
app.Map(ApplicationPaths.BlazorHotReloadJS,
static app => app.UseMiddleware<BrowserScriptMiddleware>(BrowserScriptMiddleware.GetBlazorHotReloadJS()));
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,19 @@
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<EmbeddedResource Include="WebSocketScriptInjection.js" />

<!-- Back compat only -->
<EmbeddedResource Include="BlazorHotReload.js" />
</ItemGroup>

<ItemGroup Condition="'$(DotNetBuildSourceOnly)' == 'true'">
<!-- Reference 6.0.2 targeting packs in Source Build - this was the earliest version after the API surface stabilized -->
<FrameworkReference
Update="Microsoft.AspNetCore.App"
TargetingPackVersion="6.0.2" />
<FrameworkReference
Update="Microsoft.NETCore.App"
TargetingPackVersion="6.0.2" />
<FrameworkReference Update="Microsoft.AspNetCore.App" TargetingPackVersion="6.0.2" />
<FrameworkReference Update="Microsoft.NETCore.App" TargetingPackVersion="6.0.2" />
</ItemGroup>

<ItemGroup>
<InternalsVisibleTo Include="Microsoft.AspNetCore.Watch.BrowserRefresh.Tests" />
</ItemGroup>

</Project>
Loading