| | | 1 | | namespace ArturRios.Util.FlowControl.Waiter; |
| | | 2 | | |
| | | 3 | | /// <summary> |
| | | 4 | | /// Implements an exponential backoff waiting strategy with jitter to reduce contention. |
| | | 5 | | /// </summary> |
| | | 6 | | /// <remarks> |
| | | 7 | | /// Wait times grow exponentially (2^n seconds base minus a fixed delay) and a random jitter is added. |
| | | 8 | | /// Call <see cref="Wait"/> before each retry attempt until <see cref="CanRetry"/> is false. |
| | | 9 | | /// </remarks> |
| | | 10 | | /// <param name="maxRetryCount">Maximum number of retries allowed.</param> |
| | 6 | 11 | | public class JitteredWaiter(int maxRetryCount) |
| | | 12 | | { |
| | | 13 | | private const int FixedWaitDelay = 500; |
| | | 14 | | |
| | | 15 | | /// <summary> |
| | | 16 | | /// Maximum number of retries permitted. |
| | | 17 | | /// </summary> |
| | 22 | 18 | | public int MaxRetryCount { get; } = maxRetryCount; |
| | | 19 | | |
| | 36 | 20 | | private int Count { get; set; } |
| | | 21 | | |
| | | 22 | | /// <summary> |
| | | 23 | | /// Indicates whether another retry attempt can be performed. |
| | | 24 | | /// </summary> |
| | 4 | 25 | | public bool CanRetry => Count < MaxRetryCount; |
| | | 26 | | |
| | | 27 | | /// <summary> |
| | | 28 | | /// Asynchronously waits based on the current retry attempt using exponential backoff with jitter. |
| | | 29 | | /// </summary> |
| | | 30 | | /// <exception cref="MaxRetriesReachedException">Thrown when called more times than <see cref="MaxRetryCount"/>.</ex |
| | | 31 | | public async Task Wait() |
| | 12 | 32 | | { |
| | 12 | 33 | | if (Count >= MaxRetryCount) |
| | 2 | 34 | | { |
| | 2 | 35 | | throw new MaxRetriesReachedException(); |
| | | 36 | | } |
| | | 37 | | |
| | 10 | 38 | | var currentRetryAttempt = Count++; |
| | | 39 | | |
| | 10 | 40 | | if (currentRetryAttempt == 0) |
| | 5 | 41 | | { |
| | 5 | 42 | | await Task.Delay(FixedWaitDelay); |
| | 5 | 43 | | } |
| | | 44 | | else |
| | 5 | 45 | | { |
| | 5 | 46 | | var backoffPeriodMs = Convert.ToInt32(Math.Pow(2, currentRetryAttempt) * 1000) - FixedWaitDelay; |
| | 5 | 47 | | await Task.Delay(FixedWaitDelay + backoffPeriodMs / 2 + new System.Random().Next(0, backoffPeriodMs / 2)); |
| | 5 | 48 | | } |
| | 10 | 49 | | } |
| | | 50 | | } |