Skip to content

Commit

Permalink
Use feature switch to perform hot reload trimming
Browse files Browse the repository at this point in the history
Contributes to dotnet/runtime#51159
  • Loading branch information
pranavkm committed May 7, 2021
1 parent 5c3ef58 commit 7bd65cf
Show file tree
Hide file tree
Showing 12 changed files with 48 additions and 95 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
<ItemGroup>
<Compile Include="$(ComponentsSharedSourceRoot)src\ArrayBuilder.cs" LinkBase="RenderTree" />
<Compile Include="$(ComponentsSharedSourceRoot)src\JsonSerializerOptionsProvider.cs" />
<Compile Include="$(ComponentsSharedSourceRoot)src\HotReloadEnvironment.cs" LinkBase="HotReload" />
<Compile Include="$(ComponentsSharedSourceRoot)src\HotReloadFeature.cs" LinkBase="HotReload" />
<Compile Include="$(SharedSourceRoot)LinkerFlags.cs" LinkBase="Shared" />
</ItemGroup>

Expand Down
14 changes: 4 additions & 10 deletions src/Components/Components/src/Properties/ILLink.Substitutions.xml
Original file line number Diff line number Diff line change
@@ -1,17 +1,11 @@
<linker>
<assembly fullname="Microsoft.AspNetCore.Components" >
<!-- HotReload will not be available in a trimmed app. We'll attempt to aggressively remove all references to it. -->
<type fullname="Microsoft.AspNetCore.Components.RenderTree.Renderer">
<!-- Renderer.IsHotReloading will always return false in a trimmed app. -->
<method signature="System.Boolean get_IsHotReloading()" body="stub" value="false" />
<method signature="System.Void RenderRootComponentsOnHotReload()" body="remove" />
<method signature="System.Void InitializeHotReload(System.IServiceProvider)" body="stub" />
<method signature="System.Void CaptureRootComponentForHotReload(Microsoft.AspNetCore.Components.ParameterView,Microsoft.AspNetCore.Components.Rendering.ComponentState)" body="stub" />
<method signature="System.Void DisposeForHotReload()" body="stub" />
</type>
<assembly fullname="Microsoft.AspNetCore.Components">
<!-- Avoid any overhead in RenderHandle.IsHotReloading by aggressively trimming it -->
<type fullname="Microsoft.AspNetCore.Components.RenderHandle">
<method signature="System.Boolean get_IsHotReloading()" body="stub" value="false" />
</type>
<type fullname="Microsoft.AspNetCore.Components.HotReload.HotReloadFeature" feature="System.Diagnostics.Debugger.IsSupported" featurevalue="false">
<method signature="System.Boolean get_IsSupported()" body="stub" value="false" />
</type>
</assembly>
</linker>
3 changes: 2 additions & 1 deletion src/Components/Components/src/RenderHandle.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNetCore.Components.HotReload;
using Microsoft.AspNetCore.Components.RenderTree;

namespace Microsoft.AspNetCore.Components
Expand Down Expand Up @@ -46,7 +47,7 @@ public Dispatcher Dispatcher
/// <summary>
/// Gets a value that determines if the <see cref="Renderer"/> is triggering a render in response to a hot-reload change.
/// </summary>
public bool IsHotReloading => _renderer?.IsHotReloading ?? false;
public bool IsHotReloading => HotReloadFeature.IsSupported && (_renderer?.IsHotReloading ?? false);

/// <summary>
/// Notifies the renderer that the component should be rendered.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Components.HotReload;
using Microsoft.AspNetCore.Components.Rendering;

