• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

ImmediatePlatform / Immediate.Jobs / 30657938276

31 Jul 2026 07:08PM UTC coverage: 84.111% (+0.9%) from 83.228%
30657938276

push

github

web-flow
Retain job execution history (#82)

* Retain job execution history

* Address job retention review feedback

* Bound relational concurrency retries

723 of 843 new or added lines in 13 files covered. (85.77%)

14 existing lines in 4 files now uncovered.

8216 of 9768 relevant lines covered (84.11%)

2.7 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

83.82
/src/Immediate.Jobs.EntityFrameworkCore/EntityFrameworkCoreJobStorage.cs
1
using System.Data.Common;
2
using Microsoft.EntityFrameworkCore;
3

4
// TODO: remove and fix diagnostics
5
#pragma warning disable MA0015 // Specify the parameter name in ArgumentException
6

7
namespace Immediate.Jobs.EntityFrameworkCore;
8

9
/// <summary>An optimistic-concurrency EF Core implementation of <see cref="IJobStorage"/>.</summary>
10
/// <typeparam name="TContext">The application context containing the Immediate.Jobs model.</typeparam>
11
/// <param name="contextFactory">The factory used to create application database contexts.</param>
12
/// <param name="timeProvider">The clock used for storage timestamps, or <see langword="null"/> to use the system clock.</param>
13
public sealed class EntityFrameworkCoreJobStorage<TContext>(
5✔
14
        IDbContextFactory<TContext> contextFactory,
5✔
15
        TimeProvider? timeProvider = null
5✔
16
) : IRecurringJobStorage, IJobGraphStorage, IJobStorageReplica
5✔
17
        where TContext : DbContext
18
{
19
        private const int MaxConcurrencyAttempts = 5;
20
        private const int MaxConsecutiveFailedFairClaims = 5;
21
        private readonly TimeProvider _timeProvider = timeProvider ?? TimeProvider.System;
5✔
22

23
        /// <inheritdoc />
24
        public ValueTask DisposeAsync() => ValueTask.CompletedTask;
5✔
25

26
        /// <inheritdoc />
27
        public async ValueTask InitializeAsync(CancellationToken cancellationToken = default)
28
        {
29
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
4✔
30
                _ = context.Model.FindEntityType(typeof(ImmediateJobEntity))
4✔
31
                        ?? throw new ImmediateJobException("Immediate.Jobs entities are not configured. Call modelBuilder.AddImmediateJobs() from OnModelCreating.");
4✔
32
        }
3✔
33

34
        /// <inheritdoc />
35
        public async ValueTask EnqueueAsync(JobRecord job, CancellationToken cancellationToken = default)
36
        {
37
                ArgumentNullException.ThrowIfNull(job);
5✔
38
                await ExecuteWithStrategyAsync(
5✔
39
                        operationCancellationToken => EnqueueCoreAsync(job, operationCancellationToken),
5✔
40
                        cancellationToken
5✔
41
                ).ConfigureAwait(false);
5✔
42
        }
5✔
43

44
        private async Task EnqueueCoreAsync(JobRecord job, CancellationToken cancellationToken)
45
        {
46
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
47
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
5✔
48
                if (job.GroupId is { } groupId && !await HasLiveGroupJobsAsync(
5✔
49
                        context,
5✔
50
                        job.QueueName,
5✔
51
                        groupId,
5✔
52
                        cancellationToken
5✔
53
                ).ConfigureAwait(false))
5✔
54
                {
55
                        var cursor = await context.Set<ImmediateFairQueueGroupEntity>()
5✔
56
                                .SingleOrDefaultAsync(
5✔
57
                                        group => group.QueueName == job.QueueName && group.GroupId == groupId,
5✔
58
                                        cancellationToken
5✔
59
                                )
5✔
60
                                .ConfigureAwait(false);
5✔
61
                        if (cursor is not null)
5✔
62
                                _ = context.Remove(cursor);
4✔
63
                }
64

65
                _ = context.Set<ImmediateJobEntity>().Add(ToEntity(job));
5✔
66
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
5✔
67
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
5✔
68
        }
5✔
69

70
        /// <inheritdoc />
71
        public async ValueTask EnqueueContinuationAsync(
72
                JobRecord job,
73
                IReadOnlyList<JobContinuationEdge> edges,
74
                CancellationToken cancellationToken = default
75
        )
76
        {
77
                ArgumentNullException.ThrowIfNull(job);
5✔
78
                ArgumentNullException.ThrowIfNull(edges);
5✔
79
                await ExecuteGraphInsertAsync(batch: null, [job], edges, cancellationToken).ConfigureAwait(false);
5✔
80
        }
5✔
81

82
        /// <inheritdoc />
83
        public async ValueTask EnqueueBatchAsync(
84
                JobBatchRecord batch,
85
                IReadOnlyList<JobRecord> jobs,
86
                IReadOnlyList<JobContinuationEdge> edges,
87
                CancellationToken cancellationToken = default
88
        )
89
        {
90
                ArgumentNullException.ThrowIfNull(batch);
5✔
91
                ArgumentNullException.ThrowIfNull(jobs);
5✔
92
                ArgumentNullException.ThrowIfNull(edges);
5✔
93
                if (jobs.Count == 0)
5✔
94
                        throw new ImmediateJobException("An atomic batch cannot be committed without jobs.");
×
95
                await ExecuteGraphInsertAsync(batch, jobs, edges, cancellationToken).ConfigureAwait(false);
5✔
96
        }
5✔
97

98
        private ValueTask ExecuteGraphInsertAsync(
99
                JobBatchRecord? batch,
100
                IReadOnlyList<JobRecord> jobs,
101
                IReadOnlyList<JobContinuationEdge> edges,
102
                CancellationToken cancellationToken
103
        ) => RetryConcurrencyAsync(
5✔
104
                operationCancellationToken => InsertGraphCoreAsync(batch, jobs, edges, operationCancellationToken),
5✔
105
                cancellationToken
5✔
106
        );
5✔
107

108
        private async Task InsertGraphCoreAsync(
109
                JobBatchRecord? batch,
110
                IReadOnlyList<JobRecord> jobs,
111
                IReadOnlyList<JobContinuationEdge> edges,
112
                CancellationToken cancellationToken
113
        )
114
        {
115
                var jobIds = jobs.Select(static job => job.Id).ToHashSet(StringComparer.Ordinal);
5✔
116
                if (jobIds.Count != jobs.Count)
5✔
117
                        throw new ImmediateJobException("A batch or continuation insert contains duplicate job identifiers.");
×
118
                if (batch is not null && jobs.Any(job => !string.Equals(job.BatchId, batch.Id, StringComparison.Ordinal)))
5✔
119
                        throw new ImmediateJobException("Every atomic batch member must carry the committed batch identifier.");
×
120

121
                var edgeEntities = edges.Select(ToEntity).ToArray();
5✔
122
                if (edgeEntities.Any(edge => !jobIds.Contains(edge.ChildJobId)))
5✔
123
                        throw new ImmediateJobException("Every continuation edge must target a job inserted by the same operation.");
×
124
                if (edgeEntities.DistinctBy(static edge => (edge.ChildJobId, edge.ParentKind, edge.ParentId)).Count() != edgeEntities.Length)
5✔
125
                        throw new ImmediateJobException("Duplicate continuation edges are not allowed.");
×
126
                ThrowIfCyclic(jobIds, edgeEntities);
5✔
127

128
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
129
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
5✔
130
                var jobEntities = jobs.Select(ToEntity).ToDictionary(static job => job.Id, StringComparer.Ordinal);
5✔
131
                await EvaluateInitialDependenciesAsync(
5✔
132
                        context,
5✔
133
                        jobEntities,
5✔
134
                        edgeEntities,
5✔
135
                        _timeProvider.GetUtcNow(),
5✔
136
                        cancellationToken
5✔
137
                ).ConfigureAwait(false);
5✔
138

139
                if (batch is not null)
5✔
140
                {
141
                        var terminal = jobEntities.Values.Where(static job => IsTerminal(job.State)).ToArray();
5✔
142
                        var pending = jobEntities.Count - terminal.Length;
5✔
143
                        var succeeded = terminal.Count(static job => job.State == JobState.Succeeded);
4✔
144
                        var failed = terminal.Count(static job => job.State == JobState.Failed);
4✔
145
                        var cancelled = terminal.Count(static job => job.State == JobState.Cancelled);
4✔
146
                        var skipped = terminal.Count(static job => job.State == JobState.Skipped);
4✔
147
                        _ = context.Add(new ImmediateJobBatchEntity
5✔
148
                        {
5✔
149
                                Id = batch.Id,
5✔
150
                                CreatedAt = batch.CreatedAt,
5✔
151
                                TotalJobs = jobEntities.Count,
5✔
152
                                PendingCount = pending,
5✔
153
                                SucceededCount = succeeded,
5✔
154
                                FailedCount = failed,
5✔
155
                                CancelledCount = cancelled,
5✔
156
                                SkippedCount = skipped,
5✔
157
                                StartedAt = batch.StartedAt,
5✔
158
                                CompletedAt = pending == 0 ? batch.CompletedAt ?? _timeProvider.GetUtcNow() : null,
5✔
159
                                State = pending == 0 ? GetTerminalBatchState(failed, cancelled) : BatchState.Executing,
5✔
160
                                ConcurrencyStamp = Guid.NewGuid(),
5✔
161
                        });
5✔
162
                }
163

164
                context.AddRange(jobEntities.Values);
5✔
165
                context.AddRange(edgeEntities);
5✔
166
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
5✔
167
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
5✔
168
        }
5✔
169

170
        /// <inheritdoc />
171
        public async ValueTask<IReadOnlyList<JobRecord>> AcquireDueJobsAsync(
172
                JobAcquisitionRequest request,
173
                CancellationToken cancellationToken = default
174
        )
175
        {
176
                ArgumentNullException.ThrowIfNull(request);
5✔
177
                ArgumentException.ThrowIfNullOrWhiteSpace(request.WorkerId);
5✔
178
                ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(request.Lease, TimeSpan.Zero);
5✔
179
                ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(request.BatchSize, 0);
5✔
180
                if (request.FairQueues is not null)
5✔
181
                        return await AcquireDueJobsFairAsync(request, cancellationToken).ConfigureAwait(false);
5✔
182

183
                var now = _timeProvider.GetUtcNow();
5✔
184
                var acquired = new List<JobRecord>(request.BatchSize);
5✔
185
                foreach (var queue in request.Queues)
5✔
186
                {
187
                        var queueCapacity = Math.Min(queue.Capacity, request.BatchSize - acquired.Count);
5✔
188
                        if (queueCapacity <= 0)
5✔
189
                                continue;
190

191
                        var jobCapacities = queue.JobCapacities.ToDictionary(static pair => pair.Key, static pair => pair.Value, StringComparer.Ordinal);
5✔
192
                        while (queueCapacity > 0)
5✔
193
                        {
194
                                var eligibleNames = jobCapacities.Where(static pair => pair.Value > 0).Select(static pair => pair.Key).ToArray();
5✔
195
                                if (eligibleNames.Length == 0)
5✔
196
                                        break;
197

198
                                await using var readContext = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
199
                                var candidates = await readContext.Set<ImmediateJobEntity>()
5✔
200
                                        .AsNoTracking()
5✔
201
                                        .Where(job => job.QueueName == queue.QueueName && eligibleNames.Contains(job.JobName) &&
5✔
202
                                                (((job.State == JobState.Scheduled || job.State == JobState.Pending) && job.DueAt <= now)
5✔
203
                                                        || (job.State == JobState.Active && job.LeaseExpiresAt <= now)))
5✔
204
                                        .OrderBy(job => job.DueAt)
5✔
205
                                        .ThenBy(job => job.CreatedAt)
5✔
206
                                        .ThenBy(job => job.Id)
5✔
207
                                        .Take(queueCapacity)
5✔
208
                                        .ToListAsync(cancellationToken)
5✔
209
                                        .ConfigureAwait(false);
5✔
210
                                if (candidates.Count == 0)
5✔
211
                                        break;
212

213
                                var selected = new List<ImmediateJobEntity>(candidates.Count);
5✔
214
                                var selectionCapacities = new Dictionary<string, int>(jobCapacities, StringComparer.Ordinal);
5✔
215
                                foreach (var candidate in candidates)
5✔
216
                                {
217
                                        if (selectionCapacities[candidate.JobName] <= 0)
5✔
218
                                                continue;
219
                                        selectionCapacities[candidate.JobName]--;
5✔
220
                                        selected.Add(candidate);
5✔
221
                                }
222

223
                                var claimed = await AcquireCandidatesAsync(
5✔
224
                                        selected,
5✔
225
                                        request.WorkerId,
5✔
226
                                        request.Lease,
5✔
227
                                        now,
5✔
228
                                        cancellationToken
5✔
229
                                ).ConfigureAwait(false);
5✔
230
                                foreach (var job in claimed)
5✔
231
                                {
232
                                        jobCapacities[job.JobName]--;
5✔
233
                                        queueCapacity--;
5✔
234
                                        acquired.Add(job);
5✔
235
                                }
236

237
                                if (claimed.Count == 0)
5✔
238
                                        break;
239
                        }
4✔
240
                }
4✔
241

242
                return acquired;
5✔
243
        }
4✔
244

245
        private async ValueTask<IReadOnlyList<JobRecord>> AcquireDueJobsFairAsync(
246
                JobAcquisitionRequest request,
247
                CancellationToken cancellationToken
248
        )
249
        {
250
                var now = _timeProvider.GetUtcNow();
5✔
251
                var acquired = new List<JobRecord>(request.BatchSize);
5✔
252
                foreach (var queue in request.Queues)
5✔
253
                {
254
                        var consecutiveFailedClaims = 0;
5✔
255
                        var queueCapacity = Math.Min(queue.Capacity, request.BatchSize - acquired.Count);
5✔
256
                        if (queueCapacity <= 0)
5✔
257
                                continue;
258

259
                        var jobCapacities = queue.JobCapacities.ToDictionary(
5✔
260
                                static pair => pair.Key,
5✔
261
                                static pair => pair.Value,
5✔
262
                                StringComparer.Ordinal
5✔
263
                        );
5✔
264
                        while (queueCapacity > 0)
5✔
265
                        {
266
                                var eligibleNames = jobCapacities
5✔
267
                                        .Where(static pair => pair.Value > 0)
5✔
268
                                        .Select(static pair => pair.Key)
5✔
269
                                        .ToArray();
5✔
270
                                if (eligibleNames.Length == 0)
5✔
271
                                        break;
272

273
                                await using var readContext = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
274
                                var eligibleQuery = readContext.Set<ImmediateJobEntity>()
5✔
275
                                        .AsNoTracking()
5✔
276
                                        .Where(job => job.QueueName == queue.QueueName && eligibleNames.Contains(job.JobName) &&
5✔
277
                                                (((job.State == JobState.Scheduled || job.State == JobState.Pending) && job.DueAt <= now)
5✔
278
                                                        || (job.State == JobState.Active && job.LeaseExpiresAt <= now)));
5✔
279
                                if (!await eligibleQuery
5✔
280
                                        .AnyAsync(static job => job.GroupId != null, cancellationToken)
5✔
281
                                        .ConfigureAwait(false))
5✔
282
                                {
283
                                        var claimed = await AcquireFairFastPathAsync(
4✔
284
                                                queue.QueueName,
4✔
285
                                                jobCapacities,
4✔
286
                                                queueCapacity,
4✔
287
                                                request.WorkerId,
4✔
288
                                                request.Lease,
4✔
289
                                                now,
4✔
290
                                                cancellationToken
4✔
291
                                        ).ConfigureAwait(false);
4✔
292
                                        queueCapacity -= claimed.Count;
4✔
293
                                        acquired.AddRange(claimed);
4✔
294
                                        break;
4✔
295
                                }
296

297
                                var groupedHeads = await eligibleQuery
5✔
298
                                        .Where(static job => job.GroupId != null)
5✔
299
                                        .GroupBy(static job => job.GroupId)
5✔
300
                                        .Select(static group => group
5✔
301
                                                .OrderBy(job => job.DueAt)
5✔
302
                                                .ThenBy(job => job.CreatedAt)
5✔
303
                                                .ThenBy(job => job.Id)
5✔
304
                                                .First())
5✔
305
                                        .ToListAsync(cancellationToken)
5✔
306
                                        .ConfigureAwait(false);
5✔
307
                                var ungroupedHead = await eligibleQuery
5✔
308
                                        .Where(static job => job.GroupId == null)
5✔
309
                                        .OrderBy(job => job.DueAt)
5✔
310
                                        .ThenBy(job => job.CreatedAt)
5✔
311
                                        .ThenBy(job => job.Id)
5✔
312
                                        .FirstOrDefaultAsync(cancellationToken)
5✔
313
                                        .ConfigureAwait(false);
5✔
314
                                if (groupedHeads.Count == 0)
5✔
315
                                {
316
                                        var claimed = await AcquireFairFastPathAsync(
×
317
                                                queue.QueueName,
×
318
                                                jobCapacities,
×
319
                                                queueCapacity,
×
320
                                                request.WorkerId,
×
321
                                                request.Lease,
×
322
                                                now,
×
323
                                                cancellationToken
×
324
                                        ).ConfigureAwait(false);
×
325
                                        queueCapacity -= claimed.Count;
×
326
                                        acquired.AddRange(claimed);
×
327
                                        break;
×
328
                                }
329

330
                                var activeQuery = readContext.Set<ImmediateJobEntity>()
5✔
331
                                        .AsNoTracking()
5✔
332
                                        .Where(job => job.QueueName == queue.QueueName
5✔
333
                                                && job.State == JobState.Active
5✔
334
                                                && job.LeaseExpiresAt > now);
5✔
335
                                var totalInflight = await activeQuery
5✔
336
                                        .CountAsync(cancellationToken)
5✔
337
                                        .ConfigureAwait(false);
5✔
338
                                var groupedHeadIds = groupedHeads.Select(static job => job.Id).ToArray();
5✔
339
                                var cursorQuery = readContext.Set<ImmediateFairQueueGroupEntity>()
5✔
340
                                        .AsNoTracking()
5✔
341
                                        .Where(group => group.QueueName == queue.QueueName);
5✔
342
                                var groupStateQuery = eligibleQuery
5✔
343
                                        .Where(job => groupedHeadIds.Contains(job.Id));
5✔
344
                                var groupStates = request.FairQueues!.GroupRoundRobin
5✔
345
                                        ? await groupStateQuery
5✔
346
                                                .Select(job => new FairQueueCandidateState(
5✔
347
                                                        job.Id,
5✔
348
                                                        activeQuery.Count(active => active.GroupId == job.GroupId),
5✔
349
                                                        cursorQuery
5✔
350
                                                                .Where(cursor => cursor.GroupId == job.GroupId)
5✔
351
                                                                .Select(static cursor => cursor.LastServedSequence)
5✔
352
                                                                .FirstOrDefault()
5✔
353
                                                ))
5✔
354
                                                .ToDictionaryAsync(static state => state.JobId, StringComparer.Ordinal, cancellationToken)
5✔
355
                                                .ConfigureAwait(false)
5✔
356
                                        : await groupStateQuery
5✔
357
                                                .Select(job => new FairQueueCandidateState(
5✔
358
                                                        job.Id,
5✔
359
                                                        activeQuery.Count(active => active.GroupId == job.GroupId),
5✔
360
                                                        0
5✔
361
                                                ))
5✔
362
                                                .ToDictionaryAsync(static state => state.JobId, StringComparer.Ordinal, cancellationToken)
4✔
363
                                                .ConfigureAwait(false);
5✔
364
                                var nextSequence = 0L;
5✔
365
                                if (request.FairQueues.GroupRoundRobin)
5✔
366
                                {
367
                                        var maxSequence = await cursorQuery
5✔
368
                                                .MaxAsync(static group => (long?)group.LastServedSequence, cancellationToken)
5✔
369
                                                .ConfigureAwait(false);
5✔
370
                                        nextSequence = (maxSequence ?? 0) + 1;
5✔
371
                                }
372

373
                                var candidates = ungroupedHead is null ? groupedHeads : [.. groupedHeads, ungroupedHead];
5✔
374
                                var ranked = candidates.Select(job =>
5✔
375
                                {
5✔
376
                                        FairQueueCandidateState? state = null;
5✔
377
                                        if (job.GroupId is not null)
5✔
378
                                                _ = groupStates.TryGetValue(job.Id, out state);
5✔
379
                                        var noisy = IsNoisy(job.GroupId, state?.Inflight ?? 0, totalInflight, request.FairQueues);
5✔
380
                                        return new
5✔
381
                                        {
5✔
382
                                                Job = job,
5✔
383
                                                Noisy = noisy,
5✔
384
                                                NoisyInflight = noisy ? state!.Inflight : 0,
5✔
385
                                                LastServedSequence = state?.LastServedSequence ?? 0,
5✔
386
                                        };
5✔
387
                                });
5✔
388
                                var selected = ranked
5✔
389
                                        .OrderBy(static candidate => candidate.Noisy)
5✔
390
                                        .ThenBy(static candidate => candidate.NoisyInflight)
5✔
391
                                        .ThenBy(candidate => request.FairQueues.GroupRoundRobin
5✔
392
                                                ? candidate.LastServedSequence
5✔
393
                                                : 0)
5✔
394
                                        .ThenBy(static candidate => candidate.Job.DueAt)
5✔
395
                                        .ThenBy(static candidate => candidate.Job.CreatedAt)
5✔
396
                                        .ThenBy(static candidate => candidate.Job.Id, StringComparer.Ordinal)
5✔
397
                                        .First()
5✔
398
                                        .Job;
5✔
399
                                var claimedJob = request.FairQueues.GroupRoundRobin
5✔
400
                                        ? await AcquireFairCandidateAsync(
5✔
401
                                                selected,
5✔
402
                                                request.WorkerId,
5✔
403
                                                request.Lease,
5✔
404
                                                now,
5✔
405
                                                nextSequence,
5✔
406
                                                cancellationToken
5✔
407
                                        ).ConfigureAwait(false)
5✔
408
                                        : GetFirstOrDefault(await AcquireCandidatesAsync(
5✔
409
                                                        [selected],
5✔
410
                                                        request.WorkerId,
5✔
411
                                                        request.Lease,
5✔
412
                                                        now,
5✔
413
                                                        cancellationToken
5✔
414
                                                ).ConfigureAwait(false));
5✔
415
                                if (claimedJob is null)
5✔
416
                                {
417
                                        if (++consecutiveFailedClaims >= MaxConsecutiveFailedFairClaims)
4✔
418
                                                break;
4✔
419
                                        continue;
420
                                }
421

422
                                consecutiveFailedClaims = 0;
5✔
423
                                jobCapacities[claimedJob.JobName]--;
5✔
424
                                queueCapacity--;
5✔
425
                                acquired.Add(claimedJob);
5✔
426
                        }
4✔
427
                }
4✔
428

429
                return acquired;
5✔
430
        }
4✔
431

432
        private async ValueTask<IReadOnlyList<JobRecord>> AcquireFairFastPathAsync(
433
                string queueName,
434
                Dictionary<string, int> jobCapacities,
435
                int queueCapacity,
436
                string workerId,
437
                TimeSpan lease,
438
                DateTimeOffset now,
439
                CancellationToken cancellationToken
440
        )
441
        {
442
                var acquired = new List<JobRecord>(queueCapacity);
4✔
443
                while (queueCapacity > 0)
4✔
444
                {
445
                        var eligibleNames = jobCapacities
4✔
446
                                .Where(static pair => pair.Value > 0)
4✔
447
                                .Select(static pair => pair.Key)
4✔
448
                                .ToArray();
4✔
449
                        if (eligibleNames.Length == 0)
4✔
450
                                break;
451

452
                        await using var readContext = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
4✔
453
                        var candidates = await readContext.Set<ImmediateJobEntity>()
4✔
454
                                .AsNoTracking()
4✔
455
                                .Where(job => job.QueueName == queueName && eligibleNames.Contains(job.JobName) &&
4✔
456
                                        (((job.State == JobState.Scheduled || job.State == JobState.Pending) && job.DueAt <= now)
4✔
457
                                                || (job.State == JobState.Active && job.LeaseExpiresAt <= now)))
4✔
458
                                .OrderBy(job => job.DueAt)
4✔
459
                                .ThenBy(job => job.CreatedAt)
4✔
460
                                .ThenBy(job => job.Id)
4✔
461
                                .Take(queueCapacity)
4✔
462
                                .ToListAsync(cancellationToken)
4✔
463
                                .ConfigureAwait(false);
4✔
464
                        if (candidates.Count == 0)
4✔
465
                                break;
466

467
                        var selected = new List<ImmediateJobEntity>(candidates.Count);
4✔
468
                        var selectionCapacities = new Dictionary<string, int>(jobCapacities, StringComparer.Ordinal);
4✔
469
                        foreach (var candidate in candidates)
4✔
470
                        {
471
                                if (selectionCapacities[candidate.JobName] <= 0)
4✔
472
                                        continue;
473
                                selectionCapacities[candidate.JobName]--;
4✔
474
                                selected.Add(candidate);
4✔
475
                        }
476

477
                        var claimed = await AcquireCandidatesAsync(
4✔
478
                                selected,
4✔
479
                                workerId,
4✔
480
                                lease,
4✔
481
                                now,
4✔
482
                                cancellationToken
4✔
483
                        ).ConfigureAwait(false);
4✔
484
                        foreach (var job in claimed)
4✔
485
                        {
486
                                jobCapacities[job.JobName]--;
4✔
487
                                queueCapacity--;
4✔
488
                                acquired.Add(job);
4✔
489
                        }
490

491
                        if (claimed.Count == 0)
4✔
492
                                break;
493
                }
3✔
494

495
                return acquired;
4✔
496
        }
3✔
497

498
        private async ValueTask<JobRecord?> AcquireFairCandidateAsync(
499
                ImmediateJobEntity candidate,
500
                string workerId,
501
                TimeSpan lease,
502
                DateTimeOffset now,
503
                long nextSequence,
504
                CancellationToken cancellationToken
505
        )
506
        {
507
                await using var strategyContext = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
508
                var strategy = strategyContext.Database.CreateExecutionStrategy();
5✔
509
                return await strategy.ExecuteAsync(
5✔
510
                        operationCancellationToken => AcquireFairCandidateCoreAsync(
5✔
511
                                candidate,
5✔
512
                                workerId,
5✔
513
                                lease,
5✔
514
                                now,
5✔
515
                                nextSequence,
5✔
516
                                operationCancellationToken
5✔
517
                        ),
5✔
518
                        cancellationToken
5✔
519
                ).ConfigureAwait(false);
5✔
520
        }
4✔
521

522
        private async Task<JobRecord?> AcquireFairCandidateCoreAsync(
523
                ImmediateJobEntity candidate,
524
                string workerId,
525
                TimeSpan lease,
526
                DateTimeOffset now,
527
                long nextSequence,
528
                CancellationToken cancellationToken
529
        )
530
        {
531
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
532
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
5✔
533
                var entity = Copy(candidate);
5✔
534
                _ = context.Attach(entity);
5✔
535
                await PrepareAcquisitionExecutionsAsync(context, candidate, workerId, now, cancellationToken).ConfigureAwait(false);
5✔
536
                entity.State = JobState.Active;
5✔
537
                entity.WorkerId = workerId;
5✔
538
                entity.LeaseExpiresAt = now + lease;
5✔
539
                entity.Attempt++;
5✔
540
                entity.CompletedAt = null;
5✔
541
                entity.ExecutionTraceId = null;
5✔
542
                entity.ExecutionSpanId = null;
5✔
543
                entity.ExecutionStartedAt = null;
5✔
544
                entity.ConcurrencyStamp = Guid.NewGuid();
5✔
545

546
                if (candidate.GroupId is { } groupId)
5✔
547
                {
548
                        var group = await context.Set<ImmediateFairQueueGroupEntity>()
5✔
549
                                .SingleOrDefaultAsync(
5✔
550
                                        item => item.QueueName == candidate.QueueName && item.GroupId == groupId,
5✔
551
                                        cancellationToken
5✔
552
                                )
5✔
553
                                .ConfigureAwait(false);
5✔
554
                        if (group is null)
5✔
555
                        {
556
                                _ = context.Add(new ImmediateFairQueueGroupEntity
5✔
557
                                {
5✔
558
                                        QueueName = candidate.QueueName,
5✔
559
                                        GroupId = groupId,
5✔
560
                                        LastServedSequence = nextSequence,
5✔
561
                                        ConcurrencyStamp = Guid.NewGuid(),
5✔
562
                                });
5✔
563
                        }
564
                        else if (group.LastServedSequence >= nextSequence)
4✔
565
                        {
566
                                // Selection observed an older cursor snapshot. Re-rank instead of moving this group backward.
567
                                return null;
4✔
568
                        }
569
                        else
570
                        {
571
                                group.LastServedSequence = nextSequence;
4✔
572
                                group.ConcurrencyStamp = Guid.NewGuid();
4✔
573
                        }
574
                }
575

576
                if (entity.BatchId is { } batchId)
5✔
577
                {
578
                        var batch = await context.Set<ImmediateJobBatchEntity>()
×
579
                                .SingleOrDefaultAsync(item => item.Id == batchId, cancellationToken)
×
580
                                .ConfigureAwait(false);
×
581
                        if (batch is not null && batch.StartedAt is null)
×
582
                        {
583
                                batch.StartedAt = now;
×
584
                                batch.ConcurrencyStamp = Guid.NewGuid();
×
585
                        }
586
                }
587

588
                try
589
                {
590
                        _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
5✔
591
                        await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
5✔
592
                        return ToRecord(entity);
5✔
593
                }
594
                catch (DbUpdateException)
4✔
595
                {
596
                        // The job or its group cursor changed after candidate selection.
597
                        return null;
5✔
598
                }
599
        }
4✔
600

601
        private static JobRecord? GetFirstOrDefault(IReadOnlyList<JobRecord> jobs) =>
602
                jobs.Count == 0 ? null : jobs[0];
4✔
603

604
        private static bool IsNoisy(
605
                string? groupId,
606
                int inflight,
607
                int totalInflight,
608
                FairQueuePolicy policy
609
        )
610
        {
611
                return groupId is not null
5✔
612
                        && totalInflight > 0
5✔
613
                        && inflight >= policy.MinInflightForNoisy
5✔
614
                        && (double)inflight / totalInflight > policy.ConcurrencyShareThreshold;
5✔
615
        }
616

617
        private sealed record FairQueueCandidateState(
5✔
618
                string JobId,
5✔
619
                int Inflight,
5✔
620
                long LastServedSequence
5✔
621
        );
5✔
622

623
        /// <inheritdoc />
624
        public async ValueTask<IReadOnlyList<JobRecord>> AcquireJobsAsync(
625
                IReadOnlyCollection<string> jobIds,
626
                string workerId,
627
                TimeSpan lease,
628
                CancellationToken cancellationToken = default
629
        )
630
        {
631
                ArgumentNullException.ThrowIfNull(jobIds);
5✔
632
                ArgumentException.ThrowIfNullOrWhiteSpace(workerId);
5✔
633
                ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(lease, TimeSpan.Zero);
5✔
634
                if (jobIds.Count == 0)
5✔
635
                        return [];
×
636

637
                var now = _timeProvider.GetUtcNow();
5✔
638
                var ids = jobIds.ToArray();
5✔
639
                await using var readContext = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
640
                var candidates = await readContext.Set<ImmediateJobEntity>()
5✔
641
                        .AsNoTracking()
5✔
642
                        .Where(job => ids.Contains(job.Id) &&
5✔
643
                                (((job.State == JobState.Scheduled || job.State == JobState.Pending) && job.DueAt <= now)
5✔
644
                                || (job.State == JobState.Active && job.LeaseExpiresAt <= now)))
5✔
645
                        .ToListAsync(cancellationToken)
5✔
646
                        .ConfigureAwait(false);
5✔
647

648
                return await AcquireCandidatesAsync(candidates, workerId, lease, now, cancellationToken).ConfigureAwait(false);
5✔
649
        }
4✔
650

651
        private async ValueTask<IReadOnlyList<JobRecord>> AcquireCandidatesAsync(
652
                List<ImmediateJobEntity> candidates,
653
                string workerId,
654
                TimeSpan lease,
655
                DateTimeOffset now,
656
                CancellationToken cancellationToken
657
        )
658
        {
659
                var acquired = new List<JobRecord>(candidates.Count);
5✔
660
                foreach (var candidate in candidates)
5✔
661
                {
662
                        await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
663
                        var entity = Copy(candidate);
5✔
664
                        _ = context.Attach(entity);
5✔
665
                        await PrepareAcquisitionExecutionsAsync(context, candidate, workerId, now, cancellationToken).ConfigureAwait(false);
5✔
666
                        entity.State = JobState.Active;
5✔
667
                        entity.WorkerId = workerId;
5✔
668
                        entity.LeaseExpiresAt = now + lease;
5✔
669
                        entity.Attempt++;
5✔
670
                        entity.CompletedAt = null;
5✔
671
                        entity.ExecutionTraceId = null;
5✔
672
                        entity.ExecutionSpanId = null;
5✔
673
                        entity.ExecutionStartedAt = null;
5✔
674
                        entity.ConcurrencyStamp = Guid.NewGuid();
5✔
675
                        if (entity.BatchId is { } batchId)
5✔
676
                        {
677
                                var batch = await context.Set<ImmediateJobBatchEntity>()
5✔
678
                                        .SingleOrDefaultAsync(item => item.Id == batchId, cancellationToken)
5✔
679
                                        .ConfigureAwait(false);
5✔
680
                                if (batch is not null && batch.StartedAt is null)
5✔
681
                                {
682
                                        batch.StartedAt = now;
5✔
683
                                        batch.ConcurrencyStamp = Guid.NewGuid();
5✔
684
                                }
685
                        }
686

687
                        try
688
                        {
689
                                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
5✔
690
                                acquired.Add(ToRecord(entity));
5✔
691
                        }
5✔
692
                        catch (DbUpdateException)
1✔
693
                        {
694
                                // Suppress only an expected optimistic-claim race; genuine provider failures remain visible.
695
                                if (!await CandidateWasClaimedAsync(candidate, cancellationToken).ConfigureAwait(false))
1✔
NEW
696
                                        throw;
×
697
                        }
698
                }
4✔
699

700
                return acquired;
5✔
701
        }
4✔
702

703
        private async ValueTask<bool> CandidateWasClaimedAsync(
704
                ImmediateJobEntity candidate,
705
                CancellationToken cancellationToken
706
        )
707
        {
708
                try
709
                {
710
                        await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
1✔
711
                        var currentStamp = await context.Set<ImmediateJobEntity>()
1✔
712
                                .AsNoTracking()
1✔
713
                                .Where(job => job.Id == candidate.Id)
1✔
714
                                .Select(static job => (Guid?)job.ConcurrencyStamp)
1✔
715
                                .SingleOrDefaultAsync(cancellationToken)
1✔
716
                                .ConfigureAwait(false);
1✔
717
                        return currentStamp != candidate.ConcurrencyStamp;
1✔
NEW
718
                }
×
NEW
719
                catch (Exception exception) when (exception is DbException or InvalidOperationException)
×
720
                {
NEW
721
                        return false;
×
722
                }
723
        }
1✔
724

725
        /// <inheritdoc />
726
        public ValueTask SetExecutionTelemetryAsync(
727
                string jobId,
728
                int executionNumber,
729
                string workerId,
730
                string? traceId,
731
                string? spanId,
732
                DateTimeOffset startedAt,
733
                CancellationToken cancellationToken = default
734
        ) => MutateOwnedAsync(jobId, executionNumber, workerId, (job, execution) =>
1✔
735
        {
1✔
736
                job.ExecutionTraceId = traceId;
1✔
737
                job.ExecutionSpanId = spanId;
1✔
738
                job.ExecutionStartedAt = startedAt;
1✔
739
                execution.ExecutionTraceId = traceId;
1✔
740
                execution.ExecutionSpanId = spanId;
1✔
741
                execution.ExecutionStartedAt = startedAt;
1✔
742
        }, cancellationToken);
1✔
743

744
        /// <inheritdoc />
745
        public ValueTask RenewLeaseAsync(
746
                string jobId,
747
                int executionNumber,
748
                string workerId,
749
                TimeSpan lease,
750
                CancellationToken cancellationToken = default
751
        )
752
        {
753
                ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(lease, TimeSpan.Zero);
1✔
754
                return MutateOwnedAsync(
1✔
755
                        jobId,
1✔
756
                        executionNumber,
1✔
757
                        workerId,
1✔
NEW
758
                        (job, _) => job.LeaseExpiresAt = _timeProvider.GetUtcNow() + lease,
×
759
                        cancellationToken
1✔
760
                );
1✔
761
        }
762

763
        /// <inheritdoc />
764
        public ValueTask CompleteAsync(
765
                string jobId,
766
                int executionNumber,
767
                string workerId,
768
                CancellationToken cancellationToken = default
769
        ) => CompleteWithContinuationsAsync(jobId, executionNumber, workerId, [], cancellationToken);
5✔
770

771
        /// <inheritdoc />
772
        public ValueTask CompleteWithContinuationsAsync(
773
                string jobId,
774
                int executionNumber,
775
                string workerId,
776
                IReadOnlyList<JobContinuationAddition> additions,
777
                CancellationToken cancellationToken = default
778
        )
779
        {
780
                ArgumentNullException.ThrowIfNull(additions);
5✔
781
                return MutateOwnedWithDependenciesAsync(
5✔
782
                        jobId,
5✔
783
                        executionNumber,
5✔
784
                        workerId,
5✔
785
                        error: null,
5✔
786
                        nextRetryAt: null,
5✔
787
                        succeeded: true,
5✔
788
                        additions,
5✔
789
                        cancellationToken
5✔
790
                );
5✔
791
        }
792

793
        /// <inheritdoc />
794
        public ValueTask AddBatchJobAsync(
795
                string currentJobId,
796
                int executionNumber,
797
                JobRecord job,
798
                ContinuationOptions options,
799
                CancellationToken cancellationToken = default
800
        )
801
        {
802
                ArgumentNullException.ThrowIfNull(job);
5✔
803
                if (options == ContinuationOptions.Detached)
5✔
804
                        throw new ImmediateJobException("AddToBatchAsync cannot create a detached job.");
×
805
                return RetryConcurrencyAsync(
5✔
806
                        operationCancellationToken => AddBatchJobCoreAsync(
5✔
807
                                currentJobId,
5✔
808
                                executionNumber,
5✔
809
                                job,
5✔
810
                                options,
5✔
811
                                operationCancellationToken
5✔
812
                        ),
5✔
813
                        cancellationToken
5✔
814
                );
5✔
815
        }
816

817
        /// <inheritdoc />
818
        public ValueTask FailAsync(
819
                string jobId,
820
                int executionNumber,
821
                string workerId,
822
                string error,
823
                DateTimeOffset? nextRetryAt,
824
                CancellationToken cancellationToken = default
825
        ) => MutateOwnedWithDependenciesAsync(
5✔
826
                jobId,
5✔
827
                executionNumber,
5✔
828
                workerId,
5✔
829
                error,
5✔
830
                nextRetryAt,
5✔
831
                succeeded: false,
5✔
832
                [],
5✔
833
                cancellationToken
5✔
834
        );
5✔
835

836
        /// <inheritdoc />
837
        public async ValueTask UpsertRecurringAsync(RecurringJobSchedule schedule, CancellationToken cancellationToken = default)
838
        {
839
                ArgumentNullException.ThrowIfNull(schedule);
5✔
840
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
841
                if (await UpdateRecurringAsync(context, schedule, cancellationToken).ConfigureAwait(false) != 0)
5✔
842
                        return;
843
                await ThrowIfReplacingCodeDefinedScheduleAsync(context, schedule, cancellationToken).ConfigureAwait(false);
5✔
844

845
                _ = context.Add(ToEntity(schedule));
5✔
846
                try
847
                {
848
                        _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
5✔
849
                }
5✔
850
                catch (DbUpdateException)
851
                {
852
                        // A competing node inserted the same schedule after our update attempt.
853
                        await using var retryContext = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
×
854
                        if (await UpdateRecurringAsync(retryContext, schedule, cancellationToken).ConfigureAwait(false) != 0)
×
855
                                return;
856
                        await ThrowIfReplacingCodeDefinedScheduleAsync(retryContext, schedule, cancellationToken).ConfigureAwait(false);
×
857
                        throw;
×
858
                }
859
        }
4✔
860

861
        /// <inheritdoc />
862
        public async ValueTask RemoveObsoleteCodeDefinedRecurringAsync(
863
                IReadOnlyCollection<string> activeScheduleNames,
864
                CancellationToken cancellationToken = default
865
        )
866
        {
867
                ArgumentNullException.ThrowIfNull(activeScheduleNames);
4✔
868
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
4✔
869
                var schedules = context.Set<ImmediateRecurringJobEntity>()
4✔
870
                        .Where(schedule => schedule.IsCodeDefined);
4✔
871
                if (activeScheduleNames.Count != 0)
4✔
872
                        schedules = schedules.Where(schedule => !activeScheduleNames.Contains(schedule.Name));
4✔
873
                _ = await schedules.ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false);
4✔
874
        }
4✔
875

876
        /// <inheritdoc />
877
        public async ValueTask RemoveRecurringAsync(string name, CancellationToken cancellationToken = default)
878
        {
879
                ArgumentException.ThrowIfNullOrWhiteSpace(name);
5✔
880
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
881
                var removed = await context.Set<ImmediateRecurringJobEntity>()
5✔
882
                        .Where(schedule => schedule.Name == name && !schedule.IsCodeDefined)
5✔
883
                        .ExecuteDeleteAsync(cancellationToken)
5✔
884
                        .ConfigureAwait(false);
5✔
885
                if (removed != 0)
5✔
886
                        return;
887
                if (await context.Set<ImmediateRecurringJobEntity>()
5✔
888
                        .AnyAsync(schedule => schedule.Name == name, cancellationToken)
5✔
889
                        .ConfigureAwait(false))
5✔
890
                {
891
                        throw new ImmediateJobException("Code-defined recurring schedules cannot be deleted.");
4✔
892
                }
893

894
                throw new KeyNotFoundException($"Recurring schedule '{name}' was not found.");
5✔
895
        }
3✔
896

897
        /// <inheritdoc />
898
        public ValueTask PauseRecurringAsync(string name, CancellationToken cancellationToken = default)
899
                => MutateRecurringAsync(name, schedule => schedule.IsPaused = true, cancellationToken);
×
900

901
        /// <inheritdoc />
902
        public ValueTask ResumeRecurringAsync(string name, CancellationToken cancellationToken = default)
903
                => MutateRecurringAsync(name, schedule => schedule.IsPaused = false, cancellationToken);
×
904

905
        /// <inheritdoc />
906
        public async ValueTask<IReadOnlyList<RecurringJobSchedule>> GetDueRecurringAsync(DateTimeOffset now, int batchSize, CancellationToken cancellationToken = default)
907
        {
908
                ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(batchSize, 0);
×
909
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
×
910
                return await context.Set<ImmediateRecurringJobEntity>()
×
911
                        .AsNoTracking()
×
912
                        .Where(schedule => !schedule.IsPaused && schedule.NextRunAt <= now)
×
913
                        .OrderBy(schedule => schedule.NextRunAt)
×
914
                        .Take(batchSize)
×
915
                        .Select(schedule => new RecurringJobSchedule
×
916
                        {
×
917
                                Name = schedule.Name,
×
918
                                JobName = schedule.JobName,
×
919
                                Cron = schedule.Cron,
×
920
                                TimeZone = schedule.TimeZone,
×
921
                                IsCodeDefined = schedule.IsCodeDefined,
×
922
                                IsPaused = schedule.IsPaused,
×
923
                                NextRunAt = schedule.NextRunAt,
×
924
                                LastRunAt = schedule.LastRunAt,
×
925
                        })
×
926
                        .ToListAsync(cancellationToken)
×
927
                        .ConfigureAwait(false);
×
928
        }
929

930
        /// <inheritdoc />
931
        public async ValueTask<bool> MaterializeRecurringAsync(
932
                RecurringJobSchedule schedule,
933
                JobRecord job,
934
                DateTimeOffset nextRunAt,
935
                CancellationToken cancellationToken = default
936
        )
937
        {
938
                ArgumentNullException.ThrowIfNull(schedule);
5✔
939
                ArgumentNullException.ThrowIfNull(job);
5✔
940
                await using var strategyContext = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
941
                var strategy = strategyContext.Database.CreateExecutionStrategy();
5✔
942
                return await strategy.ExecuteAsync(
5✔
943
                        operationCancellationToken => MaterializeRecurringCoreAsync(
5✔
944
                                schedule,
5✔
945
                                job,
5✔
946
                                nextRunAt,
5✔
947
                                operationCancellationToken
5✔
948
                        ),
5✔
949
                        cancellationToken
5✔
950
                ).ConfigureAwait(false);
5✔
951
        }
4✔
952

953
        private async Task<bool> MaterializeRecurringCoreAsync(
954
                RecurringJobSchedule schedule,
955
                JobRecord job,
956
                DateTimeOffset nextRunAt,
957
                CancellationToken cancellationToken
958
        )
959
        {
960
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
961
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
5✔
962
                var entity = await context.Set<ImmediateRecurringJobEntity>()
5✔
963
                        .SingleOrDefaultAsync(item => item.Name == schedule.Name, cancellationToken)
5✔
964
                        .ConfigureAwait(false);
5✔
965
                if (entity is null || entity.IsPaused || entity.NextRunAt != schedule.NextRunAt)
5✔
966
                        return false;
1✔
967

968
                entity.LastRunAt = schedule.NextRunAt;
5✔
969
                entity.NextRunAt = nextRunAt;
5✔
970
                entity.ConcurrencyStamp = Guid.NewGuid();
5✔
971
                _ = context.Add(ToEntity(job));
5✔
972
                try
973
                {
974
                        _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
5✔
975
                        await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
5✔
976
                        return true;
5✔
977
                }
978
                catch (DbUpdateException)
979
                {
980
                        await transaction.RollbackAsync(cancellationToken).ConfigureAwait(false);
×
981
                        return false;
×
982
                }
983
        }
4✔
984

985
        /// <inheritdoc />
986
        public async ValueTask<JobMonitoringSnapshot> GetMonitoringSnapshotAsync(CancellationToken cancellationToken = default)
987
        {
988
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
989
                var rawCounts = await context.Set<ImmediateJobEntity>()
5✔
990
                        .AsNoTracking()
5✔
991
                        .GroupBy(job => job.State)
5✔
992
                        .Select(group => new { State = group.Key, Count = group.LongCount() })
5✔
993
                        .ToListAsync(cancellationToken)
5✔
994
                        .ConfigureAwait(false);
5✔
995
                var counts = Enum.GetValues<JobState>().ToDictionary(static state => state, static _ => 0L);
5✔
996
                foreach (var item in rawCounts)
5✔
997
                        counts[item.State] = item.Count;
5✔
998

999
                var recurring = await context.Set<ImmediateRecurringJobEntity>()
5✔
1000
                        .AsNoTracking()
5✔
1001
                        .OrderBy(schedule => schedule.Name)
5✔
1002
                        .Select(schedule => new RecurringJobSchedule
5✔
1003
                        {
5✔
1004
                                Name = schedule.Name,
5✔
1005
                                JobName = schedule.JobName,
5✔
1006
                                Cron = schedule.Cron,
5✔
1007
                                TimeZone = schedule.TimeZone,
5✔
1008
                                IsCodeDefined = schedule.IsCodeDefined,
5✔
1009
                                IsPaused = schedule.IsPaused,
5✔
1010
                                NextRunAt = schedule.NextRunAt,
5✔
1011
                                LastRunAt = schedule.LastRunAt,
5✔
1012
                        })
5✔
1013
                        .ToListAsync(cancellationToken)
5✔
1014
                        .ConfigureAwait(false);
5✔
1015
                var cutoff = _timeProvider.GetUtcNow() - TimeSpan.FromMinutes(2);
5✔
1016
                var servers = await context.Set<ImmediateJobServerEntity>()
5✔
1017
                        .AsNoTracking()
5✔
1018
                        .Where(server => server.LastHeartbeat >= cutoff)
5✔
1019
                        .OrderBy(server => server.WorkerId)
5✔
1020
                        .Select(server => new JobServerSnapshot(server.WorkerId, server.LastHeartbeat, server.ActiveWorkers, server.MaxWorkers))
5✔
1021
                        .ToListAsync(cancellationToken)
5✔
1022
                        .ConfigureAwait(false);
5✔
1023
                return new(_timeProvider.GetUtcNow(), counts, recurring, servers)
5✔
1024
                {
5✔
1025
                        Capabilities = this.GetCapabilities(),
5✔
1026
                };
5✔
1027
        }
4✔
1028

1029
        /// <inheritdoc />
1030
        public async ValueTask<IReadOnlyList<JobRecord>> QueryJobsAsync(JobQuery query, CancellationToken cancellationToken = default)
1031
        {
1032
                ArgumentNullException.ThrowIfNull(query);
5✔
1033
                ArgumentOutOfRangeException.ThrowIfNegative(query.Skip);
5✔
1034
                ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(query.Take, 0);
5✔
1035
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1036
                var jobs = context.Set<ImmediateJobEntity>().AsNoTracking();
5✔
1037
                if (query.Id is { } id)
5✔
1038
                        jobs = jobs.Where(job => job.Id == id);
5✔
1039
                if (query.State is { } state)
5✔
1040
                        jobs = jobs.Where(job => job.State == state);
4✔
1041
                if (!string.IsNullOrWhiteSpace(query.QueueName))
5✔
1042
                        jobs = jobs.Where(job => job.QueueName == query.QueueName);
×
1043
                if (!string.IsNullOrWhiteSpace(query.JobName))
5✔
1044
                        jobs = jobs.Where(job => job.JobName == query.JobName);
×
1045
                if (!string.IsNullOrWhiteSpace(query.Search))
5✔
1046
                {
1047
                        var search = query.Search.ToUpperInvariant();
×
1048
                        // The parameterless form is intentionally used because relational providers translate it to SQL.
1049
#pragma warning disable CA1304, CA1311, CA1862, MA0011
1050
                        jobs = jobs.Where(job => job.JobName.ToUpper().Contains(search));
×
1051
#pragma warning restore CA1304, CA1311, CA1862, MA0011
1052
                }
1053

1054
                var entities = await jobs.OrderByDescending(job => job.CreatedAt)
5✔
1055
                        .ThenBy(job => job.Id)
5✔
1056
                        .Skip(query.Skip)
5✔
1057
                        .Take(query.Take)
5✔
1058
                        .ToListAsync(cancellationToken)
5✔
1059
                        .ConfigureAwait(false);
5✔
1060
                return [.. entities.Select(ToRecord)];
5✔
1061
        }
4✔
1062

1063
        /// <inheritdoc />
1064
        public async ValueTask<IReadOnlyList<JobExecutionRecord>> QueryJobExecutionsAsync(
1065
                JobExecutionQuery query,
1066
                CancellationToken cancellationToken = default
1067
        )
1068
        {
1069
                ArgumentNullException.ThrowIfNull(query);
1✔
1070
                query.Validate();
1✔
1071
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
1✔
1072
                var job = await context.Set<ImmediateJobEntity>()
1✔
1073
                        .AsNoTracking()
1✔
1074
                        .SingleOrDefaultAsync(item => item.Id == query.JobId, cancellationToken)
1✔
1075
                        .ConfigureAwait(false);
1✔
1076
                if (job is null)
1✔
1077
                        return [];
1✔
1078

1079
                var executions = context.Set<ImmediateJobExecutionEntity>()
1✔
1080
                        .AsNoTracking()
1✔
1081
                        .Where(execution => execution.JobId == query.JobId);
1✔
1082
                if (query.Attempt is { } attempt)
1✔
NEW
1083
                        executions = executions.Where(execution => execution.Attempt == attempt);
×
1084

1085
                var synthetic = JobExecutionRecord.CreateSynthetic(ToRecord(job));
1✔
1086
                var syntheticMissing = synthetic is not null
1✔
1087
                        && (query.Attempt is null || query.Attempt == synthetic.Attempt)
1✔
1088
                        && !await executions.AnyAsync(
1✔
1089
                                execution => execution.Attempt == synthetic.Attempt,
1✔
1090
                                cancellationToken
1✔
1091
                        ).ConfigureAwait(false);
1✔
1092
                var skip = query.Skip;
1✔
1093
                var take = Math.Min(query.Take, JobExecutionQuery.MaximumTake);
1✔
1094
                var result = new List<JobExecutionRecord>(take);
1✔
1095
                if (syntheticMissing && skip == 0 && take != 0)
1✔
1096
                {
NEW
1097
                        result.Add(synthetic!);
×
NEW
1098
                        take--;
×
1099
                }
1100
                else if (syntheticMissing)
1✔
1101
                {
NEW
1102
                        skip--;
×
1103
                }
1104

1105
                if (take != 0 && skip >= 0)
1✔
1106
                {
1107
                        var persisted = await executions
1✔
1108
                                .OrderByDescending(execution => execution.Attempt)
1✔
1109
                                .Skip(skip)
1✔
1110
                                .Take(take)
1✔
1111
                                .ToListAsync(cancellationToken)
1✔
1112
                                .ConfigureAwait(false);
1✔
1113
                        result.AddRange(persisted.Select(ToRecord));
1✔
1114
                }
1115

1116
                return result;
1✔
1117
        }
1✔
1118

1119
        /// <inheritdoc />
1120
        public async ValueTask<BatchStatus?> GetBatchStatusAsync(
1121
                string batchId,
1122
                CancellationToken cancellationToken = default
1123
        )
1124
        {
1125
                ArgumentException.ThrowIfNullOrWhiteSpace(batchId);
5✔
1126
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1127
                var batch = await context.Set<ImmediateJobBatchEntity>()
5✔
1128
                        .AsNoTracking()
5✔
1129
                        .SingleOrDefaultAsync(item => item.Id == batchId, cancellationToken)
5✔
1130
                        .ConfigureAwait(false);
5✔
1131
                return batch is null ? null : ToStatus(batch);
5✔
1132
        }
4✔
1133

1134
        /// <inheritdoc />
1135
        public async ValueTask<IReadOnlyList<JobContinuationEdge>> GetIncomingEdgesAsync(
1136
                IReadOnlyCollection<string> childJobIds,
1137
                CancellationToken cancellationToken = default
1138
        )
1139
        {
1140
                ArgumentNullException.ThrowIfNull(childJobIds);
5✔
1141
                foreach (var childJobId in childJobIds)
5✔
1142
                        ArgumentException.ThrowIfNullOrWhiteSpace(childJobId);
5✔
1143
                if (childJobIds.Count == 0)
5✔
1144
                        return [];
5✔
1145

1146
                var ids = childJobIds.Distinct(StringComparer.Ordinal).ToArray();
5✔
1147
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1148
                var edges = await context.Set<ImmediateJobContinuationEntity>()
5✔
1149
                        .AsNoTracking()
5✔
1150
                        .Where(edge => ids.Contains(edge.ChildJobId))
5✔
1151
                        .OrderBy(edge => edge.ChildJobId)
5✔
1152
                        .ThenBy(edge => edge.ParentKind)
5✔
1153
                        .ThenBy(edge => edge.ParentId)
5✔
1154
                        .ToListAsync(cancellationToken)
5✔
1155
                        .ConfigureAwait(false);
5✔
1156
                return [.. edges.Select(ToContinuationEdge)];
5✔
1157
        }
4✔
1158

1159
        /// <inheritdoc />
1160
        public async ValueTask<IReadOnlyList<BatchStatus>> QueryBatchesAsync(
1161
                JobBatchQuery query,
1162
                CancellationToken cancellationToken = default
1163
        )
1164
        {
1165
                ArgumentNullException.ThrowIfNull(query);
×
1166
                ArgumentOutOfRangeException.ThrowIfNegative(query.Skip);
×
1167
                ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(query.Take, 0);
×
1168
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
×
1169
                var batches = context.Set<ImmediateJobBatchEntity>().AsNoTracking();
×
1170
                if (query.State is { } state)
×
1171
                        batches = batches.Where(batch => batch.State == state);
×
1172
                var entities = await batches.OrderByDescending(batch => batch.CreatedAt)
×
1173
                        .ThenBy(batch => batch.Id)
×
1174
                        .Skip(query.Skip)
×
1175
                        .Take(query.Take)
×
1176
                        .ToListAsync(cancellationToken)
×
1177
                        .ConfigureAwait(false);
×
1178
                return [.. entities.Select(ToStatus)];
×
1179
        }
1180

1181
        /// <inheritdoc />
1182
        public async ValueTask<IReadOnlyList<BatchMemberStatus>> QueryBatchMembersAsync(
1183
                string batchId,
1184
                BatchMemberQuery query,
1185
                CancellationToken cancellationToken = default
1186
        )
1187
        {
1188
                ArgumentException.ThrowIfNullOrWhiteSpace(batchId);
4✔
1189
                ArgumentNullException.ThrowIfNull(query);
4✔
1190
                ArgumentOutOfRangeException.ThrowIfNegative(query.Skip);
4✔
1191
                ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(query.Take, 0);
4✔
1192
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
4✔
1193
                var jobs = context.Set<ImmediateJobEntity>()
4✔
1194
                        .AsNoTracking()
4✔
1195
                        .Where(job => job.BatchId == batchId);
4✔
1196
                if (query.State is { } state)
4✔
1197
                        jobs = jobs.Where(job => job.State == state);
×
1198
                return await jobs.OrderBy(job => job.CreatedAt)
4✔
1199
                        .ThenBy(job => job.Id)
4✔
1200
                        .Skip(query.Skip)
4✔
1201
                        .Take(query.Take)
4✔
1202
                        .Select(job => new BatchMemberStatus(
4✔
1203
                                job.Id,
4✔
1204
                                job.JobName,
4✔
1205
                                job.QueueName,
4✔
1206
                                job.State,
4✔
1207
                                job.Attempt,
4✔
1208
                                job.CreatedAt,
4✔
1209
                                job.CompletedAt,
4✔
1210
                                job.LastError
4✔
1211
                        ))
4✔
1212
                        .ToListAsync(cancellationToken)
4✔
1213
                        .ConfigureAwait(false);
4✔
1214
        }
3✔
1215

1216
        /// <inheritdoc />
1217
        public async ValueTask<BatchGraph?> GetBatchGraphAsync(
1218
                string batchId,
1219
                CancellationToken cancellationToken = default
1220
        )
1221
        {
1222
                ArgumentException.ThrowIfNullOrWhiteSpace(batchId);
4✔
1223
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
4✔
1224
                if (!await context.Set<ImmediateJobBatchEntity>()
4✔
1225
                        .AnyAsync(batch => batch.Id == batchId, cancellationToken)
4✔
1226
                        .ConfigureAwait(false))
4✔
1227
                {
1228
                        return null;
4✔
1229
                }
1230

1231
                var jobs = await context.Set<ImmediateJobEntity>()
×
1232
                        .AsNoTracking()
×
1233
                        .Where(job => job.BatchId == batchId)
×
1234
                        .OrderBy(job => job.CreatedAt)
×
1235
                        .ThenBy(job => job.Id)
×
1236
                        .Select(job => new BatchGraphNode(job.Id, job.JobName, job.State))
×
1237
                        .ToListAsync(cancellationToken)
×
1238
                        .ConfigureAwait(false);
×
1239
                var ids = jobs.Select(static job => job.JobId).ToArray();
×
1240
                var edges = ids.Length == 0
×
1241
                        ? []
×
1242
                        : await context.Set<ImmediateJobContinuationEntity>()
×
1243
                                .AsNoTracking()
×
1244
                                .Where(edge => ids.Contains(edge.ChildJobId))
×
1245
                                .OrderBy(edge => edge.ChildJobId)
×
1246
                                .ThenBy(edge => edge.ParentKind)
×
1247
                                .ThenBy(edge => edge.ParentId)
×
1248
                                .ToListAsync(cancellationToken)
×
1249
                                .ConfigureAwait(false);
×
1250
                return new(batchId, jobs, [.. edges.Select(ToGraphEdge)]);
4✔
1251
        }
3✔
1252

1253
        /// <inheritdoc />
1254
        public async ValueTask<JobStatus?> GetJobStatusAsync(
1255
                string jobId,
1256
                CancellationToken cancellationToken = default
1257
        )
1258
        {
1259
                ArgumentException.ThrowIfNullOrWhiteSpace(jobId);
5✔
1260
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1261
                var job = await context.Set<ImmediateJobEntity>()
5✔
1262
                        .AsNoTracking()
5✔
1263
                        .SingleOrDefaultAsync(item => item.Id == jobId, cancellationToken)
5✔
1264
                        .ConfigureAwait(false);
5✔
1265
                if (job is null)
5✔
1266
                        return null;
5✔
1267
                var edges = await context.Set<ImmediateJobContinuationEntity>()
5✔
1268
                        .AsNoTracking()
5✔
1269
                        .Where(edge => edge.ChildJobId == jobId)
5✔
1270
                        .OrderBy(edge => edge.ParentKind)
5✔
1271
                        .ThenBy(edge => edge.ParentId)
5✔
1272
                        .ToListAsync(cancellationToken)
5✔
1273
                        .ConfigureAwait(false);
5✔
1274
                return new(
5✔
1275
                        job.Id,
5✔
1276
                        job.JobName,
5✔
1277
                        job.QueueName,
5✔
1278
                        job.State,
5✔
1279
                        job.Attempt,
5✔
1280
                        MaxAttempts: null,
5✔
1281
                        job.CreatedAt,
5✔
1282
                        job.DueAt,
5✔
1283
                        job.CompletedAt,
5✔
1284
                        job.LastError,
5✔
1285
                        job.BatchId,
5✔
1286
                        [.. edges.Select(ToGraphEdge)]
5✔
1287
                );
5✔
1288
        }
4✔
1289

1290
        /// <inheritdoc />
1291
        public ValueTask CancelBatchAsync(string batchId, CancellationToken cancellationToken = default)
1292
        {
1293
                ArgumentException.ThrowIfNullOrWhiteSpace(batchId);
5✔
1294
                return RetryConcurrencyAsync(
5✔
1295
                        operationCancellationToken => CancelBatchCoreAsync(batchId, operationCancellationToken),
5✔
1296
                        cancellationToken
5✔
1297
                );
5✔
1298
        }
1299

1300
        private async Task CancelBatchCoreAsync(string batchId, CancellationToken cancellationToken)
1301
        {
1302
                var now = _timeProvider.GetUtcNow();
5✔
1303
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1304
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
5✔
1305
                var batch = await context.Set<ImmediateJobBatchEntity>()
5✔
1306
                        .SingleOrDefaultAsync(item => item.Id == batchId, cancellationToken)
5✔
1307
                        .ConfigureAwait(false)
5✔
1308
                        ?? throw new KeyNotFoundException($"Batch '{batchId}' was not found.");
5✔
1309
                if (batch.State != BatchState.Executing)
5✔
1310
                        throw new ImmediateJobException("Only an executing batch can be cancelled.");
×
1311

1312
                var jobs = await context.Set<ImmediateJobEntity>()
5✔
1313
                        .Where(job => job.BatchId == batchId)
5✔
1314
                        .ToListAsync(cancellationToken)
5✔
1315
                        .ConfigureAwait(false);
5✔
1316
                var jobsToCancel = jobs.Where(job => !IsTerminal(job.State)).ToArray();
5✔
1317
                foreach (var job in jobsToCancel)
5✔
1318
                {
1319
                        if (job.State == JobState.Active)
5✔
1320
                        {
NEW
1321
                                var execution = await GetOrMaterializeExecutionAsync(context, job, cancellationToken).ConfigureAwait(false)
×
NEW
1322
                                        ?? throw new ImmediateJobException($"Active job '{job.Id}' has no execution ordinal.");
×
NEW
1323
                                execution.State = JobExecutionState.Cancelled;
×
NEW
1324
                                execution.CompletedAt = now;
×
NEW
1325
                                execution.Error = null;
×
1326
                        }
1327

1328
                        job.State = JobState.Cancelled;
5✔
1329
                        job.CompletedAt = now;
5✔
1330
                        job.WorkerId = null;
5✔
1331
                        job.LeaseExpiresAt = null;
5✔
1332
                        job.ConcurrencyStamp = Guid.NewGuid();
5✔
1333
                }
4✔
1334

1335
                foreach (var job in jobsToCancel)
5✔
1336
                        await PropagateTerminalAsync(context, job, now, cancellationToken).ConfigureAwait(false);
5✔
1337

1338
                var terminalGroups = GetTerminalFairQueueGroups(context);
5✔
1339
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
5✔
1340
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
5✔
1341
                foreach (var (queueName, groupId) in terminalGroups)
5✔
1342
                {
1343
                        await TryRemoveFairQueueCursorAsync(queueName, groupId, CancellationToken.None).ConfigureAwait(false);
×
1344
                }
1345
        }
5✔
1346

1347
        /// <inheritdoc />
1348
        public ValueTask DeleteBatchAsync(string batchId, CancellationToken cancellationToken = default)
1349
        {
1350
                ArgumentException.ThrowIfNullOrWhiteSpace(batchId);
5✔
1351
                return ExecuteWithStrategyAsync(
5✔
1352
                        operationCancellationToken => DeleteBatchCoreAsync(batchId, operationCancellationToken),
5✔
1353
                        cancellationToken
5✔
1354
                );
5✔
1355
        }
1356

1357
        private async Task DeleteBatchCoreAsync(string batchId, CancellationToken cancellationToken)
1358
        {
1359
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1360
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
5✔
1361
                var batch = await context.Set<ImmediateJobBatchEntity>()
5✔
1362
                        .SingleOrDefaultAsync(item => item.Id == batchId, cancellationToken)
5✔
1363
                        .ConfigureAwait(false)
5✔
1364
                        ?? throw new KeyNotFoundException($"Batch '{batchId}' was not found.");
5✔
1365
                if (batch.State == BatchState.Executing)
5✔
1366
                        throw new ImmediateJobException("Only a terminal batch can be deleted.");
×
1367

1368
                var jobs = await context.Set<ImmediateJobEntity>()
5✔
1369
                        .Where(job => job.BatchId == batchId)
5✔
1370
                        .ToListAsync(cancellationToken)
5✔
1371
                        .ConfigureAwait(false);
5✔
1372
                var jobIds = jobs.Select(static job => job.Id).ToArray();
5✔
1373
                var edges = await context.Set<ImmediateJobContinuationEntity>()
5✔
1374
                        .Where(edge =>
5✔
1375
                                jobIds.Contains(edge.ChildJobId)
5✔
1376
                                || (edge.ParentKind == ContinuationParentKind.Job && jobIds.Contains(edge.ParentId))
5✔
1377
                                || (edge.ParentKind == ContinuationParentKind.Batch && edge.ParentId == batchId))
5✔
1378
                        .ToListAsync(cancellationToken)
5✔
1379
                        .ConfigureAwait(false);
5✔
1380
                context.RemoveRange(edges);
5✔
1381
                context.RemoveRange(jobs);
5✔
1382
                _ = context.Remove(batch);
5✔
1383
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
5✔
1384
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
5✔
1385
        }
5✔
1386

1387
        /// <inheritdoc />
1388
        public ValueTask RetryAsync(string jobId, CancellationToken cancellationToken = default)
1389
        {
1390
                ArgumentException.ThrowIfNullOrWhiteSpace(jobId);
5✔
1391
                return RetryConcurrencyAsync(
5✔
1392
                        operationCancellationToken => RetryCoreAsync(jobId, operationCancellationToken),
5✔
1393
                        cancellationToken
5✔
1394
                );
5✔
1395
        }
1396

1397
        private async Task RetryCoreAsync(string jobId, CancellationToken cancellationToken)
1398
        {
1399
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1400
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
5✔
1401
                var job = await context.Set<ImmediateJobEntity>()
5✔
1402
                        .SingleOrDefaultAsync(item => item.Id == jobId &&
5✔
1403
                                (item.State == JobState.Failed || item.State == JobState.Scheduled), cancellationToken)
5✔
1404
                        .ConfigureAwait(false);
5✔
1405
                if (job is null)
5✔
1406
                {
1407
                        if (await context.Set<ImmediateJobEntity>()
5✔
1408
                                .AnyAsync(item => item.Id == jobId, cancellationToken)
5✔
1409
                                .ConfigureAwait(false))
5✔
1410
                        {
1411
                                throw new ImmediateJobException("Only failed or scheduled jobs can be retried.");
5✔
1412
                        }
1413

1414
                        throw new KeyNotFoundException($"Job '{jobId}' was not found.");
5✔
1415
                }
1416

1417
                var wasFailed = job.State == JobState.Failed;
1✔
1418
                _ = await GetOrMaterializeExecutionAsync(context, job, cancellationToken).ConfigureAwait(false);
1✔
1419
                if (wasFailed && job.BatchId is { } batchId)
1✔
1420
                {
1421
                        var batch = await context.Set<ImmediateJobBatchEntity>()
×
1422
                                .SingleAsync(item => item.Id == batchId, cancellationToken)
×
1423
                                .ConfigureAwait(false);
×
1424
                        batch.PendingCount++;
×
1425
                        batch.FailedCount = Math.Max(0, batch.FailedCount - 1);
×
1426
                        batch.State = BatchState.Executing;
×
1427
                        batch.CompletedAt = null;
×
1428
                        batch.ConcurrencyStamp = Guid.NewGuid();
×
1429
                }
1430

1431
                job.State = JobState.Pending;
1✔
1432
                job.DueAt = _timeProvider.GetUtcNow();
1✔
1433
                job.WorkerId = null;
1✔
1434
                job.LeaseExpiresAt = null;
1✔
1435
                if (wasFailed)
1✔
1436
                {
1437
                        job.CompletedAt = null;
1✔
1438
                        job.LastError = null;
1✔
1439
                }
1440

1441
                job.ConcurrencyStamp = Guid.NewGuid();
1✔
1442
                try
1443
                {
1444
                        _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
1✔
1445
                }
1✔
1446
                catch (DbUpdateConcurrencyException)
1447
                {
1448
                        if (!await context.Set<ImmediateJobEntity>()
×
1449
                                .AsNoTracking()
×
1450
                                .AnyAsync(item => item.Id == jobId, cancellationToken)
×
1451
                                .ConfigureAwait(false))
×
1452
                        {
1453
                                throw new KeyNotFoundException($"Job '{jobId}' was not found.");
×
1454
                        }
1455

1456
                        throw new ImmediateJobException("Only failed or scheduled jobs can be retried.");
×
1457
                }
1458

1459
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
1✔
1460
        }
1✔
1461

1462
        /// <inheritdoc />
1463
        public ValueTask DeleteAsync(string jobId, CancellationToken cancellationToken = default)
1464
        {
1465
                ArgumentException.ThrowIfNullOrWhiteSpace(jobId);
5✔
1466
                return ExecuteWithStrategyAsync(
5✔
1467
                        operationCancellationToken => DeleteCoreAsync(jobId, operationCancellationToken),
5✔
1468
                        cancellationToken
5✔
1469
                );
5✔
1470
        }
1471

1472
        private async Task DeleteCoreAsync(string jobId, CancellationToken cancellationToken)
1473
        {
1474
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1475
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
5✔
1476
                var job = await context.Set<ImmediateJobEntity>()
5✔
1477
                        .AsNoTracking()
5✔
1478
                        .SingleOrDefaultAsync(item => item.Id == jobId
5✔
1479
                                && (item.State == JobState.Succeeded || item.State == JobState.Failed || item.State == JobState.Cancelled || item.State == JobState.Skipped), cancellationToken)
5✔
1480
                        .ConfigureAwait(false);
5✔
1481
                if (job is null)
5✔
1482
                {
1483
                        if (await context.Set<ImmediateJobEntity>()
5✔
1484
                                .AnyAsync(item => item.Id == jobId, cancellationToken)
5✔
1485
                                .ConfigureAwait(false))
5✔
1486
                        {
1487
                                throw new ImmediateJobException("Only terminal jobs can be deleted.");
4✔
1488
                        }
1489

1490
                        throw new KeyNotFoundException($"Job '{jobId}' was not found.");
5✔
1491
                }
1492

1493
                if (job.BatchId is not null)
1✔
1494
                        throw new ImmediateJobException("Batch members are deleted with their batch so the workflow remains coherent.");
×
1495
                _ = await context.Set<ImmediateJobContinuationEntity>()
1✔
1496
                        .Where(edge => edge.ChildJobId == jobId ||
1✔
1497
                                (edge.ParentKind == ContinuationParentKind.Job && edge.ParentId == jobId))
1✔
1498
                        .ExecuteDeleteAsync(cancellationToken)
1✔
1499
                        .ConfigureAwait(false);
1✔
1500
                var removed = await context.Set<ImmediateJobEntity>()
1✔
1501
                        .Where(item => item.Id == jobId &&
1✔
1502
                                (item.State == JobState.Succeeded || item.State == JobState.Failed || item.State == JobState.Cancelled || item.State == JobState.Skipped))
1✔
1503
                        .ExecuteDeleteAsync(cancellationToken)
1✔
1504
                        .ConfigureAwait(false);
1✔
1505
                if (removed == 0)
1✔
1506
                {
1507
                        if (await context.Set<ImmediateJobEntity>()
×
1508
                                .AnyAsync(item => item.Id == jobId, cancellationToken)
×
1509
                                .ConfigureAwait(false))
×
1510
                        {
1511
                                throw new ImmediateJobException("Only terminal jobs can be deleted.");
×
1512
                        }
1513

1514
                        throw new KeyNotFoundException($"Job '{jobId}' was not found.");
×
1515
                }
1516

1517
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
1✔
1518
        }
1✔
1519

1520
        /// <inheritdoc />
1521
        public ValueTask PurgeJobsAsync(
1522
                TimeSpan succeededRetention,
1523
                TimeSpan failedRetention,
1524
                CancellationToken cancellationToken = default
1525
        )
1526
        {
1527
                var now = _timeProvider.GetUtcNow();
4✔
1528
                return ExecuteWithStrategyAsync(
4✔
1529
                        operationCancellationToken => PurgeJobsCoreAsync(
4✔
1530
                                now - succeededRetention,
4✔
1531
                                now - failedRetention,
4✔
1532
                                operationCancellationToken
4✔
1533
                        ),
4✔
1534
                        cancellationToken
4✔
1535
                );
4✔
1536
        }
1537

1538
        /// <inheritdoc />
1539
        public ValueTask PurgeBatchesAsync(
1540
                TimeSpan batchSucceededRetention,
1541
                TimeSpan batchFailedRetention,
1542
                CancellationToken cancellationToken = default
1543
        )
1544
        {
1545
                var now = _timeProvider.GetUtcNow();
4✔
1546
                return ExecuteWithStrategyAsync(
4✔
1547
                        operationCancellationToken => PurgeBatchesCoreAsync(
4✔
1548
                                now - batchSucceededRetention,
4✔
1549
                                now - batchFailedRetention,
4✔
1550
                                operationCancellationToken
4✔
1551
                        ),
4✔
1552
                        cancellationToken
4✔
1553
                );
4✔
1554
        }
1555

1556
        private async Task PurgeJobsCoreAsync(
1557
                DateTimeOffset succeededBefore,
1558
                DateTimeOffset failedBefore,
1559
                CancellationToken cancellationToken
1560
        )
1561
        {
1562
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
4✔
1563
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
4✔
1564
                var jobs = await context.Set<ImmediateJobEntity>()
4✔
1565
                        .Where(job => job.BatchId == null
4✔
1566
                                && ((job.State == JobState.Succeeded && job.CompletedAt < succeededBefore)
4✔
1567
                                || ((job.State == JobState.Failed || job.State == JobState.Cancelled || job.State == JobState.Skipped) && job.CompletedAt < failedBefore))
4✔
1568
                        )
4✔
1569
                        .ToListAsync(cancellationToken)
4✔
1570
                        .ConfigureAwait(false);
4✔
1571
                if (jobs.Count != 0)
4✔
1572
                {
1573
                        var jobIds = jobs.Select(static job => job.Id).ToArray();
×
1574
                        var edges = await context.Set<ImmediateJobContinuationEntity>()
×
1575
                                .Where(edge =>
×
1576
                                        jobIds.Contains(edge.ChildJobId)
×
1577
                                        || (jobIds.Contains(edge.ParentId) && edge.ParentKind == ContinuationParentKind.Job)
×
1578
                                )
×
1579
                                .ToListAsync(cancellationToken)
×
1580
                                .ConfigureAwait(false);
×
1581
                        context.RemoveRange(edges);
×
1582
                }
1583

1584
                context.RemoveRange(jobs);
4✔
1585
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
4✔
1586
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
4✔
1587
        }
4✔
1588

1589
        private async Task PurgeBatchesCoreAsync(
1590
                DateTimeOffset batchSucceededBefore,
1591
                DateTimeOffset batchFailedBefore,
1592
                CancellationToken cancellationToken
1593
        )
1594
        {
1595
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
4✔
1596
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
4✔
1597
                var batches = await context.Set<ImmediateJobBatchEntity>()
4✔
1598
                        .Where(batch => (batch.State == BatchState.Succeeded && batch.CompletedAt < batchSucceededBefore)
4✔
1599
                                || ((batch.State == BatchState.Failed || batch.State == BatchState.Cancelled)
4✔
1600
                                        && batch.CompletedAt < batchFailedBefore))
4✔
1601
                        .ToListAsync(cancellationToken)
4✔
1602
                        .ConfigureAwait(false);
4✔
1603
                if (batches.Count != 0)
4✔
1604
                {
1605
                        var batchIds = batches.Select(static batch => batch.Id).ToArray();
×
1606
                        var memberIds = await context.Set<ImmediateJobEntity>()
×
1607
                                .Where(job => job.BatchId != null && batchIds.Contains(job.BatchId))
×
1608
                                .Select(job => job.Id)
×
1609
                                .ToListAsync(cancellationToken)
×
1610
                                .ConfigureAwait(false);
×
1611
                        var edges = await context.Set<ImmediateJobContinuationEntity>()
×
1612
                                .Where(edge =>
×
1613
                                        (batchIds.Contains(edge.ParentId) && edge.ParentKind == ContinuationParentKind.Batch)
×
1614
                                        || memberIds.Contains(edge.ChildJobId)
×
1615
                                        || (memberIds.Contains(edge.ParentId) && edge.ParentKind == ContinuationParentKind.Job)
×
1616
                                )
×
1617
                                .ToListAsync(cancellationToken)
×
1618
                                .ConfigureAwait(false);
×
1619
                        context.RemoveRange(edges);
×
1620
                        context.RemoveRange(batches);
×
1621
                }
1622

1623
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
4✔
1624
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
4✔
1625
        }
4✔
1626

1627
        /// <inheritdoc />
1628
        public async ValueTask HeartbeatAsync(JobServerSnapshot server, CancellationToken cancellationToken = default)
1629
        {
1630
                ArgumentNullException.ThrowIfNull(server);
1✔
1631
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
1✔
1632
                var cutoff = _timeProvider.GetUtcNow() - TimeSpan.FromMinutes(2);
1✔
1633
                _ = await context.Set<ImmediateJobServerEntity>()
1✔
1634
                        .Where(item => item.LastHeartbeat < cutoff)
1✔
1635
                        .ExecuteDeleteAsync(cancellationToken)
1✔
1636
                        .ConfigureAwait(false);
1✔
1637
                var entity = await context.Set<ImmediateJobServerEntity>().FindAsync([server.WorkerId], cancellationToken).ConfigureAwait(false);
1✔
1638
                if (entity is null)
1✔
1639
                {
1640
                        _ = context.Add(new ImmediateJobServerEntity
1✔
1641
                        {
1✔
1642
                                WorkerId = server.WorkerId,
1✔
1643
                                LastHeartbeat = server.LastHeartbeat,
1✔
1644
                                ActiveWorkers = server.ActiveWorkers,
1✔
1645
                                MaxWorkers = server.MaxWorkers,
1✔
1646
                        });
1✔
1647
                }
1648
                else
1649
                {
1650
                        entity.LastHeartbeat = server.LastHeartbeat;
×
1651
                        entity.ActiveWorkers = server.ActiveWorkers;
×
1652
                        entity.MaxWorkers = server.MaxWorkers;
×
1653
                }
1654

1655
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
1✔
1656
        }
1✔
1657

1658
        /// <inheritdoc />
1659
        public async ValueTask<bool> IsHealthyAsync(CancellationToken cancellationToken = default)
1660
        {
1661
                try
1662
                {
1663
                        await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
×
1664
                        return await context.Database.CanConnectAsync(cancellationToken).ConfigureAwait(false);
×
1665
                }
×
1666
                catch (Exception exception) when (exception is DbException or InvalidOperationException)
×
1667
                {
1668
                        return false;
×
1669
                }
1670
        }
×
1671

1672
        private ValueTask MutateOwnedWithDependenciesAsync(
1673
                string jobId,
1674
                int executionNumber,
1675
                string workerId,
1676
                string? error,
1677
                DateTimeOffset? nextRetryAt,
1678
                bool succeeded,
1679
                IReadOnlyList<JobContinuationAddition> additions,
1680
                CancellationToken cancellationToken
1681
        ) => RetryConcurrencyAsync(
5✔
1682
                operationCancellationToken => MutateOwnedCoreAsync(
5✔
1683
                        jobId,
5✔
1684
                        executionNumber,
5✔
1685
                        workerId,
5✔
1686
                        error,
5✔
1687
                        nextRetryAt,
5✔
1688
                        succeeded,
5✔
1689
                        additions,
5✔
1690
                        operationCancellationToken
5✔
1691
                ),
5✔
1692
                cancellationToken
5✔
1693
        );
5✔
1694

1695
        private async ValueTask RetryConcurrencyAsync(
1696
                Func<CancellationToken, Task> operation,
1697
                CancellationToken cancellationToken
1698
        )
1699
        {
1700
                var concurrencyAttempt = 0;
5✔
1701
                while (true)
1✔
1702
                {
1703
                        try
1704
                        {
1705
                                await ExecuteWithStrategyAsync(operation, cancellationToken).ConfigureAwait(false);
5✔
1706
                                return;
5✔
1707
                        }
1708
                        catch (DbUpdateConcurrencyException) when (++concurrencyAttempt < MaxConcurrencyAttempts)
5✔
1709
                        {
1710
                                // The transaction rolled back, so the next attempt re-evaluates the graph from durable state.
1711
                        }
1✔
1712
                        catch (DbUpdateException exception) when (++concurrencyAttempt < MaxConcurrencyAttempts)
5✔
1713
                        {
1714
                                if (!await IsSyntheticExecutionInsertRaceAsync(exception, cancellationToken).ConfigureAwait(false))
1✔
NEW
1715
                                        throw;
×
1716
                                // The failed context is disposed by the operation; retry with the execution inserted by the winner.
1717
                        }
1718
                }
1719
        }
5✔
1720

1721
        private async ValueTask ExecuteWithStrategyAsync(
1722
                Func<CancellationToken, Task> operation,
1723
                CancellationToken cancellationToken
1724
        )
1725
        {
1726
                await using var strategyContext = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1727
                var strategy = strategyContext.Database.CreateExecutionStrategy();
5✔
1728
                await strategy.ExecuteAsync(operation, cancellationToken).ConfigureAwait(false);
5✔
1729
        }
5✔
1730

1731
        private async ValueTask<bool> IsSyntheticExecutionInsertRaceAsync(
1732
                DbUpdateException exception,
1733
                CancellationToken cancellationToken
1734
        )
1735
        {
1736
                var syntheticExecutions = exception.Entries
1✔
1737
                        .Select(static entry => entry.Entity)
1✔
1738
                        .OfType<ImmediateJobExecutionEntity>()
1✔
1739
                        .Where(static execution => execution.IsSynthetic)
1✔
1740
                        .DistinctBy(static execution => (execution.JobId, execution.Attempt))
1✔
1741
                        .ToArray();
1✔
1742
                if (syntheticExecutions.Length == 0)
1✔
NEW
1743
                        return false;
×
1744

1745
                try
1746
                {
1747
                        await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
1✔
1748
                        foreach (var execution in syntheticExecutions)
1✔
1749
                        {
1750
                                if (!await context.Set<ImmediateJobExecutionEntity>()
1✔
1751
                                        .AsNoTracking()
1✔
1752
                                        .AnyAsync(
1✔
1753
                                                item => item.JobId == execution.JobId && item.Attempt == execution.Attempt,
1✔
1754
                                                cancellationToken
1✔
1755
                                        )
1✔
1756
                                        .ConfigureAwait(false))
1✔
1757
                                {
NEW
1758
                                        return false;
×
1759
                                }
1760
                        }
1761

1762
                        return true;
1✔
NEW
1763
                }
×
NEW
1764
                catch (Exception verificationException) when (
×
NEW
1765
                        verificationException is DbException or InvalidOperationException
×
NEW
1766
                )
×
1767
                {
NEW
1768
                        return false;
×
1769
                }
1770
        }
1✔
1771

1772
        private ValueTask MutateOwnedAsync(
1773
                string jobId,
1774
                int executionNumber,
1775
                string workerId,
1776
                Action<ImmediateJobEntity, ImmediateJobExecutionEntity> mutate,
1777
                CancellationToken cancellationToken
1778
        ) => RetryConcurrencyAsync(
1✔
1779
                operationCancellationToken => MutateOwnedOnceAsync(
1✔
1780
                        jobId,
1✔
1781
                        executionNumber,
1✔
1782
                        workerId,
1✔
1783
                        mutate,
1✔
1784
                        operationCancellationToken
1✔
1785
                ),
1✔
1786
                cancellationToken
1✔
1787
        );
1✔
1788

1789
        private async Task MutateOwnedOnceAsync(
1790
                string jobId,
1791
                int executionNumber,
1792
                string workerId,
1793
                Action<ImmediateJobEntity, ImmediateJobExecutionEntity> mutate,
1794
                CancellationToken cancellationToken
1795
        )
1796
        {
1797
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
1✔
1798
                var job = await context.Set<ImmediateJobEntity>()
1✔
1799
                        .SingleOrDefaultAsync(item => item.Id == jobId && item.Attempt == executionNumber && item.State == JobState.Active && item.WorkerId == workerId, cancellationToken)
1✔
1800
                        .ConfigureAwait(false) ?? throw new ImmediateJobException($"Worker '{workerId}' does not own active job '{jobId}'.");
1✔
1801
                var execution = await GetOrMaterializeExecutionAsync(context, job, cancellationToken).ConfigureAwait(false)
1✔
1802
                        ?? throw new ImmediateJobException($"Active job '{job.Id}' has no execution ordinal.");
1✔
1803
                mutate(job, execution);
1✔
1804
                job.ConcurrencyStamp = Guid.NewGuid();
1✔
1805
                try
1806
                {
1807
                        _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
1✔
1808
                }
1✔
NEW
1809
                catch (DbUpdateConcurrencyException exception)
×
1810
                {
1811
                        throw new ImmediateJobException(
1✔
1812
                                $"Worker '{workerId}' does not own active job '{jobId}'.",
1✔
1813
                                exception
1✔
1814
                        );
1✔
1815
                }
1816
        }
1✔
1817

1818
        private async Task MutateOwnedCoreAsync(
1819
                string jobId,
1820
                int executionNumber,
1821
                string workerId,
1822
                string? error,
1823
                DateTimeOffset? nextRetryAt,
1824
                bool succeeded,
1825
                IReadOnlyList<JobContinuationAddition> additions,
1826
                CancellationToken cancellationToken
1827
        )
1828
        {
1829
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1830
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
5✔
1831
                var job = await context.Set<ImmediateJobEntity>()
5✔
1832
                        .SingleOrDefaultAsync(item => item.Id == jobId && item.Attempt == executionNumber && item.State == JobState.Active && item.WorkerId == workerId, cancellationToken)
5✔
1833
                        .ConfigureAwait(false) ?? throw new ImmediateJobException($"Worker '{workerId}' does not own active job '{jobId}'.");
5✔
1834
                var now = _timeProvider.GetUtcNow();
5✔
1835
                var execution = await GetOrMaterializeExecutionAsync(context, job, cancellationToken).ConfigureAwait(false)
5✔
1836
                        ?? throw new ImmediateJobException($"Active job '{job.Id}' has no execution ordinal.");
5✔
1837
                execution.State = succeeded ? JobExecutionState.Succeeded : JobExecutionState.Failed;
5✔
1838
                execution.CompletedAt = now;
5✔
1839
                execution.Error = error;
5✔
1840
                job.WorkerId = null;
5✔
1841
                job.LeaseExpiresAt = null;
5✔
1842
                job.LastError = error;
5✔
1843
                job.ConcurrencyStamp = Guid.NewGuid();
5✔
1844
                if (!succeeded && nextRetryAt is { } retryAt)
5✔
1845
                {
1846
                        job.State = retryAt <= now ? JobState.Pending : JobState.Scheduled;
×
1847
                        job.DueAt = retryAt;
×
1848
                        job.CompletedAt = null;
×
1849
                        _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
×
1850
                        await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
×
1851
                        return;
×
1852
                }
1853

1854
                if (succeeded && additions.Count != 0)
5✔
1855
                {
1856
                        await FlushContinuationAdditionsAsync(context, job, additions, cancellationToken).ConfigureAwait(false);
5✔
1857
                        _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
×
1858
                }
1859

1860
                job.State = succeeded ? JobState.Succeeded : JobState.Failed;
5✔
1861
                job.CompletedAt = now;
5✔
1862
                await PropagateTerminalAsync(context, job, now, cancellationToken).ConfigureAwait(false);
5✔
1863
                var terminalGroups = GetTerminalFairQueueGroups(context);
5✔
1864
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
5✔
1865
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
5✔
1866
                foreach (var (queueName, groupId) in terminalGroups)
5✔
1867
                        await TryRemoveFairQueueCursorAsync(queueName, groupId, CancellationToken.None).ConfigureAwait(false);
5✔
1868
        }
5✔
1869

1870
        private static (string QueueName, string GroupId)[] GetTerminalFairQueueGroups(TContext context) =>
1871
                [
5✔
1872
                        .. context.ChangeTracker
5✔
1873
                                .Entries<ImmediateJobEntity>()
5✔
1874
                                .Select(static entry => entry.Entity)
5✔
1875
                                .Where(static job => job.GroupId is not null && IsTerminal(job.State))
5✔
1876
                                .Select(static job => (job.QueueName, GroupId: job.GroupId!))
5✔
1877
                                .Distinct(),
5✔
1878
                ];
5✔
1879

1880
        private async ValueTask TryRemoveFairQueueCursorAsync(
1881
                string queueName,
1882
                string groupId,
1883
                CancellationToken cancellationToken
1884
        )
1885
        {
1886
                try
1887
                {
1888
                        await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1889
                        if (await HasLiveGroupJobsAsync(context, queueName, groupId, cancellationToken).ConfigureAwait(false))
5✔
1890
                        {
1891
                                return;
1892
                        }
1893

1894
                        var cursor = await context.Set<ImmediateFairQueueGroupEntity>()
4✔
1895
                                .SingleOrDefaultAsync(
4✔
1896
                                        group => group.QueueName == queueName && group.GroupId == groupId,
4✔
1897
                                        cancellationToken
4✔
1898
                                )
4✔
1899
                                .ConfigureAwait(false);
4✔
1900
                        if (cursor is null)
4✔
1901
                                return;
1902

1903
                        _ = context.Remove(cursor);
4✔
1904
                        _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
4✔
1905
                }
4✔
1906
                catch (Exception exception) when (
×
1907
                        !cancellationToken.IsCancellationRequested
×
1908
                        && exception is DbException or DbUpdateException
×
1909
                )
×
1910
                {
1911
                        // Cleanup is best-effort metadata maintenance and must not invalidate a committed transition.
1912
                }
×
1913
        }
5✔
1914

1915
        private static Task<bool> HasLiveGroupJobsAsync(
1916
                TContext context,
1917
                string queueName,
1918
                string groupId,
1919
                CancellationToken cancellationToken
1920
        ) => context.Set<ImmediateJobEntity>().AnyAsync(
5✔
1921
                job => job.QueueName == queueName
5✔
1922
                        && job.GroupId == groupId
5✔
1923
                        && (job.State == JobState.Pending
5✔
1924
                                || job.State == JobState.Scheduled
5✔
1925
                                || job.State == JobState.Active),
5✔
1926
                cancellationToken
5✔
1927
        );
5✔
1928

1929
        private async Task AddBatchJobCoreAsync(
1930
                string currentJobId,
1931
                int executionNumber,
1932
                JobRecord record,
1933
                ContinuationOptions options,
1934
                CancellationToken cancellationToken
1935
        )
1936
        {
1937
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1938
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
5✔
1939
                var current = await context.Set<ImmediateJobEntity>()
5✔
1940
                        .SingleOrDefaultAsync(job => job.Id == currentJobId && job.Attempt == executionNumber && job.State == JobState.Active, cancellationToken)
5✔
1941
                        .ConfigureAwait(false)
5✔
1942
                        ?? throw new ImmediateJobException($"The current active job '{currentJobId}' was not found.");
5✔
1943
                if (current.BatchId is not { } batchId)
5✔
1944
                        throw new ImmediateJobException("The current job does not belong to a batch.");
×
1945
                if (options is not (ContinuationOptions.BesideContinuations or ContinuationOptions.BeforeContinuations))
5✔
1946
                        throw new ArgumentOutOfRangeException(nameof(options));
×
1947
                if (!string.Equals(record.BatchId, batchId, StringComparison.Ordinal))
5✔
1948
                        throw new ImmediateJobException("The new job must belong to the current job's batch.");
5✔
1949
                if (record.State is JobState.Active or JobState.AwaitingContinuation || IsTerminal(record.State))
×
1950
                        throw new ImmediateJobException($"Concurrent batch member '{record.Id}' has invalid state '{record.State}'.");
×
1951

1952
                var batch = await context.Set<ImmediateJobBatchEntity>()
×
1953
                        .SingleAsync(item => item.Id == batchId && item.State == BatchState.Executing, cancellationToken)
×
1954
                        .ConfigureAwait(false);
×
1955
                var job = ToEntity(record);
×
1956
                _ = context.Add(job);
×
1957
                batch.TotalJobs++;
×
1958
                batch.PendingCount++;
×
1959
                batch.ConcurrencyStamp = Guid.NewGuid();
×
1960

1961
                if (options == ContinuationOptions.BeforeContinuations)
×
1962
                {
1963
                        var waiters = await GetActiveWaitersAsync(context, currentJobId, cancellationToken).ConfigureAwait(false);
×
1964
                        foreach (var waiter in waiters)
×
1965
                        {
1966
                                _ = context.Add(new ImmediateJobContinuationEntity
×
1967
                                {
×
1968
                                        ChildJobId = waiter.Id,
×
1969
                                        ParentKind = ContinuationParentKind.Job,
×
1970
                                        ParentId = job.Id,
×
1971
                                        Trigger = ContinuationTrigger.Success,
×
1972
                                });
×
1973
                                waiter.RemainingDependencies++;
×
1974
                                waiter.ConcurrencyStamp = Guid.NewGuid();
×
1975
                        }
1976
                }
1977

1978
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
×
1979
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
×
1980
        }
×
1981

1982
        private static async Task FlushContinuationAdditionsAsync(
1983
                TContext context,
1984
                ImmediateJobEntity current,
1985
                IReadOnlyList<JobContinuationAddition> additions,
1986
                CancellationToken cancellationToken
1987
        )
1988
        {
1989
                var ids = new HashSet<string>(StringComparer.Ordinal);
5✔
1990
                var trackedAdditions = 0;
5✔
1991
                foreach (var addition in additions)
5✔
1992
                {
1993
                        ArgumentNullException.ThrowIfNull(addition);
5✔
1994
                        ArgumentNullException.ThrowIfNull(addition.Job);
5✔
1995
                        if (!ids.Add(addition.Job.Id))
5✔
1996
                                throw new ImmediateJobException("Buffered continuations contain duplicate job identifiers.");
×
1997
                        if (!Enum.IsDefined(addition.Trigger))
5✔
1998
                                throw new ArgumentOutOfRangeException(nameof(additions), "Unknown continuation trigger.");
4✔
1999
                        if (addition.Job.State is not (JobState.Pending or JobState.Scheduled))
5✔
2000
                                throw new ImmediateJobException($"Dynamic continuation '{addition.Job.Id}' has invalid state '{addition.Job.State}'.");
×
2001

2002
                        if (addition.Options == ContinuationOptions.Detached)
5✔
2003
                        {
2004
                                if (addition.Job.BatchId is not null)
5✔
2005
                                        throw new ImmediateJobException("A detached continuation cannot belong to a batch.");
5✔
2006
                        }
2007
                        else if (addition.Options is ContinuationOptions.BesideContinuations or ContinuationOptions.BeforeContinuations)
5✔
2008
                        {
2009
                                if (current.BatchId is null || !string.Equals(addition.Job.BatchId, current.BatchId, StringComparison.Ordinal))
5✔
2010
                                        throw new ImmediateJobException("A batch-tracked continuation must belong to the current job's batch.");
5✔
2011
                                trackedAdditions++;
×
2012
                        }
2013
                        else
2014
                        {
2015
                                throw new ArgumentOutOfRangeException(nameof(additions), "Unknown continuation option.");
4✔
2016
                        }
2017
                }
2018

2019
                var waiters = additions.Any(static addition => addition.Options == ContinuationOptions.BeforeContinuations)
×
2020
                        ? await GetActiveWaitersAsync(context, current.Id, cancellationToken).ConfigureAwait(false)
×
2021
                        : [];
×
2022
                ImmediateJobBatchEntity? batch = null;
2023
                if (trackedAdditions != 0)
×
2024
                {
2025
                        if (current.BatchId is not { } batchId)
×
2026
                                throw new ImmediateJobException("The current job does not belong to a batch.");
×
2027
                        batch = await context.Set<ImmediateJobBatchEntity>()
×
2028
                                .SingleAsync(item => item.Id == batchId && item.State == BatchState.Executing, cancellationToken)
×
2029
                                .ConfigureAwait(false);
×
2030
                        batch.TotalJobs += trackedAdditions;
×
2031
                        batch.PendingCount += trackedAdditions;
×
2032
                        batch.ConcurrencyStamp = Guid.NewGuid();
×
2033
                }
2034

2035
                foreach (var addition in additions)
×
2036
                {
2037
                        var job = ToEntity(addition.Job with
×
2038
                        {
×
2039
                                State = JobState.AwaitingContinuation,
×
2040
                                RemainingDependencies = 1,
×
2041
                        });
×
2042
                        _ = context.Add(job);
×
2043
                        _ = context.Add(new ImmediateJobContinuationEntity
×
2044
                        {
×
2045
                                ChildJobId = job.Id,
×
2046
                                ParentKind = ContinuationParentKind.Job,
×
2047
                                ParentId = current.Id,
×
2048
                                Trigger = addition.Trigger,
×
2049
                        });
×
2050

2051
                        if (addition.Options != ContinuationOptions.BeforeContinuations)
×
2052
                                continue;
2053
                        foreach (var waiter in waiters)
×
2054
                        {
2055
                                _ = context.Add(new ImmediateJobContinuationEntity
×
2056
                                {
×
2057
                                        ChildJobId = waiter.Id,
×
2058
                                        ParentKind = ContinuationParentKind.Job,
×
2059
                                        ParentId = job.Id,
×
2060
                                        Trigger = ContinuationTrigger.Success,
×
2061
                                });
×
2062
                                waiter.RemainingDependencies++;
×
2063
                                waiter.ConcurrencyStamp = Guid.NewGuid();
×
2064
                        }
2065
                }
2066
        }
×
2067

2068
        private static async Task<List<ImmediateJobEntity>> GetActiveWaitersAsync(
2069
                TContext context,
2070
                string currentJobId,
2071
                CancellationToken cancellationToken
2072
        )
2073
        {
2074
                var waiterIds = await context.Set<ImmediateJobContinuationEntity>()
×
2075
                        .Where(edge => edge.ParentKind == ContinuationParentKind.Job && edge.ParentId == currentJobId)
×
2076
                        .Select(edge => edge.ChildJobId)
×
2077
                        .Distinct()
×
2078
                        .ToArrayAsync(cancellationToken)
×
2079
                        .ConfigureAwait(false);
×
2080
                return waiterIds.Length == 0
×
2081
                        ? []
×
2082
                        : await context.Set<ImmediateJobEntity>()
×
2083
                                .Where(job => waiterIds.Contains(job.Id) && job.State == JobState.AwaitingContinuation)
×
2084
                                .ToListAsync(cancellationToken)
×
2085
                                .ConfigureAwait(false);
×
2086
        }
2087

2088
        private static async Task PropagateTerminalAsync(
2089
                TContext context,
2090
                ImmediateJobEntity terminalJob,
2091
                DateTimeOffset now,
2092
                CancellationToken cancellationToken
2093
        )
2094
        {
2095
                var parents = new Queue<(ContinuationParentKind Kind, string Id, ContinuationParentOutcome Outcome)>();
5✔
2096
                var processed = new HashSet<(ContinuationParentKind Kind, string Id)>();
5✔
2097
                parents.Enqueue((
5✔
2098
                        ContinuationParentKind.Job,
5✔
2099
                        terminalJob.Id,
5✔
2100
                        GetParentOutcome(terminalJob.State)
5✔
2101
                ));
5✔
2102
                await UpdateBatchForTerminalJobAsync(context, terminalJob, now, parents, cancellationToken).ConfigureAwait(false);
5✔
2103

2104
                while (parents.TryDequeue(out var parent))
5✔
2105
                {
2106
                        if (!processed.Add((parent.Kind, parent.Id)))
5✔
2107
                                continue;
2108
                        var edges = await context.Set<ImmediateJobContinuationEntity>()
5✔
2109
                                .Where(edge => edge.ParentKind == parent.Kind
5✔
2110
                                        && edge.ParentId == parent.Id
5✔
2111
                                        && edge.ParentOutcome == ContinuationParentOutcome.Unsettled)
5✔
2112
                                .ToListAsync(cancellationToken)
5✔
2113
                                .ConfigureAwait(false);
5✔
2114
                        foreach (var edge in edges)
5✔
2115
                        {
2116
                                edge.ParentOutcome = parent.Outcome;
5✔
2117
                                var child = await context.Set<ImmediateJobEntity>()
5✔
2118
                                        .SingleOrDefaultAsync(job => job.Id == edge.ChildJobId, cancellationToken)
5✔
2119
                                        .ConfigureAwait(false);
5✔
2120
                                if (child is null || IsTerminal(child.State))
5✔
2121
                                        continue;
2122

2123
                                if (child.State != JobState.AwaitingContinuation || child.RemainingDependencies <= 0)
5✔
2124
                                        continue;
2125
                                child.RemainingDependencies--;
5✔
2126
                                if (parent.Outcome == ContinuationParentOutcome.Failed)
5✔
2127
                                        child.FailedDependencies++;
5✔
2128
                                if (child.RemainingDependencies == 0)
5✔
2129
                                {
2130
                                        var skip = await ShouldSkipSettledContinuationAsync(
5✔
2131
                                                context,
5✔
2132
                                                child.Id,
5✔
2133
                                                cancellationToken
5✔
2134
                                        ).ConfigureAwait(false);
5✔
2135
                                        if (skip)
5✔
2136
                                        {
2137
                                                child.State = JobState.Skipped;
5✔
2138
                                                child.CompletedAt = now;
5✔
2139
                                                parents.Enqueue((ContinuationParentKind.Job, child.Id, ContinuationParentOutcome.Other));
5✔
2140
                                                await UpdateBatchForTerminalJobAsync(context, child, now, parents, cancellationToken).ConfigureAwait(false);
5✔
2141
                                        }
2142
                                        else
2143
                                        {
2144
                                                child.State = child.DueAt <= now ? JobState.Pending : JobState.Scheduled;
5✔
2145
                                        }
2146
                                }
2147

2148
                                child.ConcurrencyStamp = Guid.NewGuid();
5✔
2149
                        }
4✔
2150
                }
4✔
2151
        }
5✔
2152

2153
        private static async Task<bool> ShouldSkipSettledContinuationAsync(
2154
                TContext context,
2155
                string childJobId,
2156
                CancellationToken cancellationToken
2157
        )
2158
        {
2159
                var edges = await context.Set<ImmediateJobContinuationEntity>()
5✔
2160
                        .Where(edge => edge.ChildJobId == childJobId)
5✔
2161
                        .ToListAsync(cancellationToken)
5✔
2162
                        .ConfigureAwait(false);
5✔
2163
                var requiresFailure = false;
5✔
2164
                var anyFailed = false;
5✔
2165
                foreach (var edge in edges)
5✔
2166
                {
2167
                        if (edge.Trigger == ContinuationTrigger.Success
5✔
2168
                                && edge.ParentOutcome != ContinuationParentOutcome.Succeeded)
5✔
2169
                        {
UNCOV
2170
                                return true;
×
2171
                        }
2172

2173
                        requiresFailure |= edge.Trigger == ContinuationTrigger.Failure;
5✔
2174
                        anyFailed |= edge.ParentOutcome == ContinuationParentOutcome.Failed;
5✔
2175
                }
2176

2177
                return requiresFailure && !anyFailed;
5✔
2178
        }
4✔
2179

2180
        private static async Task UpdateBatchForTerminalJobAsync(
2181
                TContext context,
2182
                ImmediateJobEntity job,
2183
                DateTimeOffset now,
2184
                Queue<(ContinuationParentKind Kind, string Id, ContinuationParentOutcome Outcome)> parents,
2185
                CancellationToken cancellationToken
2186
        )
2187
        {
2188
                if (job.BatchId is not { } batchId)
5✔
2189
                        return;
5✔
2190
                var batch = await context.Set<ImmediateJobBatchEntity>()
5✔
2191
                        .SingleAsync(item => item.Id == batchId, cancellationToken)
5✔
2192
                        .ConfigureAwait(false);
5✔
2193
                batch.PendingCount = Math.Max(0, batch.PendingCount - 1);
5✔
2194
                switch (job.State)
5✔
2195
                {
2196
                        case JobState.Succeeded:
2197
                                batch.SucceededCount++;
5✔
2198
                                break;
5✔
2199
                        case JobState.Failed:
2200
                                batch.FailedCount++;
×
2201
                                break;
×
2202
                        case JobState.Cancelled:
2203
                                batch.CancelledCount++;
5✔
2204
                                break;
5✔
2205
                        case JobState.Skipped:
2206
                                batch.SkippedCount++;
1✔
2207
                                break;
1✔
2208
                        case JobState.AwaitingContinuation:
2209
                        case JobState.AwaitingParameters:
2210
                        case JobState.Scheduled:
2211
                        case JobState.Pending:
2212
                        case JobState.Active:
2213
                                throw new ImmediateJobException($"Job '{job.Id}' is not terminal.");
×
2214
                        default:
2215
                                throw new ArgumentOutOfRangeException(nameof(job), job.State, "Unknown job state.");
×
2216
                }
2217

2218
                batch.ConcurrencyStamp = Guid.NewGuid();
5✔
2219
                if (batch.PendingCount != 0)
5✔
2220
                        return;
5✔
2221
                batch.State = GetTerminalBatchState(batch.FailedCount, batch.CancelledCount);
5✔
2222
                batch.CompletedAt = now;
5✔
2223
                parents.Enqueue((
5✔
2224
                        ContinuationParentKind.Batch,
5✔
2225
                        batch.Id,
5✔
2226
                        GetParentOutcome(batch.State)
5✔
2227
                ));
5✔
2228
        }
5✔
2229

2230
        private static async Task EvaluateInitialDependenciesAsync(
2231
                TContext context,
2232
                Dictionary<string, ImmediateJobEntity> jobs,
2233
                ImmediateJobContinuationEntity[] edges,
2234
                DateTimeOffset now,
2235
                CancellationToken cancellationToken
2236
        )
2237
        {
2238
                var externalJobIds = edges
5✔
2239
                        .Where(edge => edge.ParentKind == ContinuationParentKind.Job && !jobs.ContainsKey(edge.ParentId))
5✔
2240
                        .Select(static edge => edge.ParentId)
5✔
2241
                        .Distinct(StringComparer.Ordinal)
5✔
2242
                        .Order(StringComparer.Ordinal)
5✔
2243
                        .ToArray();
5✔
2244
                var externalBatchIds = edges
5✔
2245
                        .Where(static edge => edge.ParentKind == ContinuationParentKind.Batch)
5✔
2246
                        .Select(static edge => edge.ParentId)
5✔
2247
                        .Distinct(StringComparer.Ordinal)
5✔
2248
                        .Order(StringComparer.Ordinal)
5✔
2249
                        .ToArray();
5✔
2250
                var externalJobEntities = externalJobIds.Length == 0
5✔
2251
                        ? []
5✔
2252
                        : await context.Set<ImmediateJobEntity>()
5✔
2253
                                .Where(job => externalJobIds.Contains(job.Id))
5✔
2254
                                .OrderBy(static job => job.Id)
5✔
2255
                                .ToListAsync(cancellationToken)
5✔
2256
                                .ConfigureAwait(false);
5✔
2257
                var externalBatchEntities = externalBatchIds.Length == 0
5✔
2258
                        ? []
5✔
2259
                        : await context.Set<ImmediateJobBatchEntity>()
5✔
2260
                                .Where(batch => externalBatchIds.Contains(batch.Id))
5✔
2261
                                .OrderBy(static batch => batch.Id)
5✔
2262
                                .ToListAsync(cancellationToken)
5✔
2263
                                .ConfigureAwait(false);
5✔
2264
                var externalJobs = externalJobEntities.ToDictionary(job => job.Id, StringComparer.Ordinal);
5✔
2265
                var externalBatches = externalBatchEntities.ToDictionary(batch => batch.Id, StringComparer.Ordinal);
5✔
2266
                if (externalJobs.Count != externalJobIds.Length || externalBatches.Count != externalBatchIds.Length)
5✔
2267
                        throw new ImmediateJobException("A continuation parent does not exist.");
5✔
2268
                foreach (var parent in externalJobEntities.Where(parent => !IsTerminal(parent.State)))
5✔
2269
                        parent.ConcurrencyStamp = Guid.NewGuid();
5✔
2270
                foreach (var parent in externalBatchEntities.Where(parent => parent.State == BatchState.Executing))
5✔
2271
                        parent.ConcurrencyStamp = Guid.NewGuid();
4✔
2272

2273
                var incoming = edges.ToLookup(static edge => edge.ChildJobId, StringComparer.Ordinal);
5✔
2274
                var changed = true;
5✔
2275
                while (changed)
5✔
2276
                {
2277
                        changed = false;
5✔
2278
                        foreach (var job in jobs.Values)
5✔
2279
                        {
2280
                                var dependencies = incoming[job.Id];
5✔
2281
                                if (!dependencies.Any() || IsTerminal(job.State))
5✔
2282
                                        continue;
2283
                                var remaining = 0;
5✔
2284
                                var failedDependencies = 0;
5✔
2285
                                var requiresFailure = false;
5✔
2286
                                var violated = false;
5✔
2287
                                foreach (var edge in dependencies)
5✔
2288
                                {
2289
                                        var (terminal, parentSucceeded, parentFailed) = GetParentState(
5✔
2290
                                                edge,
5✔
2291
                                                jobs,
5✔
2292
                                                externalJobs,
5✔
2293
                                                externalBatches
5✔
2294
                                        );
5✔
2295
                                        requiresFailure |= edge.Trigger == ContinuationTrigger.Failure;
5✔
2296
                                        if (!terminal)
5✔
2297
                                        {
2298
                                                remaining++;
5✔
2299
                                                continue;
5✔
2300
                                        }
2301

2302
                                        edge.ParentOutcome = GetParentOutcome(parentSucceeded, parentFailed);
1✔
2303

2304
                                        if (parentFailed)
1✔
2305
                                                failedDependencies++;
×
2306
                                        if (edge.Trigger == ContinuationTrigger.Success && !parentSucceeded)
1✔
2307
                                                violated = true;
×
2308
                                }
2309

2310
                                job.FailedDependencies = failedDependencies;
5✔
2311
                                if (violated || (remaining == 0 && requiresFailure && failedDependencies == 0))
5✔
2312
                                {
2313
                                        job.State = JobState.Skipped;
×
2314
                                        job.RemainingDependencies = 0;
×
2315
                                        job.CompletedAt = now;
×
2316
                                        changed = true;
×
2317
                                }
2318
                                else if (remaining == 0)
5✔
2319
                                {
2320
                                        job.State = job.DueAt <= now ? JobState.Pending : JobState.Scheduled;
1✔
2321
                                        job.RemainingDependencies = 0;
1✔
2322
                                }
2323
                                else
2324
                                {
2325
                                        job.State = JobState.AwaitingContinuation;
5✔
2326
                                        job.RemainingDependencies = remaining;
5✔
2327
                                }
2328
                        }
2329
                }
2330
        }
5✔
2331

2332
        private static (bool Terminal, bool Succeeded, bool Failed) GetParentState(
2333
                ImmediateJobContinuationEntity edge,
2334
                Dictionary<string, ImmediateJobEntity> jobs,
2335
                Dictionary<string, ImmediateJobEntity> externalJobs,
2336
                Dictionary<string, ImmediateJobBatchEntity> externalBatches
2337
        )
2338
        {
2339
                if (edge.ParentKind == ContinuationParentKind.Batch)
5✔
2340
                {
2341
                        var state = externalBatches[edge.ParentId].State;
5✔
2342
                        return (state != BatchState.Executing, state == BatchState.Succeeded, state == BatchState.Failed);
5✔
2343
                }
2344

2345
                var jobState = jobs.TryGetValue(edge.ParentId, out var job) ? job.State : externalJobs[edge.ParentId].State;
5✔
2346
                return (IsTerminal(jobState), jobState == JobState.Succeeded, jobState == JobState.Failed);
5✔
2347
        }
2348

2349
        private static void ThrowIfCyclic(
2350
                HashSet<string> jobIds,
2351
                IReadOnlyList<ImmediateJobContinuationEntity> edges
2352
        )
2353
        {
2354
                var indegree = jobIds.ToDictionary(static id => id, static _ => 0, StringComparer.Ordinal);
5✔
2355
                var children = new Dictionary<string, List<string>>(StringComparer.Ordinal);
5✔
2356
                foreach (var edge in edges.Where(edge =>
5✔
2357
                        edge.ParentKind == ContinuationParentKind.Job && jobIds.Contains(edge.ParentId)))
5✔
2358
                {
2359
                        indegree[edge.ChildJobId]++;
5✔
2360
                        if (!children.TryGetValue(edge.ParentId, out var values))
5✔
2361
                                children[edge.ParentId] = values = [];
5✔
2362
                        values.Add(edge.ChildJobId);
5✔
2363
                }
2364

2365
                var ready = new Queue<string>(indegree.Where(static pair => pair.Value == 0).Select(static pair => pair.Key));
5✔
2366
                var visited = 0;
5✔
2367
                while (ready.TryDequeue(out var parent))
5✔
2368
                {
2369
                        visited++;
5✔
2370
                        if (!children.TryGetValue(parent, out var values))
5✔
2371
                                continue;
2372
                        foreach (var child in values)
5✔
2373
                        {
2374
                                if (--indegree[child] == 0)
5✔
2375
                                        ready.Enqueue(child);
5✔
2376
                        }
2377
                }
2378

2379
                if (visited != jobIds.Count)
5✔
2380
                        throw new ImmediateJobException("The continuation graph contains a dependency cycle.");
×
2381
        }
5✔
2382

2383
        private static bool IsTerminal(JobState state) =>
2384
                state is JobState.Succeeded or JobState.Failed or JobState.Cancelled or JobState.Skipped;
5✔
2385

2386
        private static ContinuationParentOutcome GetParentOutcome(JobState state) => state switch
5✔
2387
        {
5✔
2388
                JobState.Succeeded => ContinuationParentOutcome.Succeeded,
5✔
2389
                JobState.Failed => ContinuationParentOutcome.Failed,
5✔
2390
                JobState.AwaitingContinuation or
5✔
2391
                JobState.AwaitingParameters or
5✔
2392
                JobState.Scheduled or
5✔
2393
                JobState.Pending or
5✔
2394
                JobState.Active or
5✔
2395
                JobState.Cancelled or
5✔
2396
                JobState.Skipped => ContinuationParentOutcome.Other,
5✔
2397
                _ => throw new ArgumentOutOfRangeException(nameof(state), state, "Unknown job state."),
×
2398
        };
5✔
2399

2400
        private static ContinuationParentOutcome GetParentOutcome(BatchState state) => state switch
5✔
2401
        {
5✔
2402
                BatchState.Succeeded => ContinuationParentOutcome.Succeeded,
5✔
2403
                BatchState.Failed => ContinuationParentOutcome.Failed,
×
2404
                BatchState.Executing or BatchState.Cancelled => ContinuationParentOutcome.Other,
5✔
2405
                _ => throw new ArgumentOutOfRangeException(nameof(state), state, "Unknown batch state."),
×
2406
        };
5✔
2407

2408
        private static ContinuationParentOutcome GetParentOutcome(bool succeeded, bool failed) =>
2409
                (succeeded, failed) switch
1✔
2410
                {
1✔
2411
                        (true, _) => ContinuationParentOutcome.Succeeded,
1✔
2412
                        (_, true) => ContinuationParentOutcome.Failed,
×
2413
                        _ => ContinuationParentOutcome.Other,
×
2414
                };
1✔
2415

2416
        private static BatchState GetTerminalBatchState(int failed, int cancelled) =>
2417
                failed != 0 ? BatchState.Failed : cancelled != 0 ? BatchState.Cancelled : BatchState.Succeeded;
5✔
2418

2419
        private async ValueTask MutateRecurringAsync(string name, Action<ImmediateRecurringJobEntity> mutate, CancellationToken cancellationToken)
2420
        {
2421
                ArgumentException.ThrowIfNullOrWhiteSpace(name);
1✔
2422
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
1✔
2423
                var schedule = await context.Set<ImmediateRecurringJobEntity>().FindAsync([name], cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Recurring schedule '{name}' was not found.");
1✔
UNCOV
2424
                mutate(schedule);
×
2425
                schedule.ConcurrencyStamp = Guid.NewGuid();
×
2426
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
×
2427
        }
×
2428

2429
        private static Task<int> UpdateRecurringAsync(
2430
                TContext context,
2431
                RecurringJobSchedule schedule,
2432
                CancellationToken cancellationToken
2433
        )
2434
        {
2435
                var concurrencyStamp = Guid.NewGuid();
5✔
2436
                return context.Set<ImmediateRecurringJobEntity>()
5✔
2437
                        .Where(entity => entity.Name == schedule.Name && (schedule.IsCodeDefined || !entity.IsCodeDefined))
5✔
2438
                        .ExecuteUpdateAsync(setters => setters
5✔
2439
                                .SetProperty(entity => entity.JobName, schedule.JobName)
5✔
2440
                                .SetProperty(entity => entity.Cron, schedule.Cron)
5✔
2441
                                .SetProperty(entity => entity.TimeZone, schedule.TimeZone)
5✔
2442
                                .SetProperty(entity => entity.IsCodeDefined, schedule.IsCodeDefined)
5✔
2443
                                .SetProperty(entity => entity.NextRunAt, schedule.NextRunAt)
5✔
2444
                                .SetProperty(entity => entity.ConcurrencyStamp, concurrencyStamp),
5✔
2445
                                cancellationToken);
5✔
2446
        }
2447

2448
        private static async Task ThrowIfReplacingCodeDefinedScheduleAsync(
2449
                TContext context,
2450
                RecurringJobSchedule schedule,
2451
                CancellationToken cancellationToken
2452
        )
2453
        {
2454
                if (!schedule.IsCodeDefined && await context.Set<ImmediateRecurringJobEntity>()
5✔
2455
                        .AnyAsync(entity => entity.Name == schedule.Name && entity.IsCodeDefined, cancellationToken)
5✔
2456
                        .ConfigureAwait(false))
5✔
2457
                {
2458
                        throw new ImmediateJobException("Code-defined recurring schedules cannot be replaced by dynamic schedules.");
4✔
2459
                }
2460
        }
5✔
2461

2462
        private static ImmediateJobEntity ToEntity(JobRecord job) => new()
5✔
2463
        {
5✔
2464
                Id = job.Id,
5✔
2465
                QueueName = job.QueueName,
5✔
2466
                JobName = job.JobName,
5✔
2467
                GroupId = job.GroupId,
5✔
2468
                Payload = job.Payload,
5✔
2469
                Context = job.Context,
5✔
2470
                State = job.State,
5✔
2471
                DueAt = job.DueAt,
5✔
2472
                CreatedAt = job.CreatedAt,
5✔
2473
                Attempt = job.Attempt,
5✔
2474
                WorkerId = job.WorkerId,
5✔
2475
                LeaseExpiresAt = job.LeaseExpiresAt,
5✔
2476
                LastError = job.LastError,
5✔
2477
                CompletedAt = job.CompletedAt,
5✔
2478
                RecurringKey = job.RecurringKey,
5✔
2479
                TraceParent = job.TraceParent,
5✔
2480
                TraceState = job.TraceState,
5✔
2481
                ExecutionTraceId = job.ExecutionTraceId,
5✔
2482
                ExecutionSpanId = job.ExecutionSpanId,
5✔
2483
                ExecutionStartedAt = job.ExecutionStartedAt,
5✔
2484
                BatchId = job.BatchId,
5✔
2485
                RemainingDependencies = job.RemainingDependencies,
5✔
2486
                FailedDependencies = job.FailedDependencies,
5✔
2487
                ConcurrencyStamp = Guid.NewGuid(),
5✔
2488
        };
5✔
2489

2490
        private static async Task PrepareAcquisitionExecutionsAsync(
2491
                TContext context,
2492
                ImmediateJobEntity candidate,
2493
                string workerId,
2494
                DateTimeOffset acquiredAt,
2495
                CancellationToken cancellationToken
2496
        )
2497
        {
2498
                var previous = await GetOrMaterializeExecutionAsync(context, candidate, cancellationToken).ConfigureAwait(false);
5✔
2499
                if (candidate.State == JobState.Active && previous is not null)
5✔
2500
                {
2501
                        previous.State = JobExecutionState.Interrupted;
5✔
2502
                        previous.CompletedAt = candidate.LeaseExpiresAt;
5✔
2503
                        previous.Error = null;
5✔
2504
                }
2505

2506
                _ = context.Add(new ImmediateJobExecutionEntity
5✔
2507
                {
5✔
2508
                        JobId = candidate.Id,
5✔
2509
                        Attempt = candidate.Attempt + 1,
5✔
2510
                        State = JobExecutionState.Active,
5✔
2511
                        WorkerId = workerId,
5✔
2512
                        AcquiredAt = acquiredAt,
5✔
2513
                });
5✔
2514
        }
5✔
2515

2516
        private static async Task<ImmediateJobExecutionEntity?> GetOrMaterializeExecutionAsync(
2517
                TContext context,
2518
                ImmediateJobEntity job,
2519
                CancellationToken cancellationToken
2520
        )
2521
        {
2522
                if (job.Attempt <= 0)
5✔
2523
                        return null;
5✔
2524
                var execution = await context.Set<ImmediateJobExecutionEntity>()
5✔
2525
                        .SingleOrDefaultAsync(
5✔
2526
                                item => item.JobId == job.Id && item.Attempt == job.Attempt,
5✔
2527
                                cancellationToken
5✔
2528
                        )
5✔
2529
                        .ConfigureAwait(false);
5✔
2530
                if (execution is not null)
5✔
2531
                        return execution;
5✔
2532

2533
                var synthetic = JobExecutionRecord.CreateSynthetic(ToRecord(job));
1✔
2534
                if (synthetic is null)
1✔
NEW
2535
                        return null;
×
2536
                execution = ToEntity(synthetic);
1✔
2537
                _ = context.Add(execution);
1✔
2538
                return execution;
1✔
2539
        }
4✔
2540

2541
        private static ImmediateJobExecutionEntity ToEntity(JobExecutionRecord execution) => new()
1✔
2542
        {
1✔
2543
                JobId = execution.JobId,
1✔
2544
                Attempt = execution.Attempt,
1✔
2545
                State = execution.State,
1✔
2546
                WorkerId = execution.WorkerId,
1✔
2547
                AcquiredAt = execution.AcquiredAt,
1✔
2548
                ExecutionStartedAt = execution.ExecutionStartedAt,
1✔
2549
                CompletedAt = execution.CompletedAt,
1✔
2550
                ExecutionTraceId = execution.ExecutionTraceId,
1✔
2551
                ExecutionSpanId = execution.ExecutionSpanId,
1✔
2552
                Error = execution.Error,
1✔
2553
                IsSynthetic = execution.IsSynthetic,
1✔
2554
        };
1✔
2555

2556
        private static JobExecutionRecord ToRecord(ImmediateJobExecutionEntity execution) => new()
1✔
2557
        {
1✔
2558
                JobId = execution.JobId,
1✔
2559
                Attempt = execution.Attempt,
1✔
2560
                State = execution.State,
1✔
2561
                WorkerId = execution.WorkerId,
1✔
2562
                AcquiredAt = execution.AcquiredAt,
1✔
2563
                ExecutionStartedAt = execution.ExecutionStartedAt,
1✔
2564
                CompletedAt = execution.CompletedAt,
1✔
2565
                ExecutionTraceId = execution.ExecutionTraceId,
1✔
2566
                ExecutionSpanId = execution.ExecutionSpanId,
1✔
2567
                Error = execution.Error,
1✔
2568
                IsSynthetic = execution.IsSynthetic,
1✔
2569
        };
1✔
2570

2571
        private static ImmediateJobContinuationEntity ToEntity(JobContinuationEdge edge)
2572
        {
2573
                var hasJobParent = edge.ParentJobId is not null;
5✔
2574
                var hasBatchParent = edge.ParentBatchId is not null;
5✔
2575
                if (hasJobParent == hasBatchParent)
5✔
2576
                        throw new ImmediateJobException("A continuation edge must identify exactly one parent job or batch.");
×
2577
                return new()
5✔
2578
                {
5✔
2579
                        ChildJobId = edge.ChildJobId,
5✔
2580
                        ParentKind = hasJobParent ? ContinuationParentKind.Job : ContinuationParentKind.Batch,
5✔
2581
                        ParentId = edge.ParentJobId ?? edge.ParentBatchId!,
5✔
2582
                        Trigger = edge.Trigger,
5✔
2583
                };
5✔
2584
        }
2585

2586
        private static ImmediateJobEntity Copy(ImmediateJobEntity job) => new()
5✔
2587
        {
5✔
2588
                Id = job.Id,
5✔
2589
                QueueName = job.QueueName,
5✔
2590
                JobName = job.JobName,
5✔
2591
                GroupId = job.GroupId,
5✔
2592
                Payload = job.Payload,
5✔
2593
                Context = job.Context,
5✔
2594
                State = job.State,
5✔
2595
                DueAt = job.DueAt,
5✔
2596
                CreatedAt = job.CreatedAt,
5✔
2597
                Attempt = job.Attempt,
5✔
2598
                WorkerId = job.WorkerId,
5✔
2599
                LeaseExpiresAt = job.LeaseExpiresAt,
5✔
2600
                LastError = job.LastError,
5✔
2601
                CompletedAt = job.CompletedAt,
5✔
2602
                RecurringKey = job.RecurringKey,
5✔
2603
                TraceParent = job.TraceParent,
5✔
2604
                TraceState = job.TraceState,
5✔
2605
                ExecutionTraceId = job.ExecutionTraceId,
5✔
2606
                ExecutionSpanId = job.ExecutionSpanId,
5✔
2607
                ExecutionStartedAt = job.ExecutionStartedAt,
5✔
2608
                BatchId = job.BatchId,
5✔
2609
                RemainingDependencies = job.RemainingDependencies,
5✔
2610
                FailedDependencies = job.FailedDependencies,
5✔
2611
                ConcurrencyStamp = job.ConcurrencyStamp,
5✔
2612
        };
5✔
2613

2614
        private static JobRecord ToRecord(ImmediateJobEntity job) => new()
5✔
2615
        {
5✔
2616
                Id = job.Id,
5✔
2617
                QueueName = job.QueueName,
5✔
2618
                JobName = job.JobName,
5✔
2619
                GroupId = job.GroupId,
5✔
2620
                Payload = job.Payload,
5✔
2621
                Context = job.Context,
5✔
2622
                State = job.State,
5✔
2623
                DueAt = job.DueAt,
5✔
2624
                CreatedAt = job.CreatedAt,
5✔
2625
                Attempt = job.Attempt,
5✔
2626
                WorkerId = job.WorkerId,
5✔
2627
                LeaseExpiresAt = job.LeaseExpiresAt,
5✔
2628
                LastError = job.LastError,
5✔
2629
                CompletedAt = job.CompletedAt,
5✔
2630
                RecurringKey = job.RecurringKey,
5✔
2631
                TraceParent = job.TraceParent,
5✔
2632
                TraceState = job.TraceState,
5✔
2633
                ExecutionTraceId = job.ExecutionTraceId,
5✔
2634
                ExecutionSpanId = job.ExecutionSpanId,
5✔
2635
                ExecutionStartedAt = job.ExecutionStartedAt,
5✔
2636
                BatchId = job.BatchId,
5✔
2637
                RemainingDependencies = job.RemainingDependencies,
5✔
2638
                FailedDependencies = job.FailedDependencies,
5✔
2639
        };
5✔
2640

2641
        private static BatchStatus ToStatus(ImmediateJobBatchEntity batch) => new(
5✔
2642
                batch.Id,
5✔
2643
                batch.State,
5✔
2644
                batch.TotalJobs,
5✔
2645
                batch.SucceededCount,
5✔
2646
                batch.FailedCount,
5✔
2647
                batch.CancelledCount,
5✔
2648
                batch.SkippedCount,
5✔
2649
                batch.PendingCount,
5✔
2650
                batch.CreatedAt,
5✔
2651
                batch.StartedAt,
5✔
2652
                batch.CompletedAt,
5✔
2653
                BatchStatus.CalculateFractionSettled(batch.TotalJobs, batch.PendingCount)
5✔
2654
        );
5✔
2655

2656
        private static JobContinuationEdge ToContinuationEdge(ImmediateJobContinuationEntity edge) => new()
5✔
2657
        {
5✔
2658
                ChildJobId = edge.ChildJobId,
5✔
2659
                ParentJobId = edge.ParentKind == ContinuationParentKind.Job ? edge.ParentId : null,
5✔
2660
                ParentBatchId = edge.ParentKind == ContinuationParentKind.Batch ? edge.ParentId : null,
5✔
2661
                Trigger = edge.Trigger,
5✔
2662
        };
5✔
2663

2664
        private static BatchGraphEdge ToGraphEdge(ImmediateJobContinuationEntity edge) => new(
5✔
2665
                edge.ChildJobId,
5✔
2666
                edge.ParentKind == ContinuationParentKind.Job ? edge.ParentId : null,
5✔
2667
                edge.ParentKind == ContinuationParentKind.Batch ? edge.ParentId : null,
5✔
2668
                edge.Trigger
5✔
2669
        );
5✔
2670

2671
        private static ImmediateRecurringJobEntity ToEntity(RecurringJobSchedule schedule) => new()
5✔
2672
        {
5✔
2673
                Name = schedule.Name,
5✔
2674
                JobName = schedule.JobName,
5✔
2675
                Cron = schedule.Cron,
5✔
2676
                TimeZone = schedule.TimeZone,
5✔
2677
                IsCodeDefined = schedule.IsCodeDefined,
5✔
2678
                IsPaused = schedule.IsPaused,
5✔
2679
                NextRunAt = schedule.NextRunAt,
5✔
2680
                LastRunAt = schedule.LastRunAt,
5✔
2681
                ConcurrencyStamp = Guid.NewGuid(),
5✔
2682
        };
5✔
2683
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc