| | | 1 | | using Elsa.Resilience.Options; |
| | | 2 | | using Microsoft.Extensions.Options; |
| | | 3 | | |
| | | 4 | | namespace Elsa.Resilience.Endpoints.SimulateResponse; |
| | | 5 | | |
| | 14 | 6 | | public class SimulateResponseSessionStore(IOptions<SimulateResponseOptions> options, TimeProvider timeProvider) |
| | | 7 | | { |
| | 14 | 8 | | private readonly Dictionary<string, SessionState> _sessions = new(StringComparer.Ordinal); |
| | 14 | 9 | | private readonly object _lock = new(); |
| | 14 | 10 | | private readonly SimulateResponseOptions _options = options.Value; |
| | | 11 | | |
| | | 12 | | public bool TryGetNextIndex(string sessionId, int statusCodeCount, out int nextIndex) |
| | | 13 | | { |
| | 11 | 14 | | if (statusCodeCount <= 0) |
| | 0 | 15 | | throw new ArgumentOutOfRangeException(nameof(statusCodeCount), "Status code count must be greater than zero. |
| | | 16 | | |
| | 11 | 17 | | var now = timeProvider.GetUtcNow(); |
| | 11 | 18 | | var expiresAt = now.Add(_options.SessionSlidingExpiration); |
| | | 19 | | |
| | 11 | 20 | | lock (_lock) |
| | | 21 | | { |
| | 11 | 22 | | PruneExpired(now); |
| | | 23 | | |
| | 11 | 24 | | nextIndex = _sessions.TryGetValue(sessionId, out var state) ? Math.Min(state.NextIndex, statusCodeCount - 1) |
| | | 25 | | |
| | 11 | 26 | | if (nextIndex + 1 >= statusCodeCount) |
| | | 27 | | { |
| | 3 | 28 | | _sessions.Remove(sessionId); |
| | 3 | 29 | | return true; |
| | | 30 | | } |
| | | 31 | | |
| | 8 | 32 | | if (!_sessions.ContainsKey(sessionId) && _sessions.Count >= _options.SessionCapacity) |
| | 1 | 33 | | return false; |
| | | 34 | | |
| | 7 | 35 | | _sessions[sessionId] = new SessionState(nextIndex + 1, expiresAt); |
| | 7 | 36 | | return true; |
| | | 37 | | } |
| | 11 | 38 | | } |
| | | 39 | | |
| | | 40 | | private void PruneExpired(DateTimeOffset now) |
| | | 41 | | { |
| | 37 | 42 | | foreach (var session in _sessions.Where(x => x.Value.ExpiresAt <= now).Select(x => x.Key).ToList()) |
| | 2 | 43 | | _sessions.Remove(session); |
| | 11 | 44 | | } |
| | | 45 | | |
| | 18 | 46 | | private sealed record SessionState(int NextIndex, DateTimeOffset ExpiresAt); |
| | | 47 | | } |