namespace Microsoft.AspNetCore.Components.RenderTree
Expand Down Expand Up @@ -541,7 +542,7 @@ private static void UpdateRetainedChildComponent(
var oldParameters = new ParameterView(ParameterViewLifetime.Unbound, oldTree, oldComponentIndex);
var newParametersLifetime = new ParameterViewLifetime(diffContext.BatchBuilder);
var newParameters = new ParameterView(newParametersLifetime, newTree, newComponentIndex);
if (!newParameters.DefinitelyEquals(oldParameters) || diffContext.Renderer.IsHotReloading)
if (!newParameters.DefinitelyEquals(oldParameters) || (HotReloadFeature.IsSupported && diffContext.Renderer.IsHotReloading))
{
componentState.SetDirectParameters(newParameters);
}
Expand Down
53 changes: 13 additions & 40 deletions src/Components/Components/src/RenderTree/Renderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.HotReload;
Expand Down Expand Up @@ -35,10 +34,9 @@ public abstract partial class Renderer : IDisposable, IAsyncDisposable
private readonly Dictionary<ulong, ulong> _eventHandlerIdReplacements = new Dictionary<ulong, ulong>();
private readonly ILogger<Renderer> _logger;
private readonly ComponentFactory _componentFactory;
private HotReloadEnvironment? _hotReloadEnvironment;
private List<(ComponentState, ParameterView)>? _rootComponents;

private int _nextComponentId = 0; // TODO: change to 'long' when Mono .NET->JS interop supports it
private int _nextComponentId = 0;
private bool _isBatchInProgress;
private ulong _lastEventHandlerId;
private List<Task>? _pendingTasks;
Expand Down Expand Up @@ -98,16 +96,7 @@ public Renderer(IServiceProvider serviceProvider, ILoggerFactory loggerFactory,
_logger = loggerFactory.CreateLogger<Renderer>();
_componentFactory = new ComponentFactory(componentActivator);

InitializeHotReload(serviceProvider);
}

private void InitializeHotReload(IServiceProvider serviceProvider)
{
// HotReloadEnvironment is a test-specific feature and may not be available in a running app. We'll fallback to the default instance
// if the test fixture does not provide one.
_hotReloadEnvironment = serviceProvider.GetService<HotReloadEnvironment>() ?? HotReloadEnvironment.Instance;

if (_hotReloadEnvironment.IsHotReloadEnabled)
if (HotReloadFeature.IsSupported)
{
HotReloadManager.OnDeltaApplied += RenderRootComponentsOnHotReload;
}
Expand Down Expand Up @@ -232,7 +221,13 @@ protected async Task RenderRootComponentAsync(int componentId, ParameterView ini
// During the asynchronous rendering process we want to wait up until all components have
// finished rendering so that we can produce the complete output.
var componentState = GetRequiredComponentState(componentId);
CaptureRootComponentForHotReload(initialParameters, componentState);
if (HotReloadFeature.IsSupported)
{
// when we're doing hot-reload, stash away the parameters used while rendering root components.
// We'll use this to trigger re-renders on hot reload updates.
_rootComponents ??= new();
_rootComponents.Add((componentState, initialParameters.Clone()));
}

componentState.SetDirectParameters(initialParameters);

Expand All @@ -247,20 +242,6 @@ protected async Task RenderRootComponentAsync(int componentId, ParameterView ini
}
}

/// <remarks>
/// Intentionally authored as a separate method call so we can trim this code.
/// </remarks>
private void CaptureRootComponentForHotReload(ParameterView initialParameters, ComponentState componentState)
{
if (_hotReloadEnvironment?.IsHotReloadEnabled ?? false)
{
// when we're doing hot-reload, stash away the parameters used while rendering root components.
// We'll use this to trigger re-renders on hot reload updates.
_rootComponents ??= new();
_rootComponents.Add((componentState, initialParameters.Clone()));
}
}

/// <summary>
/// Allows derived types to handle exceptions during rendering. Defaults to rethrowing the original exception.
/// </summary>
Expand Down Expand Up @@ -1011,7 +992,10 @@ public void Dispose()
/// <inheritdoc />
public async ValueTask DisposeAsync()
{
DisposeForHotReload();
if (HotReloadFeature.IsSupported)
{
HotReloadManager.OnDeltaApplied -= RenderRootComponentsOnHotReload;
}

if (_disposed)
{
Expand All @@ -1035,16 +1019,5 @@ public async ValueTask DisposeAsync()
}
}
}

/// <remarks>
/// Intentionally authored as a separate method call so we can trim this code.
/// </remarks>
private void DisposeForHotReload()
{
if (_hotReloadEnvironment?.IsHotReloadEnabled ?? false)
{
HotReloadManager.OnDeltaApplied -= RenderRootComponentsOnHotReload;
}
}
}
}
22 changes: 0 additions & 22 deletions src/Components/Shared/src/HotReloadEnvironment.cs

This file was deleted.

15 changes: 15 additions & 0 deletions src/Components/Shared/src/HotReloadFeature.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;

