| | | 1 | | using Anichron.Core.Work; |
| | | 2 | | using Anichron.Worker.Scheduling; |
| | | 3 | | using Anichron.Worker.Settings; |
| | | 4 | | using Microsoft.Extensions.Options; |
| | | 5 | | using NodaTime; |
| | | 6 | | |
| | | 7 | | namespace Anichron.Worker.Work; |
| | | 8 | | |
| | 34 | 9 | | public sealed partial class WorkExecutor( |
| | 34 | 10 | | IWorkItemStore store, |
| | 34 | 11 | | WorkHandlerRegistry registry, |
| | 34 | 12 | | WorkerState workerState, |
| | 34 | 13 | | IServiceScopeFactory scopeFactory, |
| | 34 | 14 | | TimeProvider timeProvider, |
| | 34 | 15 | | IOptions<WorkerSettings> options, |
| | 34 | 16 | | ILogger<WorkExecutor> logger) : BackgroundService |
| | | 17 | | { |
| | 34 | 18 | | private readonly WorkerSettings settings = options.Value; |
| | 34 | 19 | | private readonly string claimant = ClaimantName(options.Value, Environment.MachineName); |
| | 34 | 20 | | private readonly OutageLog outage = new(logger, "Claiming or finishing work"); |
| | | 21 | | |
| | | 22 | | internal static string ClaimantName(WorkerSettings settings, string host) |
| | 36 | 23 | | => $"{(settings.User.Length == 0 ? "all" : settings.User)}@{host}"; |
| | | 24 | | |
| | | 25 | | protected override Task ExecuteAsync(CancellationToken stoppingToken) |
| | 33 | 26 | | => RecurringWork.RunAsync( |
| | 33 | 27 | | DrainOrLogAsync, TimeSpan.FromSeconds(settings.WorkPollIntervalSeconds), timeProvider, stoppingToken); |
| | | 28 | | |
| | 93 | 29 | | private Duration Lease => Duration.FromSeconds(settings.WorkLeaseSeconds); |
| | | 30 | | |
| | 44 | 31 | | private TimeSpan SelfStopAfter => TimeSpan.FromSeconds(settings.WorkLeaseSeconds) / 2; |
| | | 32 | | |
| | 83 | 33 | | private Instant Now => Instant.FromDateTimeOffset(timeProvider.GetUtcNow()); |
| | | 34 | | |
| | | 35 | | private async Task DrainOrLogAsync(CancellationToken stopping) |
| | 43 | 36 | | { |
| | | 37 | | try |
| | 43 | 38 | | { |
| | 63 | 39 | | while (await ClaimAsync(stopping) is { } work) |
| | 28 | 40 | | await RunAsync(work, stopping); |
| | 29 | 41 | | } |
| | 14 | 42 | | catch (Exception ex) when (!stopping.IsCancellationRequested) |
| | 6 | 43 | | { |
| | 6 | 44 | | outage.Failed(ex); |
| | 6 | 45 | | } |
| | 35 | 46 | | } |
| | | 47 | | |
| | | 48 | | private async Task<ClaimedWork?> ClaimAsync(CancellationToken stopping) |
| | 63 | 49 | | { |
| | 63 | 50 | | var work = await store.ClaimAsync(claimant, workerState.ResolvedUserId, Now, Lease, stopping); |
| | 57 | 51 | | outage.Succeeded(); |
| | 57 | 52 | | return work; |
| | 57 | 53 | | } |
| | | 54 | | |
| | | 55 | | private async Task RunAsync(ClaimedWork work, CancellationToken stopping) |
| | 28 | 56 | | { |
| | 28 | 57 | | using var selfStop = new CancellationTokenSource(SelfStopAfter, timeProvider); |
| | 28 | 58 | | using var running = CancellationTokenSource.CreateLinkedTokenSource(stopping, selfStop.Token); |
| | 28 | 59 | | using var done = new CancellationTokenSource(); |
| | 28 | 60 | | var progress = new WorkProgressSink(); |
| | 28 | 61 | | await using var scope = scopeFactory.CreateAsyncScope(); |
| | 28 | 62 | | var heartbeat = HeartbeatAsync(work.Attempt, progress, running, selfStop, done.Token); |
| | | 63 | | |
| | 28 | 64 | | object? result = null; |
| | 28 | 65 | | Exception? failure = null; |
| | | 66 | | try |
| | 28 | 67 | | { |
| | 28 | 68 | | result = await Task.Run( |
| | 28 | 69 | | () => registry.RunAsync(work, scope.ServiceProvider, progress, running.Token), CancellationToken.None); |
| | 7 | 70 | | } |
| | 21 | 71 | | catch (Exception ex) |
| | 21 | 72 | | { |
| | 21 | 73 | | failure = ex; |
| | 21 | 74 | | } |
| | | 75 | | |
| | 28 | 76 | | await done.CancelAsync(); |
| | 28 | 77 | | var lastHeartbeat = await heartbeat; |
| | 28 | 78 | | if (lastHeartbeat == HeartbeatOutcome.Lost) |
| | 3 | 79 | | { |
| | 3 | 80 | | Log.Fenced(logger, work.Attempt.Id); |
| | 3 | 81 | | } |
| | 25 | 82 | | else if (selfStop.IsCancellationRequested) |
| | 5 | 83 | | { |
| | 5 | 84 | | Log.SelfStopped(logger, work.Attempt.Id); |
| | 5 | 85 | | } |
| | 20 | 86 | | else if (lastHeartbeat == HeartbeatOutcome.CancelRequested && failure is null or OperationCanceledException) |
| | 4 | 87 | | { |
| | 4 | 88 | | await store.CancelAsync( |
| | 4 | 89 | | work.Attempt, progress.Snapshot, WorkJson.SerializeResult(result), Now, CancellationToken.None); |
| | 4 | 90 | | Log.Cancelled(logger, work.Attempt.Id); |
| | 4 | 91 | | } |
| | 16 | 92 | | else if (failure is null) |
| | 4 | 93 | | { |
| | 4 | 94 | | await store.SucceedAsync( |
| | 4 | 95 | | work.Attempt, progress.Snapshot, WorkJson.SerializeResult(result), Now, CancellationToken.None); |
| | 4 | 96 | | } |
| | 12 | 97 | | else if (failure is OperationCanceledException && stopping.IsCancellationRequested) |
| | 8 | 98 | | { |
| | 8 | 99 | | await store.ReleaseAsync(work.Attempt, Now, CancellationToken.None); |
| | 8 | 100 | | Log.Released(logger, work.Attempt.Id); |
| | 8 | 101 | | stopping.ThrowIfCancellationRequested(); |
| | 0 | 102 | | } |
| | | 103 | | else |
| | 4 | 104 | | { |
| | 4 | 105 | | await store.FailAsync( |
| | 4 | 106 | | work.Attempt, progress.Snapshot, $"{failure.GetType().Name}: {failure.Message}", Now, CancellationToken. |
| | 4 | 107 | | Log.Failed(logger, work.Attempt.Id, work.Kind, failure); |
| | 4 | 108 | | } |
| | 20 | 109 | | } |
| | | 110 | | |
| | | 111 | | private async Task<HeartbeatOutcome> HeartbeatAsync( |
| | | 112 | | WorkAttempt attempt, WorkProgressSink progress, CancellationTokenSource running, CancellationTokenSource selfSto |
| | | 113 | | CancellationToken done) |
| | 28 | 114 | | { |
| | 28 | 115 | | var interval = TimeSpan.FromSeconds(settings.WorkHeartbeatSeconds); |
| | 28 | 116 | | var outcome = HeartbeatOutcome.Held; |
| | 55 | 117 | | while (!done.IsCancellationRequested) |
| | 55 | 118 | | { |
| | | 119 | | try |
| | 55 | 120 | | { |
| | 55 | 121 | | await Task.Delay(interval, timeProvider, done); |
| | 30 | 122 | | } |
| | 25 | 123 | | catch (OperationCanceledException) when (done.IsCancellationRequested) |
| | 25 | 124 | | { |
| | 25 | 125 | | break; |
| | | 126 | | } |
| | | 127 | | |
| | | 128 | | try |
| | 30 | 129 | | { |
| | 30 | 130 | | using var limit = new CancellationTokenSource(interval, timeProvider); |
| | 30 | 131 | | var sentAt = timeProvider.GetUtcNow(); |
| | 30 | 132 | | var beat = await store.HeartbeatAsync(attempt, progress.Snapshot, Instant.FromDateTimeOffset(sentAt), Le |
| | 30 | 133 | | .WaitAsync(limit.Token); |
| | 16 | 134 | | selfStop.CancelAfter(SelfStopAfter - (timeProvider.GetUtcNow() - sentAt)); |
| | 16 | 135 | | if (beat != HeartbeatOutcome.Held) |
| | 10 | 136 | | await running.CancelAsync(); |
| | 16 | 137 | | if (beat == HeartbeatOutcome.Lost) |
| | 3 | 138 | | return beat; |
| | 13 | 139 | | outcome = beat; |
| | 13 | 140 | | } |
| | 14 | 141 | | catch (Exception ex) |
| | 14 | 142 | | { |
| | 14 | 143 | | Log.HeartbeatFailed(logger, attempt.Id, ex); |
| | 14 | 144 | | } |
| | 27 | 145 | | } |
| | | 146 | | |
| | 25 | 147 | | return outcome; |
| | 28 | 148 | | } |
| | | 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 | | } |