| | | 1 | | using Elsa.Scheduling.Options; |
| | | 2 | | using Microsoft.Extensions.Options; |
| | | 3 | | |
| | | 4 | | namespace Elsa.Scheduling.Services; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// Distributes already-due schedules over a bounded window to avoid dispatch storms during startup catch-up. |
| | | 8 | | /// </summary> |
| | 9 | 9 | | public class PastDueScheduleStaggerer(IOptions<SchedulingOptions> options) |
| | | 10 | | { |
| | | 11 | | private long _sequence; |
| | | 12 | | |
| | | 13 | | public TimeSpan GetDelay(TimeSpan calculatedDelay) |
| | | 14 | | { |
| | 36 | 15 | | if (calculatedDelay > TimeSpan.Zero) |
| | 14 | 16 | | return calculatedDelay; |
| | | 17 | | |
| | 22 | 18 | | var currentOptions = options.Value; |
| | 22 | 19 | | var minimumDelay = GetPositiveOrDefault(currentOptions.MinimumPastDueScheduleDelay, TimeSpan.FromMilliseconds(1) |
| | 22 | 20 | | var staggerInterval = currentOptions.PastDueScheduleStaggerInterval; |
| | 22 | 21 | | var staggerWindow = currentOptions.PastDueScheduleStaggerWindow; |
| | | 22 | | |
| | 22 | 23 | | if (staggerInterval <= TimeSpan.Zero || staggerWindow <= TimeSpan.Zero) |
| | 0 | 24 | | return minimumDelay; |
| | | 25 | | |
| | 22 | 26 | | var availableWindow = staggerWindow - minimumDelay; |
| | | 27 | | |
| | 22 | 28 | | if (availableWindow <= TimeSpan.Zero) |
| | 0 | 29 | | return minimumDelay; |
| | | 30 | | |
| | 22 | 31 | | var slotCount = Math.Max(1, availableWindow.Ticks / staggerInterval.Ticks + 1); |
| | 22 | 32 | | var sequence = Interlocked.Increment(ref _sequence) - 1; |
| | 22 | 33 | | var slot = (sequence & long.MaxValue) % slotCount; |
| | | 34 | | |
| | 22 | 35 | | return minimumDelay + TimeSpan.FromTicks(staggerInterval.Ticks * slot); |
| | | 36 | | } |
| | | 37 | | |
| | 22 | 38 | | private static TimeSpan GetPositiveOrDefault(TimeSpan value, TimeSpan defaultValue) => value > TimeSpan.Zero ? value |
| | | 39 | | } |