< Summary

Line coverage
99%
Covered lines: 123
Uncovered lines: 1
Coverable lines: 124
Total lines: 1634
Line coverage: 99.1%
Branch coverage
100%
Covered branches: 30
Total branches: 30
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
File 1: .cctor()100%11100%
File 2: .ctor(...)100%11100%
File 2: ClaimantName(...)100%22100%
File 2: ExecuteAsync(...)100%11100%
File 2: get_Lease()100%11100%
File 2: get_SelfStopAfter()100%11100%
File 2: get_Now()100%11100%
File 2: DrainOrLogAsync()100%22100%
File 2: ClaimAsync()100%11100%
File 2: RunAsync()100%161698%
File 2: HeartbeatAsync()100%1010100%

File(s)

/home/runner/work/anichron/anichron/src/.artifacts/obj/Anichron.Worker/debug/Microsoft.Extensions.Logging.Generators/Microsoft.Extensions.Logging.Generators.LoggerMessageGenerator/LoggerMessage.g.cs

File '/home/runner/work/anichron/anichron/src/.artifacts/obj/Anichron.Worker/debug/Microsoft.Extensions.Logging.Generators/Microsoft.Extensions.Logging.Generators.LoggerMessageGenerator/LoggerMessage.g.cs' does not exist (any more).

/home/runner/work/anichron/anichron/src/Anichron.Worker/Work/WorkExecutor.cs

