|
| 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 Microsoft.Extensions.Caching.Hybrid; |
| 5 | +using Microsoft.Extensions.Logging; |
| 6 | +using Microsoft.Extensions.Options; |
| 7 | + |
| 8 | +namespace Microsoft.AspNetCore.Components.Server.Circuits; |
| 9 | + |
| 10 | +// Implementation of ICircuitPersistenceProvider that uses HybridCache for distributed caching |
| 11 | +internal sealed partial class HybridCacheCircuitPersistenceProvider : ICircuitPersistenceProvider |
| 12 | +{ |
| 13 | + private static readonly Func<CancellationToken, ValueTask<PersistedCircuitState>> _failOnCreate = |
| 14 | + static ct => throw new InvalidOperationException(); |
| 15 | + |
| 16 | + private static readonly string[] _tags = ["Microsoft.AspNetCore.Components.Server.PersistedCircuitState"]; |
| 17 | + |
| 18 | + private readonly SemaphoreSlim _lock = new(1, 1); |
| 19 | + private readonly HybridCache _hybridCache; |
| 20 | + private readonly ILogger<ICircuitPersistenceProvider> _logger; |
| 21 | + private readonly HybridCacheEntryOptions _cacheWriteOptions; |
| 22 | + private readonly HybridCacheEntryOptions _cacheReadOptions; |
| 23 | + |
| 24 | + public HybridCacheCircuitPersistenceProvider( |
| 25 | + HybridCache hybridCache, |
| 26 | + ILogger<ICircuitPersistenceProvider> logger, |
| 27 | + IOptions<CircuitOptions> options) |
| 28 | + { |
| 29 | + _hybridCache = hybridCache; |
| 30 | + _logger = logger; |
| 31 | + _cacheWriteOptions = new HybridCacheEntryOptions |
| 32 | + { |
| 33 | + Expiration = options.Value.PersistedCircuitDistributedRetentionPeriod, |
| 34 | + LocalCacheExpiration = options.Value.PersistedCircuitInMemoryRetentionPeriod, |
| 35 | + }; |
| 36 | + _cacheReadOptions = new HybridCacheEntryOptions |
| 37 | + { |
| 38 | + Flags = HybridCacheEntryFlags.DisableLocalCacheWrite | |
| 39 | + HybridCacheEntryFlags.DisableDistributedCacheWrite | |
| 40 | + HybridCacheEntryFlags.DisableUnderlyingData, |
| 41 | + }; |
| 42 | + } |
| 43 | + |
| 44 | + public async Task PersistCircuitAsync(CircuitId circuitId, PersistedCircuitState persistedCircuitState, CancellationToken cancellation = default) |
| 45 | + { |
| 46 | + Log.CircuitPauseStarted(_logger, circuitId); |
| 47 | + |
| 48 | + try |
| 49 | + { |
| 50 | + await _lock.WaitAsync(cancellation); |
| 51 | + await _hybridCache.SetAsync(circuitId.Secret, persistedCircuitState, _cacheWriteOptions, _tags, cancellation); |
| 52 | + } |
| 53 | + catch (Exception ex) |
| 54 | + { |
| 55 | + Log.ExceptionPersistingCircuit(_logger, circuitId, ex); |
| 56 | + } |
| 57 | + finally |
| 58 | + { |
| 59 | + _lock.Release(); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + public async Task<PersistedCircuitState> RestoreCircuitAsync(CircuitId circuitId, CancellationToken cancellation = default) |
| 64 | + { |
| 65 | + Log.CircuitResumeStarted(_logger, circuitId); |
| 66 | + |
| 67 | + try |
| 68 | + { |
| 69 | + await _lock.WaitAsync(cancellation); |
| 70 | + var state = await _hybridCache.GetOrCreateAsync( |
| 71 | + circuitId.Secret, |
| 72 | + factory: _failOnCreate, |
| 73 | + options: _cacheReadOptions, |
| 74 | + _tags, |
| 75 | + cancellation); |
| 76 | + |
| 77 | + if (state == null) |
| 78 | + { |
| 79 | + Log.FailedToFindCircuitState(_logger, circuitId); |
| 80 | + return null; |
| 81 | + } |
| 82 | + |
| 83 | + await _hybridCache.RemoveAsync(circuitId.Secret, cancellation); |
| 84 | + |
| 85 | + Log.CircuitStateFound(_logger, circuitId); |
| 86 | + return state; |
| 87 | + } |
| 88 | + catch (Exception ex) |
| 89 | + { |
| 90 | + Log.ExceptionRestoringCircuit(_logger, circuitId, ex); |
| 91 | + return null; |
| 92 | + } |
| 93 | + finally |
| 94 | + { |
| 95 | + _lock.Release(); |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + private static partial class Log |
| 100 | + { |
| 101 | + [LoggerMessage(201, LogLevel.Debug, "Circuit state evicted for circuit {CircuitId} due to {Reason}", EventName = "CircuitStateEvicted")] |
| 102 | + public static partial void CircuitStateEvicted(ILogger logger, CircuitId circuitId, string reason); |
| 103 | + |
| 104 | + [LoggerMessage(202, LogLevel.Debug, "Resuming circuit with ID {CircuitId}", EventName = "CircuitResumeStarted")] |
| 105 | + public static partial void CircuitResumeStarted(ILogger logger, CircuitId circuitId); |
| 106 | + |
| 107 | + [LoggerMessage(203, LogLevel.Debug, "Failed to find persisted circuit with ID {CircuitId}", EventName = "FailedToFindCircuitState")] |
| 108 | + public static partial void FailedToFindCircuitState(ILogger logger, CircuitId circuitId); |
| 109 | + |
| 110 | + [LoggerMessage(204, LogLevel.Debug, "Circuit state found for circuit {CircuitId}", EventName = "CircuitStateFound")] |
| 111 | + public static partial void CircuitStateFound(ILogger logger, CircuitId circuitId); |
| 112 | + |
| 113 | + [LoggerMessage(205, LogLevel.Error, "An exception occurred while disposing the token source.", EventName = "ExceptionDisposingTokenSource")] |
| 114 | + public static partial void ExceptionDisposingTokenSource(ILogger logger, Exception exception); |
| 115 | + |
| 116 | + [LoggerMessage(206, LogLevel.Debug, "Pausing circuit with ID {CircuitId}", EventName = "CircuitPauseStarted")] |
| 117 | + public static partial void CircuitPauseStarted(ILogger logger, CircuitId circuitId); |
| 118 | + |
| 119 | + [LoggerMessage(207, LogLevel.Error, "An exception occurred while persisting circuit {CircuitId}.", EventName = "ExceptionPersistingCircuit")] |
| 120 | + public static partial void ExceptionPersistingCircuit(ILogger logger, CircuitId circuitId, Exception exception); |
| 121 | + |
| 122 | + [LoggerMessage(208, LogLevel.Error, "An exception occurred while restoring circuit {CircuitId}.", EventName = "ExceptionRestoringCircuit")] |
| 123 | + public static partial void ExceptionRestoringCircuit(ILogger logger, CircuitId circuitId, Exception exception); |
| 124 | + |
| 125 | + [LoggerMessage(209, LogLevel.Error, "An exception occurred during expiration handling for circuit {CircuitId}.", EventName = "ExceptionDuringExpiration")] |
| 126 | + public static partial void ExceptionDuringExpiration(ILogger logger, CircuitId circuitId, Exception exception); |
| 127 | + |
| 128 | + [LoggerMessage(210, LogLevel.Error, "An exception occurred while removing expired circuit {CircuitId}.", EventName = "ExceptionRemovingExpiredCircuit")] |
| 129 | + public static partial void ExceptionRemovingExpiredCircuit(ILogger logger, CircuitId circuitId, Exception exception); |
| 130 | + } |
| 131 | +} |
0 commit comments