| | | 1 | | using Intentum.Runtime.Resilience.Exceptions; |
| | | 2 | | |
| | | 3 | | namespace Intentum.Runtime.Resilience.Bulkhead; |
| | | 4 | | |
| | | 5 | | public sealed class MemoryBulkhead : IBulkhead |
| | | 6 | | { |
| | | 7 | | private readonly BulkheadOptions _options; |
| | | 8 | | private readonly SemaphoreSlim _semaphore; |
| | | 9 | | |
| | 6 | 10 | | public MemoryBulkhead(BulkheadOptions options) |
| | 6 | 11 | | { |
| | 6 | 12 | | _options = options; |
| | 6 | 13 | | var max = Math.Max(1, options.MaxParallelization); |
| | 6 | 14 | | _semaphore = new SemaphoreSlim(max, max); |
| | 6 | 15 | | } |
| | | 16 | | |
| | 2 | 17 | | public int AvailableSlots => _semaphore.CurrentCount; |
| | 0 | 18 | | public int QueueSize => _options.MaxParallelization - _semaphore.CurrentCount; |
| | | 19 | | |
| | | 20 | | public async Task<T> ExecuteAsync<T>(Func<Task<T>> operation, CancellationToken cancellationToken = default) |
| | 9 | 21 | | { |
| | 9 | 22 | | if (_options.MaxParallelization <= 0) |
| | 1 | 23 | | throw new BulkheadFullException(); |
| | | 24 | | |
| | 8 | 25 | | if (!await _semaphore.WaitAsync(_options.QueueTimeout, cancellationToken)) |
| | 1 | 26 | | throw new BulkheadFullException(); |
| | | 27 | | |
| | | 28 | | try |
| | 6 | 29 | | { |
| | 6 | 30 | | return await operation(); |
| | | 31 | | } |
| | | 32 | | finally |
| | 5 | 33 | | { |
| | 5 | 34 | | _semaphore.Release(); |
| | 5 | 35 | | } |
| | 5 | 36 | | } |
| | | 37 | | } |