#LineLine coverage
 1using Anichron.Core.Work;
 2using Anichron.Worker.Scheduling;
 3using Anichron.Worker.Settings;
 4using Microsoft.Extensions.Options;
 5using NodaTime;
 6
 7namespace Anichron.Worker.Work;
 8
 349public sealed partial class WorkExecutor(
 3410    IWorkItemStore store,
 3411    WorkHandlerRegistry registry,
 3412    WorkerState workerState,
 3413    IServiceScopeFactory scopeFactory,
 3414    TimeProvider timeProvider,
 3415    IOptions<WorkerSettings> options,
 3416    ILogger<WorkExecutor> logger) : BackgroundService
 17{
 3418    private readonly WorkerSettings settings = options.Value;
 3419    private readonly string claimant = ClaimantName(options.Value, Environment.MachineName);
 3420    private readonly OutageLog outage = new(logger, "Claiming or finishing work");
 21
 22    internal static string ClaimantName(WorkerSettings settings, string host)
 3623        => $"{(settings.User.Length == 0 ? "all" : settings.User)}@{host}";
 24
 25    protected override Task ExecuteAsync(CancellationToken stoppingToken)
 3326        => RecurringWork.RunAsync(
 3327            DrainOrLogAsync, TimeSpan.FromSeconds(settings.WorkPollIntervalSeconds), timeProvider, stoppingToken);
 28
 9329    private Duration Lease => Duration.FromSeconds(settings.WorkLeaseSeconds);
 30
 4431    private TimeSpan SelfStopAfter => TimeSpan.FromSeconds(settings.WorkLeaseSeconds) / 2;
 32
 8333    private Instant Now => Instant.FromDateTimeOffset(timeProvider.GetUtcNow());
 34
 35    private async Task DrainOrLogAsync(CancellationToken stopping)
 4336    {
 37        try
 4338        {
 6339            while (await ClaimAsync(stopping) is { } work)
 2840                await RunAsync(work, stopping);
 2941        }
 1442        catch (Exception ex) when (!stopping.IsCancellationRequested)
 643        {
 644            outage.Failed(ex);
 645        }
 3546    }
 47
 48    private async Task<ClaimedWork?> ClaimAsync(CancellationToken stopping)
 6349    {
 6350        var work = await store.ClaimAsync(claimant, workerState.ResolvedUserId, Now, Lease, stopping);
 5751        outage.Succeeded();
 5752        return work;
 5753    }
 54
 55    private async Task RunAsync(ClaimedWork work, CancellationToken stopping)
 2856    {
 2857        using var selfStop = new CancellationTokenSource(SelfStopAfter, timeProvider);
 2858        using var running = CancellationTokenSource.CreateLinkedTokenSource(stopping, selfStop.Token);
 2859        using var done = new CancellationTokenSource();
 2860        var progress = new WorkProgressSink();
 2861        await using var scope = scopeFactory.CreateAsyncScope();
 2862        var heartbeat = HeartbeatAsync(work.Attempt, progress, running, selfStop, done.Token);
 63
 2864        object? result = null;
 2865        Exception? failure = null;
 66        try
 2867        {
 2868            result = await Task.Run(
 2869                () => registry.RunAsync(work, scope.ServiceProvider, progress, running.Token), CancellationToken.None);
 770        }
 2171        catch (Exception ex)
 2172        {
 2173            failure = ex;
 2174        }
 75
 2876        await done.CancelAsync();
 2877        var lastHeartbeat = await heartbeat;
 2878        if (lastHeartbeat == HeartbeatOutcome.Lost)
 379        {
 380            Log.Fenced(logger, work.Attempt.Id);
 381        }
 2582        else if (selfStop.IsCancellationRequested)
 583        {
 584            Log.SelfStopped(logger, work.Attempt.Id);
 585        }
 2086        else if (lastHeartbeat == HeartbeatOutcome.CancelRequested && failure is null or OperationCanceledException)
 487        {
 488            await store.CancelAsync(
 489                work.Attempt, progress.Snapshot, WorkJson.SerializeResult(result), Now, CancellationToken.None);
 490            Log.Cancelled(logger, work.Attempt.Id);
 491        }
 1692        else if (failure is null)
 493        {
 494            await store.SucceedAsync(
 495                work.Attempt, progress.Snapshot, WorkJson.SerializeResult(result), Now, CancellationToken.None);
 496        }
 1297        else if (failure is OperationCanceledException && stopping.IsCancellationRequested)
 898        {
 899            await store.ReleaseAsync(work.Attempt, Now, CancellationToken.None);
 8100            Log.Released(logger, work.Attempt.Id);
 8101            stopping.ThrowIfCancellationRequested();
 0102        }
 103        else
 4104        {
 4105            await store.FailAsync(
 4106                work.Attempt, progress.Snapshot, $"{failure.GetType().Name}: {failure.Message}", Now, CancellationToken.
 4107            Log.Failed(logger, work.Attempt.Id, work.Kind, failure);
 4108        }
 20109    }
 110
 111    private async Task<HeartbeatOutcome> HeartbeatAsync(
 112        WorkAttempt attempt, WorkProgressSink progress, CancellationTokenSource running, CancellationTokenSource selfSto
 113        CancellationToken done)
 28114    {
 28115        var interval = TimeSpan.FromSeconds(settings.WorkHeartbeatSeconds);
 28116        var outcome = HeartbeatOutcome.Held;
 55117        while (!done.IsCancellationRequested)
 55118        {
 119            try
 55120            {
 55121                await Task.Delay(interval, timeProvider, done);
 30122            }
 25123            catch (OperationCanceledException) when (done.IsCancellationRequested)
 25124            {
 25125                break;
 126            }
 127
 128            try
 30129            {
 30130                using var limit = new CancellationTokenSource(interval, timeProvider);
 30131                var sentAt = timeProvider.GetUtcNow();
 30132                var beat = await store.HeartbeatAsync(attempt, progress.Snapshot, Instant.FromDateTimeOffset(sentAt), Le
 30133                    .WaitAsync(limit.Token);
 16134                selfStop.CancelAfter(SelfStopAfter - (timeProvider.GetUtcNow() - sentAt));
 16135                if (beat != HeartbeatOutcome.Held)
 10136                    await running.CancelAsync();
 16137                if (beat == HeartbeatOutcome.Lost)
 3138                    return beat;
 13139                outcome = beat;
 13140            }
 14141            catch (Exception ex)
 14142            {
 14143                Log.HeartbeatFailed(logger, attempt.Id, ex);
 14144            }
 27145        }
 146
 25147        return outcome;
 28148    }
 149
 150    private static partial class Log
 151    {
 152        [LoggerMessage(Level = LogLevel.Error, Message = "Work item {Id} ({Kind}) failed.")]
 153        public static partial void Failed(ILogger logger, Guid id, Core.Domain.WorkKind kind, Exception ex);
 154
 155        [LoggerMessage(Level = LogLevel.Information, Message = "Work item {Id} was handed back to the queue at shutdown.
 156        public static partial void Released(ILogger logger, Guid id);
 157
 158        [LoggerMessage(Level = LogLevel.Information, Message = "Work item {Id} was cancelled at an admin's request.")]
 159        public static partial void Cancelled(ILogger logger, Guid id);
 160
 161        [LoggerMessage(Level = LogLevel.Warning, Message = "Work item {Id} is no longer held by this attempt (its lease 
 162        public static partial void Fenced(ILogger logger, Guid id);
 163
 164        [LoggerMessage(Level = LogLevel.Warning, Message = "Work item {Id} stopped itself: no heartbeat reached the data
 165        public static partial void SelfStopped(ILogger logger, Guid id);
 166
 167        [LoggerMessage(Level = LogLevel.Warning, Message = "Heartbeat for work item {Id} failed; will retry.")]
 168        public static partial void HeartbeatFailed(ILogger logger, Guid id, Exception ex);
 169    }
 170}