|
| 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.ComponentModel; |
| 5 | +using System.Diagnostics.CodeAnalysis; |
| 6 | +using System.Globalization; |
| 7 | +using System.Linq; |
| 8 | +using System.Net.Http; |
| 9 | +using System.Reflection.Metadata; |
| 10 | +using System.Runtime.InteropServices.JavaScript; |
| 11 | +using System.Runtime.Versioning; |
| 12 | +using System.Text.Json; |
| 13 | +using System.Text.Json.Serialization; |
| 14 | + |
| 15 | +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member |
| 16 | + |
| 17 | +namespace Microsoft.DotNet.HotReload.WebAssembly.Browser; |
| 18 | + |
| 19 | +/// <summary> |
| 20 | +/// Contains methods called by interop. Intended for framework use only, not supported for use in application |
| 21 | +/// code. |
| 22 | +/// </summary> |
| 23 | +[EditorBrowsable(EditorBrowsableState.Never)] |
| 24 | +[UnconditionalSuppressMessage( |
| 25 | + "Trimming", |
| 26 | + "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", |
| 27 | + Justification = "Hot Reload does not support trimming")] |
| 28 | +internal static partial class WebAssemblyHotReload |
| 29 | +{ |
| 30 | + /// <summary> |
| 31 | + /// For framework use only. |
| 32 | + /// </summary> |
| 33 | + public readonly struct LogEntry |
| 34 | + { |
| 35 | + public string Message { get; init; } |
| 36 | + public int Severity { get; init; } |
| 37 | + } |
| 38 | + |
| 39 | + /// <summary> |
| 40 | + /// For framework use only. |
| 41 | + /// </summary> |
| 42 | + internal sealed class Update |
| 43 | + { |
| 44 | + public int Id { get; set; } |
| 45 | + public Delta[] Deltas { get; set; } = default!; |
| 46 | + } |
| 47 | + |
| 48 | + /// <summary> |
| 49 | + /// For framework use only. |
| 50 | + /// </summary> |
| 51 | + public readonly struct Delta |
| 52 | + { |
| 53 | + public string ModuleId { get; init; } |
| 54 | + public byte[] MetadataDelta { get; init; } |
| 55 | + public byte[] ILDelta { get; init; } |
| 56 | + public byte[] PdbDelta { get; init; } |
| 57 | + public int[] UpdatedTypes { get; init; } |
| 58 | + } |
| 59 | + |
| 60 | + private static readonly JsonSerializerOptions s_jsonSerializerOptions = new(JsonSerializerDefaults.Web); |
| 61 | + |
| 62 | + private static bool s_initialized; |
| 63 | + private static HotReloadAgent? s_hotReloadAgent; |
| 64 | + |
| 65 | + [JSExport] |
| 66 | + [SupportedOSPlatform("browser")] |
| 67 | + public static async Task InitializeAsync(string baseUri) |
| 68 | + { |
| 69 | + if (MetadataUpdater.IsSupported && Environment.GetEnvironmentVariable("__ASPNETCORE_BROWSER_TOOLS") == "true" && |
| 70 | + OperatingSystem.IsBrowser()) |
| 71 | + { |
| 72 | + s_initialized = true; |
| 73 | + |
| 74 | + var agent = new HotReloadAgent(); |
| 75 | + |
| 76 | + var existingAgent = Interlocked.CompareExchange(ref s_hotReloadAgent, agent, null); |
| 77 | + if (existingAgent != null) |
| 78 | + { |
| 79 | + throw new InvalidOperationException("Hot Reload agent already initialized"); |
| 80 | + } |
| 81 | + |
| 82 | + await ApplyPreviousDeltasAsync(agent, baseUri); |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + private static async ValueTask ApplyPreviousDeltasAsync(HotReloadAgent agent, string baseUri) |
| 87 | + { |
| 88 | + string errorMessage; |
| 89 | + |
| 90 | + using var client = new HttpClient() |
| 91 | + { |
| 92 | + BaseAddress = new Uri(baseUri, UriKind.Absolute) |
| 93 | + }; |
| 94 | + |
| 95 | + try |
| 96 | + { |
| 97 | + var response = await client.GetAsync("/_framework/blazor-hotreload"); |
| 98 | + if (response.IsSuccessStatusCode) |
| 99 | + { |
| 100 | + var deltasJson = await response.Content.ReadAsStringAsync(); |
| 101 | + var updates = deltasJson != "" ? JsonSerializer.Deserialize<Update[]>(deltasJson, s_jsonSerializerOptions) : null; |
| 102 | + if (updates == null) |
| 103 | + { |
| 104 | + agent.Reporter.Report($"No previous updates to apply.", AgentMessageSeverity.Verbose); |
| 105 | + return; |
| 106 | + } |
| 107 | + |
| 108 | + var i = 1; |
| 109 | + foreach (var update in updates) |
| 110 | + { |
| 111 | + agent.Reporter.Report($"Reapplying update {i}/{updates.Length}.", AgentMessageSeverity.Verbose); |
| 112 | + |
| 113 | + agent.ApplyDeltas( |
| 114 | + update.Deltas.Select(d => new UpdateDelta(Guid.Parse(d.ModuleId, CultureInfo.InvariantCulture), d.MetadataDelta, d.ILDelta, d.PdbDelta, d.UpdatedTypes))); |
| 115 | + |
| 116 | + i++; |
| 117 | + } |
| 118 | + |
| 119 | + return; |
| 120 | + } |
| 121 | + |
| 122 | + errorMessage = $"HTTP GET '/_framework/blazor-hotreload' returned {response.StatusCode}"; |
| 123 | + } |
| 124 | + catch (Exception e) |
| 125 | + { |
| 126 | + errorMessage = e.ToString(); |
| 127 | + } |
| 128 | + |
| 129 | + agent.Reporter.Report($"Failed to retrieve and apply previous deltas from the server: {errorMessage}", AgentMessageSeverity.Error); |
| 130 | + } |
| 131 | + |
| 132 | + private static HotReloadAgent? GetAgent() |
| 133 | + => s_hotReloadAgent ?? (s_initialized ? throw new InvalidOperationException("Hot Reload agent not initialized") : null); |
| 134 | + |
| 135 | + private static LogEntry[] ApplyHotReloadDeltas(Delta[] deltas, int loggingLevel) |
| 136 | + { |
| 137 | + var agent = GetAgent(); |
| 138 | + if (agent == null) |
| 139 | + { |
| 140 | + return []; |
| 141 | + } |
| 142 | + |
| 143 | + agent.ApplyDeltas( |
| 144 | + deltas.Select(d => new UpdateDelta(Guid.Parse(d.ModuleId, CultureInfo.InvariantCulture), d.MetadataDelta, d.ILDelta, d.PdbDelta, d.UpdatedTypes))); |
| 145 | + |
| 146 | + return agent.Reporter.GetAndClearLogEntries((ResponseLoggingLevel)loggingLevel) |
| 147 | + .Select(log => new LogEntry() { Message = log.message, Severity = (int)log.severity }).ToArray(); |
| 148 | + } |
| 149 | + |
| 150 | + private static readonly WebAssemblyHotReloadJsonSerializerContext jsonContext = new(new(JsonSerializerDefaults.Web)); |
| 151 | + |
| 152 | + [JSExport] |
| 153 | + [SupportedOSPlatform("browser")] |
| 154 | + public static string GetApplyUpdateCapabilities() |
| 155 | + { |
| 156 | + return GetAgent()?.Capabilities ?? ""; |
| 157 | + } |
| 158 | + |
| 159 | + [JSExport] |
| 160 | + [SupportedOSPlatform("browser")] |
| 161 | + public static string? ApplyHotReloadDeltas(string deltasJson, int loggingLevel) |
| 162 | + { |
| 163 | + var deltas = JsonSerializer.Deserialize(deltasJson, jsonContext.DeltaArray); |
| 164 | + if (deltas == null) |
| 165 | + { |
| 166 | + return null; |
| 167 | + } |
| 168 | + |
| 169 | + var result = ApplyHotReloadDeltas(deltas, loggingLevel); |
| 170 | + return result == null ? null : JsonSerializer.Serialize(result, jsonContext.LogEntryArray); |
| 171 | + } |
| 172 | +} |
| 173 | + |
| 174 | +[JsonSerializable(typeof(WebAssemblyHotReload.Delta[]))] |
| 175 | +[JsonSerializable(typeof(WebAssemblyHotReload.LogEntry[]))] |
| 176 | +internal sealed partial class WebAssemblyHotReloadJsonSerializerContext : JsonSerializerContext |
| 177 | +{ |
| 178 | +} |
0 commit comments