namespace Microsoft.AspNetCore.Components.HotReload
{
internal static class HotReloadFeature
{
/// <summary>
/// Gets a value that determines if hot reload is supported. Currently, the <c>Debugger.IsSupported</c> feature switch is used as a proxy for this.
/// </summary>
public static bool IsSupported { get; } = AppContext.TryGetSwitch("System.Diagnostics.Debugger.IsSupported", out var isSupported) ? isSupported : true;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.HotReload;
using Microsoft.AspNetCore.Components.Lifetime;
using Microsoft.AspNetCore.Components.WebAssembly.HotReload;
using Microsoft.AspNetCore.Components.WebAssembly.Infrastructure;
Expand Down Expand Up @@ -144,11 +145,9 @@ internal async Task RunAsyncCore(CancellationToken cancellationToken, WebAssembl

await manager.RestoreStateAsync(store);

var initializeTask = InitializeHotReloadAsync();
if (initializeTask is not null)
if (HotReloadFeature.IsSupported)
{
// The returned value will be "null" in a trimmed app
await initializeTask;
await WebAssemblyHotReload.InitializeAsync();
}

var tcs = new TaskCompletionSource();
Expand Down Expand Up @@ -184,11 +183,5 @@ internal async Task RunAsyncCore(CancellationToken cancellationToken, WebAssembl
await tcs.Task;
}
}

private Task? InitializeHotReloadAsync()
{
// In Development scenarios, wait for hot reload to apply deltas before initiating rendering.
return WebAssemblyHotReload.InitializeAsync();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
using System.ComponentModel;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.HotReload;
using Microsoft.AspNetCore.Components.WebAssembly.Services;
using Microsoft.Extensions.HotReload;
using Microsoft.JSInterop;
Expand All @@ -27,7 +26,10 @@ public static class WebAssemblyHotReload

internal static async Task InitializeAsync()
{
if (!HotReloadEnvironment.Instance.IsHotReloadEnabled)
// Determine if we're running under a hot reload environment (e.g. dotnet-watch).
// It's insufficient to know it the app can be hot reloaded (HotReloadEnvironment.IsEnabled),
// since the hot-reload agent might be unavilable.
if (Environment.GetEnvironmentVariable("DOTNET_MODIFIABLE_ASSEMBLIES") != "debug")
{
return;
}
Expand All @@ -45,7 +47,6 @@ internal static async Task InitializeAsync()
public static void ApplyHotReloadDelta(string moduleIdString, byte[] metadataDelta, byte[] ilDeta)
{
var moduleId = Guid.Parse(moduleIdString);
Debug.Assert(HotReloadEnvironment.Instance.IsHotReloadEnabled);

_updateDeltas[0].ModuleId = moduleId;
_updateDeltas[0].MetadataDelta = metadataDelta;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>$(DefaultNetCoreTargetFramework)</TargetFramework>
Expand Down Expand Up @@ -32,7 +32,7 @@
<Compile Include="$(SharedSourceRoot)Components\ComponentParameter.cs" Link="Prerendering/ComponentParameter.cs" />
<Compile Include="$(SharedSourceRoot)Components\PrerenderComponentApplicationStore.cs" />
<Compile Include="$(SharedSourceRoot)LinkerFlags.cs" LinkBase="Shared" />
<Compile Include="$(ComponentsSharedSourceRoot)src\HotReloadEnvironment.cs" LinkBase="HotReload" />
<Compile Include="$(ComponentsSharedSourceRoot)src\HotReloadFeature.cs" LinkBase="HotReload" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
<linker>
<assembly fullname="Microsoft.AspNetCore.Components.WebAssembly" >
<!-- HotReload will not be available in a trimmed app. We'll attempt to aggressively remove all references to it. -->
<type fullname="Microsoft.AspNetCore.Components.WebAssembly.Hosting.WebAssemblyHost">
<method signature="System.Threading.Tasks.Task InitializeHotReloadAsync()" body="stub" />
<type fullname="Microsoft.AspNetCore.Components.HotReload.HotReloadFeature" feature="System.Diagnostics.Debugger.IsSupported" featurevalue="false">
<method signature="System.Boolean get_IsSupported()" body="stub" value="false" />
</type>
</assembly>
</linker>
2 changes: 0 additions & 2 deletions src/Components/test/testassets/TestServer/HotReloadStartup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

using System.Globalization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components.HotReload;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
Expand All @@ -14,7 +13,6 @@ public class HotReloadStartup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton(new HotReloadEnvironment(isHotReloadEnabled: true));
services.AddControllers();
services.AddRazorPages();
services.AddServerSideBlazor();
Expand Down

0 comments on commit 7bd65cf

Please sign in to comment.