Skip to content

[release/8.0] [Blazor] Dispatch inbound activity handlers in Blazor Web apps #53313

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 1 commit into from
Jan 16, 2024
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
96 changes: 57 additions & 39 deletions src/Components/Server/src/Circuits/CircuitHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ internal partial class CircuitHost : IAsyncDisposable
private readonly CircuitOptions _options;
private readonly RemoteNavigationManager _navigationManager;
private readonly ILogger _logger;
private readonly Func<Func<Task>, Task> _dispatchInboundActivity;
private Func<Func<Task>, Task> _dispatchInboundActivity;
private CircuitHandler[] _circuitHandlers;
private bool _initialized;
private bool _isFirstUpdate = true;
Expand Down Expand Up @@ -735,11 +735,10 @@ internal Task UpdateRootComponents(

return Renderer.Dispatcher.InvokeAsync(async () =>
{
var webRootComponentManager = Renderer.GetOrCreateWebRootComponentManager();
var shouldClearStore = false;
var shouldWaitForQuiescence = false;
var operations = operationBatch.Operations;
var batchId = operationBatch.BatchId;
Task[]? pendingTasks = null;
try
{
if (Descriptors.Count > 0)
Expand All @@ -752,6 +751,7 @@ internal Task UpdateRootComponents(
if (_isFirstUpdate)
{
_isFirstUpdate = false;
shouldWaitForQuiescence = true;
if (store != null)
{
shouldClearStore = true;
Expand All @@ -763,6 +763,7 @@ internal Task UpdateRootComponents(

// Retrieve the circuit handlers at this point.
_circuitHandlers = [.. _scope.ServiceProvider.GetServices<CircuitHandler>().OrderBy(h => h.Order)];
_dispatchInboundActivity = BuildInboundActivityDispatcher(_circuitHandlers, Circuit);
await OnCircuitOpenedAsync(cancellation);
await OnConnectionUpAsync(cancellation);

Expand All @@ -774,44 +775,9 @@ internal Task UpdateRootComponents(
throw new InvalidOperationException($"The first set of update operations must always be of type {nameof(RootComponentOperationType.Add)}");
}
}

pendingTasks = new Task[operations.Length];
}

for (var i = 0; i < operations.Length; i++)
{
var operation = operations[i];
switch (operation.Type)
{
case RootComponentOperationType.Add:
var task = webRootComponentManager.AddRootComponentAsync(
operation.SsrComponentId,
operation.Descriptor.ComponentType,
operation.Marker.Value.Key,
operation.Descriptor.Parameters);
if (pendingTasks != null)
{
pendingTasks[i] = task;
}
break;
case RootComponentOperationType.Update:
// We don't need to await component updates as any unhandled exception will be reported and terminate the circuit.
_ = webRootComponentManager.UpdateRootComponentAsync(
operation.SsrComponentId,
operation.Descriptor.ComponentType,
operation.Marker.Value.Key,
operation.Descriptor.Parameters);
break;
case RootComponentOperationType.Remove:
webRootComponentManager.RemoveRootComponent(operation.SsrComponentId);
break;
}
}

if (pendingTasks != null)
{
await Task.WhenAll(pendingTasks);
}
await PerformRootComponentOperations(operations, shouldWaitForQuiescence);

await Client.SendAsync("JS.EndUpdateRootComponents", batchId);

Expand All @@ -837,6 +803,58 @@ internal Task UpdateRootComponents(
});
}

private async ValueTask PerformRootComponentOperations(
RootComponentOperation[] operations,
bool shouldWaitForQuiescence)
{
var webRootComponentManager = Renderer.GetOrCreateWebRootComponentManager();
var pendingTasks = shouldWaitForQuiescence
? new Task[operations.Length]
: null;

// The inbound activity pipeline needs to be awaited because it populates
// the pending tasks used to wait for quiescence.
await HandleInboundActivityAsync(() =>
{
for (var i = 0; i < operations.Length; i++)
{
var operation = operations[i];
switch (operation.Type)
{
case RootComponentOperationType.Add:
var task = webRootComponentManager.AddRootComponentAsync(
operation.SsrComponentId,
operation.Descriptor.ComponentType,
operation.Marker.Value.Key,
operation.Descriptor.Parameters);
if (pendingTasks != null)
{
pendingTasks[i] = task;
}
break;
case RootComponentOperationType.Update:
// We don't need to await component updates as any unhandled exception will be reported and terminate the circuit.
_ = webRootComponentManager.UpdateRootComponentAsync(
operation.SsrComponentId,
operation.Descriptor.ComponentType,
operation.Marker.Value.Key,
operation.Descriptor.Parameters);
break;
case RootComponentOperationType.Remove:
webRootComponentManager.RemoveRootComponent(operation.SsrComponentId);
break;
}
}

return Task.CompletedTask;
});

if (pendingTasks != null)
{
await Task.WhenAll(pendingTasks);
}
}

private static partial class Log
{
// 100s used for lifecycle stuff
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1159,6 +1159,14 @@ public void NavigationManagerCanRefreshSSRPageWhenServerInteractivityEnabled()
Browser.Equal("GET", () => Browser.Exists(By.Id("method")).Text);
}

[Fact]
public void InteractiveServerRootComponent_CanAccessCircuitContext()
{
Navigate($"{ServerPathBase}/interactivity/circuit-context");

Browser.Equal("True", () => Browser.FindElement(By.Id("has-circuit-context")).Text);
}

private void BlockWebAssemblyResourceLoad()
{
((IJavaScriptExecutor)Browser).ExecuteScript("sessionStorage.setItem('block-load-boot-resource', 'true')");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using Components.TestServer.RazorComponents;
using Components.TestServer.RazorComponents.Pages.Forms;
using Components.TestServer.Services;
using Microsoft.AspNetCore.Components.Server.Circuits;
using Microsoft.AspNetCore.Mvc;

namespace TestServer;
Expand Down Expand Up @@ -35,6 +36,10 @@ public void ConfigureServices(IServiceCollection services)
services.AddHttpContextAccessor();
services.AddSingleton<AsyncOperationService>();
services.AddCascadingAuthenticationState();

var circuitContextAccessor = new TestCircuitContextAccessor();
services.AddSingleton<CircuitHandler>(circuitContextAccessor);
services.AddSingleton(circuitContextAccessor);
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
@page "/interactivity/circuit-context"
@rendermode RenderMode.InteractiveServer
@inject TestCircuitContextAccessor CircuitContextAccessor

<h1>Circuit context</h1>

<p>
Has circuit context: <span id="has-circuit-context">@_hasCircuitContext</span>
</p>

@code {
private bool _hasCircuitContext;

protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await Task.Yield();

_hasCircuitContext = CircuitContextAccessor.HasCircuitContext;

StateHasChanged();
}
}
}