|
| 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.Text.Json; |
| 5 | +using System.Text.Json.Serialization; |
| 6 | +using Microsoft.AspNetCore.Components.Endpoints; |
| 7 | +using Microsoft.AspNetCore.Components.Infrastructure; |
| 8 | +using Microsoft.AspNetCore.Components.Web; |
| 9 | +using Microsoft.Extensions.DependencyInjection; |
| 10 | +using Microsoft.Extensions.Options; |
| 11 | + |
| 12 | +namespace Microsoft.AspNetCore.Components.Server.Circuits; |
| 13 | + |
| 14 | +internal partial class CircuitPersistenceManager( |
| 15 | + IOptions<CircuitOptions> circuitOptions, |
| 16 | + ServerComponentSerializer serverComponentSerializer, |
| 17 | + ICircuitPersistenceProvider circuitPersistenceProvider) |
| 18 | +{ |
| 19 | + public async Task PauseCircuitAsync(CircuitHost circuit, CancellationToken cancellation = default) |
| 20 | + { |
| 21 | + var renderer = circuit.Renderer; |
| 22 | + var persistenceManager = circuit.Services.GetRequiredService<ComponentStatePersistenceManager>(); |
| 23 | + var collector = new CircuitPersistenceManagerCollector(circuitOptions, serverComponentSerializer, circuit.Renderer); |
| 24 | + using var subscription = persistenceManager.State.RegisterOnPersisting( |
| 25 | + collector.PersistRootComponents, |
| 26 | + RenderMode.InteractiveServer); |
| 27 | + |
| 28 | + await persistenceManager.PersistStateAsync(collector, renderer); |
| 29 | + |
| 30 | + await circuitPersistenceProvider.PersistCircuitAsync( |
| 31 | + circuit.CircuitId, |
| 32 | + collector.PersistedCircuitState, |
| 33 | + cancellation); |
| 34 | + } |
| 35 | + |
| 36 | + public async Task<PersistedCircuitState> ResumeCircuitAsync(CircuitId circuitId, CancellationToken cancellation = default) |
| 37 | + { |
| 38 | + return await circuitPersistenceProvider.RestoreCircuitAsync(circuitId, cancellation); |
| 39 | + } |
| 40 | + |
| 41 | + // We are going to construct a RootComponentOperationBatch but we are going to replace the descriptors from the client with the |
| 42 | + // descriptors that we have persisted when pausing the circuit. |
| 43 | + // The way pausing and resuming works is that when the client starts the resume process, it 'simulates' that an SSR has happened and |
| 44 | + // queues an 'Add' operation for each server-side component that is on the document. |
| 45 | + // That ends up calling UpdateRootComponents with the old descriptors and no application state. |
| 46 | + // On the server side, we replace the descriptors with the ones that we have persisted. We can't use the original descriptors because |
| 47 | + // those have a lifetime of ~ 5 minutes, after which we are not able to unprotect them anymore. |
| 48 | + internal static RootComponentOperationBatch ToRootComponentOperationBatch( |
| 49 | + IServerComponentDeserializer serverComponentDeserializer, |
| 50 | + byte[] rootComponents, |
| 51 | + string serializedComponentOperations) |
| 52 | + { |
| 53 | + // Deserialize the existing batch the client has sent but ignore the markers |
| 54 | + if (!serverComponentDeserializer.TryDeserializeRootComponentOperations( |
| 55 | + serializedComponentOperations, |
| 56 | + out var batch, |
| 57 | + deserializeDescriptors: false)) |
| 58 | + { |
| 59 | + return null; |
| 60 | + } |
| 61 | + |
| 62 | + var persistedMarkers = TryDeserializeMarkers(rootComponents); |
| 63 | + |
| 64 | + if (persistedMarkers == null) |
| 65 | + { |
| 66 | + return null; |
| 67 | + } |
| 68 | + |
| 69 | + if (batch.Operations.Length != persistedMarkers.Count) |
| 70 | + { |
| 71 | + return null; |
| 72 | + } |
| 73 | + |
| 74 | + // Ensure that all operations in the batch are `Add` operations. |
| 75 | + for (var i = 0; i < batch.Operations.Length; i++) |
| 76 | + { |
| 77 | + var operation = batch.Operations[i]; |
| 78 | + if (operation.Type != RootComponentOperationType.Add) |
| 79 | + { |
| 80 | + return null; |
| 81 | + } |
| 82 | + |
| 83 | + // Retrieve the marker from the persisted root components, replace it and deserialize the descriptor |
| 84 | + if (!persistedMarkers.TryGetValue(operation.SsrComponentId, out var marker)) |
| 85 | + { |
| 86 | + return null; |
| 87 | + } |
| 88 | + operation.Marker = marker; |
| 89 | + |
| 90 | + if (!serverComponentDeserializer.TryDeserializeWebRootComponentDescriptor(operation.Marker.Value, out var descriptor)) |
| 91 | + { |
| 92 | + return null; |
| 93 | + } |
| 94 | + |
| 95 | + operation.Descriptor = descriptor; |
| 96 | + } |
| 97 | + |
| 98 | + return batch; |
| 99 | + |
| 100 | + static Dictionary<int, ComponentMarker> TryDeserializeMarkers(byte[] rootComponents) |
| 101 | + { |
| 102 | + if (rootComponents == null || rootComponents.Length == 0) |
| 103 | + { |
| 104 | + return null; |
| 105 | + } |
| 106 | + |
| 107 | + try |
| 108 | + { |
| 109 | + return JsonSerializer.Deserialize<Dictionary<int, ComponentMarker>>( |
| 110 | + rootComponents, |
| 111 | + JsonSerializerOptionsProvider.Options); |
| 112 | + } |
| 113 | + catch |
| 114 | + { |
| 115 | + return null; |
| 116 | + } |
| 117 | + } |
| 118 | + } |
| 119 | + |
| 120 | + private class CircuitPersistenceManagerCollector( |
| 121 | + IOptions<CircuitOptions> circuitOptions, |
| 122 | + ServerComponentSerializer serverComponentSerializer, |
| 123 | + RemoteRenderer renderer) |
| 124 | + : IPersistentComponentStateStore |
| 125 | + { |
| 126 | + internal PersistedCircuitState PersistedCircuitState { get; private set; } |
| 127 | + |
| 128 | + public Task PersistRootComponents() |
| 129 | + { |
| 130 | + var persistedComponents = new Dictionary<int, ComponentMarker>(); |
| 131 | + var components = renderer.GetOrCreateWebRootComponentManager().GetRootComponents(); |
| 132 | + var invocation = new ServerComponentInvocationSequence(); |
| 133 | + foreach (var (id, componentKey, (componentType, parameters)) in components) |
| 134 | + { |
| 135 | + var distributedRetention = circuitOptions.Value.PersistedCircuitInMemoryRetentionPeriod; |
| 136 | + var localRetention = circuitOptions.Value.PersistedCircuitInMemoryRetentionPeriod; |
| 137 | + var maxRetention = distributedRetention > localRetention ? distributedRetention : localRetention; |
| 138 | + |
| 139 | + var marker = ComponentMarker.Create(ComponentMarker.ServerMarkerType, prerendered: false, componentKey); |
| 140 | + serverComponentSerializer.SerializeInvocation(ref marker, invocation, componentType, parameters, maxRetention); |
| 141 | + persistedComponents.Add(id, marker); |
| 142 | + } |
| 143 | + |
| 144 | + PersistedCircuitState = new PersistedCircuitState |
| 145 | + { |
| 146 | + RootComponents = JsonSerializer.SerializeToUtf8Bytes( |
| 147 | + persistedComponents, |
| 148 | + CircuitPersistenceManagerSerializerContext.Default.DictionaryInt32ComponentMarker) |
| 149 | + }; |
| 150 | + |
| 151 | + return Task.CompletedTask; |
| 152 | + } |
| 153 | + |
| 154 | + // This store only support serializing the state |
| 155 | + Task<IDictionary<string, byte[]>> IPersistentComponentStateStore.GetPersistedStateAsync() => throw new NotImplementedException(); |
| 156 | + |
| 157 | + // During the persisting phase the state is captured into a Dictionary<string, byte[]>, our implementation registers |
| 158 | + // a callback so that it can run at the same time as the other components' state is persisted. |
| 159 | + // We then are called to save the persisted state, at which point, we extract the component records |
| 160 | + // and store them separately from the other state. |
| 161 | + Task IPersistentComponentStateStore.PersistStateAsync(IReadOnlyDictionary<string, byte[]> state) |
| 162 | + { |
| 163 | + PersistedCircuitState.ApplicationState = state; |
| 164 | + return Task.CompletedTask; |
| 165 | + } |
| 166 | + } |
| 167 | + |
| 168 | + [JsonSerializable(typeof(Dictionary<int, ComponentMarker>))] |
| 169 | + internal partial class CircuitPersistenceManagerSerializerContext : JsonSerializerContext |
| 170 | + { |
| 171 | + } |
| 172 | +} |
0 commit comments