| | | 1 | | namespace Intentum.Runtime.Resilience.Degradation; |
| | | 2 | | |
| | | 3 | | public sealed class MemoryDegradationPolicy : IDegradationPolicy |
| | | 4 | | { |
| | | 5 | | private readonly DegradationOptions _options; |
| | 5 | 6 | | private readonly object _lock = new(); |
| | | 7 | | private int _consecutiveFailures; |
| | | 8 | | private DateTime? _degradedSince; |
| | | 9 | | |
| | 5 | 10 | | public MemoryDegradationPolicy(DegradationOptions options) |
| | 5 | 11 | | { |
| | 5 | 12 | | _options = options; |
| | 5 | 13 | | } |
| | | 14 | | |
| | | 15 | | public bool IsDegraded |
| | | 16 | | { |
| | | 17 | | get |
| | 12 | 18 | | { |
| | 12 | 19 | | CheckRecovery(); |
| | 12 | 20 | | return _consecutiveFailures >= _options.DegradationThreshold; |
| | 12 | 21 | | } |
| | | 22 | | } |
| | | 23 | | |
| | | 24 | | public async Task<T> ExecuteAsync<T>(Func<Task<T>> operation, Func<T> degradedFallback) |
| | 8 | 25 | | { |
| | 8 | 26 | | if (IsDegraded) |
| | 1 | 27 | | return degradedFallback(); |
| | | 28 | | |
| | | 29 | | try |
| | 7 | 30 | | { |
| | 7 | 31 | | var result = await operation(); |
| | 2 | 32 | | OnSuccess(); |
| | 2 | 33 | | return result; |
| | | 34 | | } |
| | 5 | 35 | | catch |
| | 5 | 36 | | { |
| | 5 | 37 | | OnFailure(); |
| | 5 | 38 | | throw; |
| | | 39 | | } |
| | 3 | 40 | | } |
| | | 41 | | |
| | | 42 | | public void Reset() |
| | 2 | 43 | | { |
| | 2 | 44 | | lock (_lock) |
| | 2 | 45 | | { |
| | 2 | 46 | | _consecutiveFailures = 0; |
| | 2 | 47 | | _degradedSince = null; |
| | 2 | 48 | | } |
| | 2 | 49 | | } |
| | | 50 | | |
| | | 51 | | private void OnSuccess() |
| | 2 | 52 | | { |
| | 2 | 53 | | lock (_lock) |
| | 2 | 54 | | _consecutiveFailures = 0; |
| | 2 | 55 | | } |
| | | 56 | | |
| | | 57 | | private void OnFailure() |
| | 5 | 58 | | { |
| | 5 | 59 | | lock (_lock) |
| | 5 | 60 | | { |
| | 5 | 61 | | _consecutiveFailures++; |
| | 5 | 62 | | if (_consecutiveFailures >= _options.DegradationThreshold) |
| | 4 | 63 | | _degradedSince ??= DateTime.UtcNow; |
| | 5 | 64 | | } |
| | 5 | 65 | | } |
| | | 66 | | |
| | | 67 | | private void CheckRecovery() |
| | 12 | 68 | | { |
| | 12 | 69 | | if (_degradedSince.HasValue && |
| | 12 | 70 | | DateTime.UtcNow - _degradedSince.Value >= _options.CheckInterval) |
| | 1 | 71 | | { |
| | 1 | 72 | | Reset(); |
| | 1 | 73 | | } |
| | 12 | 74 | | } |
| | | 75 | | } |