< Summary

Information
Class: Elsa.Scheduling.Services.PastDueScheduleStaggerer
Assembly: Elsa.Scheduling
File(s): /home/runner/work/elsa-core/elsa-core/src/modules/Elsa.Scheduling/Services/PastDueScheduleStaggerer.cs
Line coverage
88%
Covered lines: 15
Uncovered lines: 2
Coverable lines: 17
Total lines: 39
Line coverage: 88.2%
Branch coverage
60%
Covered branches: 6
Total branches: 10
Branch coverage: 60%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
GetDelay(...)62.5%8886.66%
GetPositiveOrDefault(...)50%22100%

File(s)

/home/runner/work/elsa-core/elsa-core/src/modules/Elsa.Scheduling/Services/PastDueScheduleStaggerer.cs

#LineLine coverage
 1using Elsa.Scheduling.Options;
 2using Microsoft.Extensions.Options;
 3
 4namespace 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>
 99public class PastDueScheduleStaggerer(IOptions<SchedulingOptions> options)
 10{
 11    private long _sequence;
 12
 13    public TimeSpan GetDelay(TimeSpan calculatedDelay)
 14    {
 3615        if (calculatedDelay > TimeSpan.Zero)
 1416            return calculatedDelay;
 17
 2218        var currentOptions = options.Value;
 2219        var minimumDelay = GetPositiveOrDefault(currentOptions.MinimumPastDueScheduleDelay, TimeSpan.FromMilliseconds(1)
 2220        var staggerInterval = currentOptions.PastDueScheduleStaggerInterval;
 2221        var staggerWindow = currentOptions.PastDueScheduleStaggerWindow;
 22
 2223        if (staggerInterval <= TimeSpan.Zero || staggerWindow <= TimeSpan.Zero)
 024            return minimumDelay;
 25
 2226        var availableWindow = staggerWindow - minimumDelay;
 27
 2228        if (availableWindow <= TimeSpan.Zero)
 029            return minimumDelay;
 30
 2231        var slotCount = Math.Max(1, availableWindow.Ticks / staggerInterval.Ticks + 1);
 2232        var sequence = Interlocked.Increment(ref _sequence) - 1;
 2233        var slot = (sequence & long.MaxValue) % slotCount;
 34
 2235        return minimumDelay + TimeSpan.FromTicks(staggerInterval.Ticks * slot);
 36    }
 37
 2238    private static TimeSpan GetPositiveOrDefault(TimeSpan value, TimeSpan defaultValue) => value > TimeSpan.Zero ? value
 39}