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

ImmediatePlatform / Immediate.Jobs / 30629636973

31 Jul 2026 12:10PM UTC coverage: 83.079% (+0.8%) from 82.321%
30629636973

Pull #81

github

web-flow
Merge 108bf070f into be7540808
Pull Request #81: Add a durable skipped job state

125 of 133 new or added lines in 10 files covered. (93.98%)

5 existing lines in 3 files now uncovered.

7473 of 8995 relevant lines covered (83.08%)

2.75 hits per line

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

83.22
/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
                entity.State = JobState.Active;
5✔
536
                entity.WorkerId = workerId;
5✔
537
                entity.LeaseExpiresAt = now + lease;
5✔
538
                entity.Attempt++;
5✔
539
                entity.CompletedAt = null;
5✔
540
                entity.ExecutionTraceId = null;
5✔
541
                entity.ExecutionSpanId = null;
5✔
542
                entity.ExecutionStartedAt = null;
5✔
543
                entity.ConcurrencyStamp = Guid.NewGuid();
5✔
544

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

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

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

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

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

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

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

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

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

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

685
                        try
686
                        {
687
                                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
5✔
688
                                acquired.Add(ToRecord(entity));
5✔
689
                        }
5✔
690
                        catch (DbUpdateConcurrencyException)
1✔
691
                        {
692
                                // Another scheduler claimed or changed this candidate first.
693
                        }
1✔
694
                }
4✔
695

696
                return acquired;
5✔
697
        }
4✔
698

699
        /// <inheritdoc />
700
        public ValueTask SetExecutionTelemetryAsync(
701
                string jobId,
702
                string workerId,
703
                string? traceId,
704
                string? spanId,
705
                DateTimeOffset startedAt,
706
                CancellationToken cancellationToken = default
707
        ) => MutateOwnedAsync(jobId, workerId, job =>
1✔
708
        {
1✔
709
                job.ExecutionTraceId = traceId;
1✔
710
                job.ExecutionSpanId = spanId;
1✔
711
                job.ExecutionStartedAt = startedAt;
1✔
712
        }, cancellationToken);
1✔
713

714
        /// <inheritdoc />
715
        public ValueTask RenewLeaseAsync(string jobId, string workerId, TimeSpan lease, CancellationToken cancellationToken = default)
716
        {
717
                ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(lease, TimeSpan.Zero);
×
718
                return MutateOwnedAsync(jobId, workerId, job => job.LeaseExpiresAt = _timeProvider.GetUtcNow() + lease, cancellationToken);
×
719
        }
720

721
        /// <inheritdoc />
722
        public ValueTask CompleteAsync(string jobId, string workerId, CancellationToken cancellationToken = default) =>
723
                CompleteWithContinuationsAsync(jobId, workerId, [], cancellationToken);
5✔
724

725
        /// <inheritdoc />
726
        public ValueTask CompleteWithContinuationsAsync(
727
                string jobId,
728
                string workerId,
729
                IReadOnlyList<JobContinuationAddition> additions,
730
                CancellationToken cancellationToken = default
731
        )
732
        {
733
                ArgumentNullException.ThrowIfNull(additions);
5✔
734
                return MutateOwnedWithDependenciesAsync(
5✔
735
                        jobId,
5✔
736
                        workerId,
5✔
737
                        error: null,
5✔
738
                        nextRetryAt: null,
5✔
739
                        succeeded: true,
5✔
740
                        additions,
5✔
741
                        cancellationToken
5✔
742
                );
5✔
743
        }
744

745
        /// <inheritdoc />
746
        public ValueTask AddBatchJobAsync(
747
                string currentJobId,
748
                JobRecord job,
749
                ContinuationOptions options,
750
                CancellationToken cancellationToken = default
751
        )
752
        {
753
                ArgumentNullException.ThrowIfNull(job);
5✔
754
                if (options == ContinuationOptions.Detached)
5✔
755
                        throw new ImmediateJobException("AddToBatchAsync cannot create a detached job.");
×
756
                return RetryConcurrencyAsync(
5✔
757
                        operationCancellationToken => AddBatchJobCoreAsync(
5✔
758
                                currentJobId,
5✔
759
                                job,
5✔
760
                                options,
5✔
761
                                operationCancellationToken
5✔
762
                        ),
5✔
763
                        cancellationToken
5✔
764
                );
5✔
765
        }
766

767
        /// <inheritdoc />
768
        public ValueTask FailAsync(
769
                string jobId,
770
                string workerId,
771
                string error,
772
                DateTimeOffset? nextRetryAt,
773
                CancellationToken cancellationToken = default
774
        ) => MutateOwnedWithDependenciesAsync(jobId, workerId, error, nextRetryAt, succeeded: false, [], cancellationToken);
5✔
775

776
        /// <inheritdoc />
777
        public async ValueTask UpsertRecurringAsync(RecurringJobSchedule schedule, CancellationToken cancellationToken = default)
778
        {
779
                ArgumentNullException.ThrowIfNull(schedule);
5✔
780
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
781
                if (await UpdateRecurringAsync(context, schedule, cancellationToken).ConfigureAwait(false) != 0)
5✔
782
                        return;
783
                await ThrowIfReplacingCodeDefinedScheduleAsync(context, schedule, cancellationToken).ConfigureAwait(false);
5✔
784

785
                _ = context.Add(ToEntity(schedule));
5✔
786
                try
787
                {
788
                        _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
5✔
789
                }
5✔
790
                catch (DbUpdateException)
791
                {
792
                        // A competing node inserted the same schedule after our update attempt.
793
                        await using var retryContext = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
×
794
                        if (await UpdateRecurringAsync(retryContext, schedule, cancellationToken).ConfigureAwait(false) != 0)
×
795
                                return;
796
                        await ThrowIfReplacingCodeDefinedScheduleAsync(retryContext, schedule, cancellationToken).ConfigureAwait(false);
×
797
                        throw;
×
798
                }
799
        }
4✔
800

801
        /// <inheritdoc />
802
        public async ValueTask RemoveObsoleteCodeDefinedRecurringAsync(
803
                IReadOnlyCollection<string> activeScheduleNames,
804
                CancellationToken cancellationToken = default
805
        )
806
        {
807
                ArgumentNullException.ThrowIfNull(activeScheduleNames);
4✔
808
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
4✔
809
                var schedules = context.Set<ImmediateRecurringJobEntity>()
4✔
810
                        .Where(schedule => schedule.IsCodeDefined);
4✔
811
                if (activeScheduleNames.Count != 0)
4✔
812
                        schedules = schedules.Where(schedule => !activeScheduleNames.Contains(schedule.Name));
4✔
813
                _ = await schedules.ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false);
4✔
814
        }
4✔
815

816
        /// <inheritdoc />
817
        public async ValueTask RemoveRecurringAsync(string name, CancellationToken cancellationToken = default)
818
        {
819
                ArgumentException.ThrowIfNullOrWhiteSpace(name);
5✔
820
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
821
                var removed = await context.Set<ImmediateRecurringJobEntity>()
5✔
822
                        .Where(schedule => schedule.Name == name && !schedule.IsCodeDefined)
5✔
823
                        .ExecuteDeleteAsync(cancellationToken)
5✔
824
                        .ConfigureAwait(false);
5✔
825
                if (removed != 0)
5✔
826
                        return;
827
                if (await context.Set<ImmediateRecurringJobEntity>()
5✔
828
                        .AnyAsync(schedule => schedule.Name == name, cancellationToken)
5✔
829
                        .ConfigureAwait(false))
5✔
830
                {
831
                        throw new ImmediateJobException("Code-defined recurring schedules cannot be deleted.");
4✔
832
                }
833

834
                throw new KeyNotFoundException($"Recurring schedule '{name}' was not found.");
5✔
835
        }
3✔
836

837
        /// <inheritdoc />
838
        public ValueTask PauseRecurringAsync(string name, CancellationToken cancellationToken = default)
839
                => MutateRecurringAsync(name, schedule => schedule.IsPaused = true, cancellationToken);
×
840

841
        /// <inheritdoc />
842
        public ValueTask ResumeRecurringAsync(string name, CancellationToken cancellationToken = default)
843
                => MutateRecurringAsync(name, schedule => schedule.IsPaused = false, cancellationToken);
×
844

845
        /// <inheritdoc />
846
        public async ValueTask<IReadOnlyList<RecurringJobSchedule>> GetDueRecurringAsync(DateTimeOffset now, int batchSize, CancellationToken cancellationToken = default)
847
        {
848
                ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(batchSize, 0);
×
849
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
×
850
                return await context.Set<ImmediateRecurringJobEntity>()
×
851
                        .AsNoTracking()
×
852
                        .Where(schedule => !schedule.IsPaused && schedule.NextRunAt <= now)
×
853
                        .OrderBy(schedule => schedule.NextRunAt)
×
854
                        .Take(batchSize)
×
855
                        .Select(schedule => new RecurringJobSchedule
×
856
                        {
×
857
                                Name = schedule.Name,
×
858
                                JobName = schedule.JobName,
×
859
                                Cron = schedule.Cron,
×
860
                                TimeZone = schedule.TimeZone,
×
861
                                IsCodeDefined = schedule.IsCodeDefined,
×
862
                                IsPaused = schedule.IsPaused,
×
863
                                NextRunAt = schedule.NextRunAt,
×
864
                                LastRunAt = schedule.LastRunAt,
×
865
                        })
×
866
                        .ToListAsync(cancellationToken)
×
867
                        .ConfigureAwait(false);
×
868
        }
869

870
        /// <inheritdoc />
871
        public async ValueTask<bool> MaterializeRecurringAsync(
872
                RecurringJobSchedule schedule,
873
                JobRecord job,
874
                DateTimeOffset nextRunAt,
875
                CancellationToken cancellationToken = default
876
        )
877
        {
878
                ArgumentNullException.ThrowIfNull(schedule);
5✔
879
                ArgumentNullException.ThrowIfNull(job);
5✔
880
                await using var strategyContext = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
881
                var strategy = strategyContext.Database.CreateExecutionStrategy();
5✔
882
                return await strategy.ExecuteAsync(
5✔
883
                        operationCancellationToken => MaterializeRecurringCoreAsync(
5✔
884
                                schedule,
5✔
885
                                job,
5✔
886
                                nextRunAt,
5✔
887
                                operationCancellationToken
5✔
888
                        ),
5✔
889
                        cancellationToken
5✔
890
                ).ConfigureAwait(false);
5✔
891
        }
4✔
892

893
        private async Task<bool> MaterializeRecurringCoreAsync(
894
                RecurringJobSchedule schedule,
895
                JobRecord job,
896
                DateTimeOffset nextRunAt,
897
                CancellationToken cancellationToken
898
        )
899
        {
900
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
901
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
5✔
902
                var entity = await context.Set<ImmediateRecurringJobEntity>()
5✔
903
                        .SingleOrDefaultAsync(item => item.Name == schedule.Name, cancellationToken)
5✔
904
                        .ConfigureAwait(false);
5✔
905
                if (entity is null || entity.IsPaused || entity.NextRunAt != schedule.NextRunAt)
5✔
906
                        return false;
1✔
907

908
                entity.LastRunAt = schedule.NextRunAt;
5✔
909
                entity.NextRunAt = nextRunAt;
5✔
910
                entity.ConcurrencyStamp = Guid.NewGuid();
5✔
911
                _ = context.Add(ToEntity(job));
5✔
912
                try
913
                {
914
                        _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
5✔
915
                        await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
5✔
916
                        return true;
5✔
917
                }
918
                catch (DbUpdateException)
919
                {
920
                        await transaction.RollbackAsync(cancellationToken).ConfigureAwait(false);
×
921
                        return false;
×
922
                }
923
        }
4✔
924

925
        /// <inheritdoc />
926
        public async ValueTask<JobMonitoringSnapshot> GetMonitoringSnapshotAsync(CancellationToken cancellationToken = default)
927
        {
928
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
929
                var rawCounts = await context.Set<ImmediateJobEntity>()
5✔
930
                        .AsNoTracking()
5✔
931
                        .GroupBy(job => job.State)
5✔
932
                        .Select(group => new { State = group.Key, Count = group.LongCount() })
5✔
933
                        .ToListAsync(cancellationToken)
5✔
934
                        .ConfigureAwait(false);
5✔
935
                var counts = Enum.GetValues<JobState>().ToDictionary(static state => state, static _ => 0L);
5✔
936
                foreach (var item in rawCounts)
5✔
937
                        counts[item.State] = item.Count;
5✔
938

939
                var recurring = await context.Set<ImmediateRecurringJobEntity>()
5✔
940
                        .AsNoTracking()
5✔
941
                        .OrderBy(schedule => schedule.Name)
5✔
942
                        .Select(schedule => new RecurringJobSchedule
5✔
943
                        {
5✔
944
                                Name = schedule.Name,
5✔
945
                                JobName = schedule.JobName,
5✔
946
                                Cron = schedule.Cron,
5✔
947
                                TimeZone = schedule.TimeZone,
5✔
948
                                IsCodeDefined = schedule.IsCodeDefined,
5✔
949
                                IsPaused = schedule.IsPaused,
5✔
950
                                NextRunAt = schedule.NextRunAt,
5✔
951
                                LastRunAt = schedule.LastRunAt,
5✔
952
                        })
5✔
953
                        .ToListAsync(cancellationToken)
5✔
954
                        .ConfigureAwait(false);
5✔
955
                var cutoff = _timeProvider.GetUtcNow() - TimeSpan.FromMinutes(2);
5✔
956
                var servers = await context.Set<ImmediateJobServerEntity>()
5✔
957
                        .AsNoTracking()
5✔
958
                        .Where(server => server.LastHeartbeat >= cutoff)
5✔
959
                        .OrderBy(server => server.WorkerId)
5✔
960
                        .Select(server => new JobServerSnapshot(server.WorkerId, server.LastHeartbeat, server.ActiveWorkers, server.MaxWorkers))
5✔
961
                        .ToListAsync(cancellationToken)
5✔
962
                        .ConfigureAwait(false);
5✔
963
                return new(_timeProvider.GetUtcNow(), counts, recurring, servers)
5✔
964
                {
5✔
965
                        Capabilities = this.GetCapabilities(),
5✔
966
                };
5✔
967
        }
4✔
968

969
        /// <inheritdoc />
970
        public async ValueTask<IReadOnlyList<JobRecord>> QueryJobsAsync(JobQuery query, CancellationToken cancellationToken = default)
971
        {
972
                ArgumentNullException.ThrowIfNull(query);
5✔
973
                ArgumentOutOfRangeException.ThrowIfNegative(query.Skip);
5✔
974
                ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(query.Take, 0);
5✔
975
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
976
                var jobs = context.Set<ImmediateJobEntity>().AsNoTracking();
5✔
977
                if (query.Id is { } id)
5✔
978
                        jobs = jobs.Where(job => job.Id == id);
5✔
979
                if (query.State is { } state)
5✔
980
                        jobs = jobs.Where(job => job.State == state);
4✔
981
                if (!string.IsNullOrWhiteSpace(query.QueueName))
5✔
982
                        jobs = jobs.Where(job => job.QueueName == query.QueueName);
×
983
                if (!string.IsNullOrWhiteSpace(query.JobName))
5✔
984
                        jobs = jobs.Where(job => job.JobName == query.JobName);
×
985
                if (!string.IsNullOrWhiteSpace(query.Search))
5✔
986
                {
987
                        var search = query.Search.ToUpperInvariant();
×
988
                        // The parameterless form is intentionally used because relational providers translate it to SQL.
989
#pragma warning disable CA1304, CA1311, CA1862, MA0011
990
                        jobs = jobs.Where(job => job.JobName.ToUpper().Contains(search));
×
991
#pragma warning restore CA1304, CA1311, CA1862, MA0011
992
                }
993

994
                var entities = await jobs.OrderByDescending(job => job.CreatedAt)
5✔
995
                        .ThenBy(job => job.Id)
5✔
996
                        .Skip(query.Skip)
5✔
997
                        .Take(query.Take)
5✔
998
                        .ToListAsync(cancellationToken)
5✔
999
                        .ConfigureAwait(false);
5✔
1000
                return [.. entities.Select(ToRecord)];
5✔
1001
        }
4✔
1002

1003
        /// <inheritdoc />
1004
        public async ValueTask<BatchStatus?> GetBatchStatusAsync(
1005
                string batchId,
1006
                CancellationToken cancellationToken = default
1007
        )
1008
        {
1009
                ArgumentException.ThrowIfNullOrWhiteSpace(batchId);
5✔
1010
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1011
                var batch = await context.Set<ImmediateJobBatchEntity>()
5✔
1012
                        .AsNoTracking()
5✔
1013
                        .SingleOrDefaultAsync(item => item.Id == batchId, cancellationToken)
5✔
1014
                        .ConfigureAwait(false);
5✔
1015
                return batch is null ? null : ToStatus(batch);
5✔
1016
        }
4✔
1017

1018
        /// <inheritdoc />
1019
        public async ValueTask<IReadOnlyList<JobContinuationEdge>> GetIncomingEdgesAsync(
1020
                IReadOnlyCollection<string> childJobIds,
1021
                CancellationToken cancellationToken = default
1022
        )
1023
        {
1024
                ArgumentNullException.ThrowIfNull(childJobIds);
5✔
1025
                foreach (var childJobId in childJobIds)
5✔
1026
                        ArgumentException.ThrowIfNullOrWhiteSpace(childJobId);
5✔
1027
                if (childJobIds.Count == 0)
5✔
1028
                        return [];
5✔
1029

1030
                var ids = childJobIds.Distinct(StringComparer.Ordinal).ToArray();
5✔
1031
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1032
                var edges = await context.Set<ImmediateJobContinuationEntity>()
5✔
1033
                        .AsNoTracking()
5✔
1034
                        .Where(edge => ids.Contains(edge.ChildJobId))
5✔
1035
                        .OrderBy(edge => edge.ChildJobId)
5✔
1036
                        .ThenBy(edge => edge.ParentKind)
5✔
1037
                        .ThenBy(edge => edge.ParentId)
5✔
1038
                        .ToListAsync(cancellationToken)
5✔
1039
                        .ConfigureAwait(false);
5✔
1040
                return [.. edges.Select(ToContinuationEdge)];
5✔
1041
        }
4✔
1042

1043
        /// <inheritdoc />
1044
        public async ValueTask<IReadOnlyList<BatchStatus>> QueryBatchesAsync(
1045
                JobBatchQuery query,
1046
                CancellationToken cancellationToken = default
1047
        )
1048
        {
1049
                ArgumentNullException.ThrowIfNull(query);
×
1050
                ArgumentOutOfRangeException.ThrowIfNegative(query.Skip);
×
1051
                ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(query.Take, 0);
×
1052
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
×
1053
                var batches = context.Set<ImmediateJobBatchEntity>().AsNoTracking();
×
1054
                if (query.State is { } state)
×
1055
                        batches = batches.Where(batch => batch.State == state);
×
1056
                var entities = await batches.OrderByDescending(batch => batch.CreatedAt)
×
1057
                        .ThenBy(batch => batch.Id)
×
1058
                        .Skip(query.Skip)
×
1059
                        .Take(query.Take)
×
1060
                        .ToListAsync(cancellationToken)
×
1061
                        .ConfigureAwait(false);
×
1062
                return [.. entities.Select(ToStatus)];
×
1063
        }
1064

1065
        /// <inheritdoc />
1066
        public async ValueTask<IReadOnlyList<BatchMemberStatus>> QueryBatchMembersAsync(
1067
                string batchId,
1068
                BatchMemberQuery query,
1069
                CancellationToken cancellationToken = default
1070
        )
1071
        {
1072
                ArgumentException.ThrowIfNullOrWhiteSpace(batchId);
4✔
1073
                ArgumentNullException.ThrowIfNull(query);
4✔
1074
                ArgumentOutOfRangeException.ThrowIfNegative(query.Skip);
4✔
1075
                ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(query.Take, 0);
4✔
1076
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
4✔
1077
                var jobs = context.Set<ImmediateJobEntity>()
4✔
1078
                        .AsNoTracking()
4✔
1079
                        .Where(job => job.BatchId == batchId);
4✔
1080
                if (query.State is { } state)
4✔
1081
                        jobs = jobs.Where(job => job.State == state);
×
1082
                return await jobs.OrderBy(job => job.CreatedAt)
4✔
1083
                        .ThenBy(job => job.Id)
4✔
1084
                        .Skip(query.Skip)
4✔
1085
                        .Take(query.Take)
4✔
1086
                        .Select(job => new BatchMemberStatus(
4✔
1087
                                job.Id,
4✔
1088
                                job.JobName,
4✔
1089
                                job.QueueName,
4✔
1090
                                job.State,
4✔
1091
                                job.Attempt,
4✔
1092
                                job.CreatedAt,
4✔
1093
                                job.CompletedAt,
4✔
1094
                                job.LastError
4✔
1095
                        ))
4✔
1096
                        .ToListAsync(cancellationToken)
4✔
1097
                        .ConfigureAwait(false);
4✔
1098
        }
3✔
1099

1100
        /// <inheritdoc />
1101
        public async ValueTask<BatchGraph?> GetBatchGraphAsync(
1102
                string batchId,
1103
                CancellationToken cancellationToken = default
1104
        )
1105
        {
1106
                ArgumentException.ThrowIfNullOrWhiteSpace(batchId);
4✔
1107
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
4✔
1108
                if (!await context.Set<ImmediateJobBatchEntity>()
4✔
1109
                        .AnyAsync(batch => batch.Id == batchId, cancellationToken)
4✔
1110
                        .ConfigureAwait(false))
4✔
1111
                {
1112
                        return null;
4✔
1113
                }
1114

1115
                var jobs = await context.Set<ImmediateJobEntity>()
×
1116
                        .AsNoTracking()
×
1117
                        .Where(job => job.BatchId == batchId)
×
1118
                        .OrderBy(job => job.CreatedAt)
×
1119
                        .ThenBy(job => job.Id)
×
1120
                        .Select(job => new BatchGraphNode(job.Id, job.JobName, job.State))
×
1121
                        .ToListAsync(cancellationToken)
×
1122
                        .ConfigureAwait(false);
×
1123
                var ids = jobs.Select(static job => job.JobId).ToArray();
×
1124
                var edges = ids.Length == 0
×
1125
                        ? []
×
1126
                        : await context.Set<ImmediateJobContinuationEntity>()
×
1127
                                .AsNoTracking()
×
1128
                                .Where(edge => ids.Contains(edge.ChildJobId))
×
1129
                                .OrderBy(edge => edge.ChildJobId)
×
1130
                                .ThenBy(edge => edge.ParentKind)
×
1131
                                .ThenBy(edge => edge.ParentId)
×
1132
                                .ToListAsync(cancellationToken)
×
1133
                                .ConfigureAwait(false);
×
1134
                return new(batchId, jobs, [.. edges.Select(ToGraphEdge)]);
4✔
1135
        }
3✔
1136

1137
        /// <inheritdoc />
1138
        public async ValueTask<JobStatus?> GetJobStatusAsync(
1139
                string jobId,
1140
                CancellationToken cancellationToken = default
1141
        )
1142
        {
1143
                ArgumentException.ThrowIfNullOrWhiteSpace(jobId);
5✔
1144
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1145
                var job = await context.Set<ImmediateJobEntity>()
5✔
1146
                        .AsNoTracking()
5✔
1147
                        .SingleOrDefaultAsync(item => item.Id == jobId, cancellationToken)
5✔
1148
                        .ConfigureAwait(false);
5✔
1149
                if (job is null)
5✔
1150
                        return null;
5✔
1151
                var edges = await context.Set<ImmediateJobContinuationEntity>()
5✔
1152
                        .AsNoTracking()
5✔
1153
                        .Where(edge => edge.ChildJobId == jobId)
5✔
1154
                        .OrderBy(edge => edge.ParentKind)
5✔
1155
                        .ThenBy(edge => edge.ParentId)
5✔
1156
                        .ToListAsync(cancellationToken)
5✔
1157
                        .ConfigureAwait(false);
5✔
1158
                return new(
5✔
1159
                        job.Id,
5✔
1160
                        job.JobName,
5✔
1161
                        job.QueueName,
5✔
1162
                        job.State,
5✔
1163
                        job.Attempt,
5✔
1164
                        MaxAttempts: null,
5✔
1165
                        job.CreatedAt,
5✔
1166
                        job.DueAt,
5✔
1167
                        job.CompletedAt,
5✔
1168
                        job.LastError,
5✔
1169
                        job.BatchId,
5✔
1170
                        [.. edges.Select(ToGraphEdge)]
5✔
1171
                );
5✔
1172
        }
4✔
1173

1174
        /// <inheritdoc />
1175
        public ValueTask CancelBatchAsync(string batchId, CancellationToken cancellationToken = default)
1176
        {
1177
                ArgumentException.ThrowIfNullOrWhiteSpace(batchId);
5✔
1178
                return ExecuteWithStrategyAsync(
5✔
1179
                        operationCancellationToken => CancelBatchCoreAsync(batchId, operationCancellationToken),
5✔
1180
                        cancellationToken
5✔
1181
                );
5✔
1182
        }
1183

1184
        private async Task CancelBatchCoreAsync(string batchId, CancellationToken cancellationToken)
1185
        {
1186
                var now = _timeProvider.GetUtcNow();
5✔
1187
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1188
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
5✔
1189
                var batch = await context.Set<ImmediateJobBatchEntity>()
5✔
1190
                        .SingleOrDefaultAsync(item => item.Id == batchId, cancellationToken)
5✔
1191
                        .ConfigureAwait(false)
5✔
1192
                        ?? throw new KeyNotFoundException($"Batch '{batchId}' was not found.");
5✔
1193
                if (batch.State != BatchState.Executing)
5✔
1194
                        throw new ImmediateJobException("Only an executing batch can be cancelled.");
×
1195

1196
                var jobs = await context.Set<ImmediateJobEntity>()
5✔
1197
                        .Where(job => job.BatchId == batchId)
5✔
1198
                        .ToListAsync(cancellationToken)
5✔
1199
                        .ConfigureAwait(false);
5✔
1200
                var jobsToCancel = jobs.Where(job => !IsTerminal(job.State)).ToArray();
5✔
1201
                foreach (var job in jobsToCancel)
5✔
1202
                {
1203
                        job.State = JobState.Cancelled;
5✔
1204
                        job.CompletedAt = now;
5✔
1205
                        job.WorkerId = null;
5✔
1206
                        job.LeaseExpiresAt = null;
5✔
1207
                        job.ConcurrencyStamp = Guid.NewGuid();
5✔
1208
                }
1209

1210
                foreach (var job in jobsToCancel)
5✔
1211
                        await PropagateTerminalAsync(context, job, now, cancellationToken).ConfigureAwait(false);
5✔
1212

1213
                var terminalGroups = GetTerminalFairQueueGroups(context);
5✔
1214
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
5✔
1215
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
5✔
1216
                foreach (var (queueName, groupId) in terminalGroups)
5✔
1217
                {
1218
                        await TryRemoveFairQueueCursorAsync(queueName, groupId, CancellationToken.None).ConfigureAwait(false);
×
1219
                }
1220
        }
5✔
1221

1222
        /// <inheritdoc />
1223
        public ValueTask DeleteBatchAsync(string batchId, CancellationToken cancellationToken = default)
1224
        {
1225
                ArgumentException.ThrowIfNullOrWhiteSpace(batchId);
5✔
1226
                return ExecuteWithStrategyAsync(
5✔
1227
                        operationCancellationToken => DeleteBatchCoreAsync(batchId, operationCancellationToken),
5✔
1228
                        cancellationToken
5✔
1229
                );
5✔
1230
        }
1231

1232
        private async Task DeleteBatchCoreAsync(string batchId, CancellationToken cancellationToken)
1233
        {
1234
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1235
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
5✔
1236
                var batch = await context.Set<ImmediateJobBatchEntity>()
5✔
1237
                        .SingleOrDefaultAsync(item => item.Id == batchId, cancellationToken)
5✔
1238
                        .ConfigureAwait(false)
5✔
1239
                        ?? throw new KeyNotFoundException($"Batch '{batchId}' was not found.");
5✔
1240
                if (batch.State == BatchState.Executing)
4✔
1241
                        throw new ImmediateJobException("Only a terminal batch can be deleted.");
×
1242

1243
                var jobs = await context.Set<ImmediateJobEntity>()
4✔
1244
                        .Where(job => job.BatchId == batchId)
4✔
1245
                        .ToListAsync(cancellationToken)
4✔
1246
                        .ConfigureAwait(false);
4✔
1247
                var jobIds = jobs.Select(static job => job.Id).ToArray();
4✔
1248
                var edges = await context.Set<ImmediateJobContinuationEntity>()
4✔
1249
                        .Where(edge =>
4✔
1250
                                jobIds.Contains(edge.ChildJobId)
4✔
1251
                                || (edge.ParentKind == ContinuationParentKind.Job && jobIds.Contains(edge.ParentId))
4✔
1252
                                || (edge.ParentKind == ContinuationParentKind.Batch && edge.ParentId == batchId))
4✔
1253
                        .ToListAsync(cancellationToken)
4✔
1254
                        .ConfigureAwait(false);
4✔
1255
                context.RemoveRange(edges);
4✔
1256
                context.RemoveRange(jobs);
4✔
1257
                _ = context.Remove(batch);
4✔
1258
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
4✔
1259
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
4✔
1260
        }
4✔
1261

1262
        /// <inheritdoc />
1263
        public ValueTask RetryAsync(string jobId, CancellationToken cancellationToken = default)
1264
        {
1265
                ArgumentException.ThrowIfNullOrWhiteSpace(jobId);
5✔
1266
                return ExecuteWithStrategyAsync(
5✔
1267
                        operationCancellationToken => RetryCoreAsync(jobId, operationCancellationToken),
5✔
1268
                        cancellationToken
5✔
1269
                );
5✔
1270
        }
1271

1272
        private async Task RetryCoreAsync(string jobId, CancellationToken cancellationToken)
1273
        {
1274
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1275
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
5✔
1276
                var job = await context.Set<ImmediateJobEntity>()
5✔
1277
                        .SingleOrDefaultAsync(item => item.Id == jobId && item.State == JobState.Failed, cancellationToken)
5✔
1278
                        .ConfigureAwait(false);
5✔
1279
                if (job is null)
5✔
1280
                {
1281
                        if (await context.Set<ImmediateJobEntity>()
5✔
1282
                                .AnyAsync(item => item.Id == jobId, cancellationToken)
5✔
1283
                                .ConfigureAwait(false))
5✔
1284
                        {
1285
                                throw new ImmediateJobException("Only failed jobs can be retried.");
4✔
1286
                        }
1287

1288
                        throw new KeyNotFoundException($"Job '{jobId}' was not found.");
5✔
1289
                }
1290

1291
                if (job.BatchId is { } batchId)
1✔
1292
                {
1293
                        var batch = await context.Set<ImmediateJobBatchEntity>()
×
1294
                                .SingleAsync(item => item.Id == batchId, cancellationToken)
×
1295
                                .ConfigureAwait(false);
×
1296
                        batch.PendingCount++;
×
1297
                        batch.FailedCount = Math.Max(0, batch.FailedCount - 1);
×
1298
                        batch.State = BatchState.Executing;
×
1299
                        batch.CompletedAt = null;
×
1300
                        batch.ConcurrencyStamp = Guid.NewGuid();
×
1301
                }
1302

1303
                job.State = JobState.Pending;
1✔
1304
                job.DueAt = _timeProvider.GetUtcNow();
1✔
1305
                job.WorkerId = null;
1✔
1306
                job.LeaseExpiresAt = null;
1✔
1307
                job.CompletedAt = null;
1✔
1308
                job.LastError = null;
1✔
1309
                job.ConcurrencyStamp = Guid.NewGuid();
1✔
1310
                try
1311
                {
1312
                        _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
1✔
1313
                }
1✔
1314
                catch (DbUpdateConcurrencyException)
1315
                {
1316
                        if (!await context.Set<ImmediateJobEntity>()
×
1317
                                .AsNoTracking()
×
1318
                                .AnyAsync(item => item.Id == jobId, cancellationToken)
×
1319
                                .ConfigureAwait(false))
×
1320
                        {
1321
                                throw new KeyNotFoundException($"Job '{jobId}' was not found.");
×
1322
                        }
1323

1324
                        throw new ImmediateJobException("Only failed jobs can be retried.");
×
1325
                }
1326

1327
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
1✔
1328
        }
1✔
1329

1330
        /// <inheritdoc />
1331
        public ValueTask DeleteAsync(string jobId, CancellationToken cancellationToken = default)
1332
        {
1333
                ArgumentException.ThrowIfNullOrWhiteSpace(jobId);
5✔
1334
                return ExecuteWithStrategyAsync(
5✔
1335
                        operationCancellationToken => DeleteCoreAsync(jobId, operationCancellationToken),
5✔
1336
                        cancellationToken
5✔
1337
                );
5✔
1338
        }
1339

1340
        private async Task DeleteCoreAsync(string jobId, CancellationToken cancellationToken)
1341
        {
1342
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1343
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
5✔
1344
                var job = await context.Set<ImmediateJobEntity>()
5✔
1345
                        .AsNoTracking()
5✔
1346
                        .SingleOrDefaultAsync(item => item.Id == jobId
5✔
1347
                                && (item.State == JobState.Succeeded || item.State == JobState.Failed || item.State == JobState.Cancelled || item.State == JobState.Skipped), cancellationToken)
5✔
1348
                        .ConfigureAwait(false);
5✔
1349
                if (job is null)
5✔
1350
                {
1351
                        if (await context.Set<ImmediateJobEntity>()
5✔
1352
                                .AnyAsync(item => item.Id == jobId, cancellationToken)
5✔
1353
                                .ConfigureAwait(false))
5✔
1354
                        {
1355
                                throw new ImmediateJobException("Only terminal jobs can be deleted.");
4✔
1356
                        }
1357

1358
                        throw new KeyNotFoundException($"Job '{jobId}' was not found.");
5✔
1359
                }
1360

1361
                if (job.BatchId is not null)
1✔
1362
                        throw new ImmediateJobException("Batch members are deleted with their batch so the workflow remains coherent.");
×
1363
                _ = await context.Set<ImmediateJobContinuationEntity>()
1✔
1364
                        .Where(edge => edge.ChildJobId == jobId ||
1✔
1365
                                (edge.ParentKind == ContinuationParentKind.Job && edge.ParentId == jobId))
1✔
1366
                        .ExecuteDeleteAsync(cancellationToken)
1✔
1367
                        .ConfigureAwait(false);
1✔
1368
                var removed = await context.Set<ImmediateJobEntity>()
1✔
1369
                        .Where(item => item.Id == jobId &&
1✔
1370
                                (item.State == JobState.Succeeded || item.State == JobState.Failed || item.State == JobState.Cancelled || item.State == JobState.Skipped))
1✔
1371
                        .ExecuteDeleteAsync(cancellationToken)
1✔
1372
                        .ConfigureAwait(false);
1✔
1373
                if (removed == 0)
1✔
1374
                {
1375
                        if (await context.Set<ImmediateJobEntity>()
×
1376
                                .AnyAsync(item => item.Id == jobId, cancellationToken)
×
1377
                                .ConfigureAwait(false))
×
1378
                        {
1379
                                throw new ImmediateJobException("Only terminal jobs can be deleted.");
×
1380
                        }
1381

1382
                        throw new KeyNotFoundException($"Job '{jobId}' was not found.");
×
1383
                }
1384

1385
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
1✔
1386
        }
1✔
1387

1388
        /// <inheritdoc />
1389
        public ValueTask PurgeJobsAsync(
1390
                TimeSpan succeededRetention,
1391
                TimeSpan failedRetention,
1392
                CancellationToken cancellationToken = default
1393
        )
1394
        {
1395
                var now = _timeProvider.GetUtcNow();
4✔
1396
                return ExecuteWithStrategyAsync(
4✔
1397
                        operationCancellationToken => PurgeJobsCoreAsync(
4✔
1398
                                now - succeededRetention,
4✔
1399
                                now - failedRetention,
4✔
1400
                                operationCancellationToken
4✔
1401
                        ),
4✔
1402
                        cancellationToken
4✔
1403
                );
4✔
1404
        }
1405

1406
        /// <inheritdoc />
1407
        public ValueTask PurgeBatchesAsync(
1408
                TimeSpan batchSucceededRetention,
1409
                TimeSpan batchFailedRetention,
1410
                CancellationToken cancellationToken = default
1411
        )
1412
        {
1413
                var now = _timeProvider.GetUtcNow();
4✔
1414
                return ExecuteWithStrategyAsync(
4✔
1415
                        operationCancellationToken => PurgeBatchesCoreAsync(
4✔
1416
                                now - batchSucceededRetention,
4✔
1417
                                now - batchFailedRetention,
4✔
1418
                                operationCancellationToken
4✔
1419
                        ),
4✔
1420
                        cancellationToken
4✔
1421
                );
4✔
1422
        }
1423

1424
        private async Task PurgeJobsCoreAsync(
1425
                DateTimeOffset succeededBefore,
1426
                DateTimeOffset failedBefore,
1427
                CancellationToken cancellationToken
1428
        )
1429
        {
1430
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
4✔
1431
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
4✔
1432
                var jobs = await context.Set<ImmediateJobEntity>()
4✔
1433
                        .Where(job => job.BatchId == null
4✔
1434
                                && ((job.State == JobState.Succeeded && job.CompletedAt < succeededBefore)
4✔
1435
                                || ((job.State == JobState.Failed || job.State == JobState.Cancelled || job.State == JobState.Skipped) && job.CompletedAt < failedBefore))
4✔
1436
                        )
4✔
1437
                        .ToListAsync(cancellationToken)
4✔
1438
                        .ConfigureAwait(false);
4✔
1439
                if (jobs.Count != 0)
4✔
1440
                {
1441
                        var jobIds = jobs.Select(static job => job.Id).ToArray();
×
1442
                        var edges = await context.Set<ImmediateJobContinuationEntity>()
×
1443
                                .Where(edge =>
×
1444
                                        jobIds.Contains(edge.ChildJobId)
×
1445
                                        || (jobIds.Contains(edge.ParentId) && edge.ParentKind == ContinuationParentKind.Job)
×
1446
                                )
×
1447
                                .ToListAsync(cancellationToken)
×
1448
                                .ConfigureAwait(false);
×
1449
                        context.RemoveRange(edges);
×
1450
                }
1451

1452
                context.RemoveRange(jobs);
4✔
1453
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
4✔
1454
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
4✔
1455
        }
4✔
1456

1457
        private async Task PurgeBatchesCoreAsync(
1458
                DateTimeOffset batchSucceededBefore,
1459
                DateTimeOffset batchFailedBefore,
1460
                CancellationToken cancellationToken
1461
        )
1462
        {
1463
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
4✔
1464
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
4✔
1465
                var batches = await context.Set<ImmediateJobBatchEntity>()
4✔
1466
                        .Where(batch => (batch.State == BatchState.Succeeded && batch.CompletedAt < batchSucceededBefore)
4✔
1467
                                || ((batch.State == BatchState.Failed || batch.State == BatchState.Cancelled)
4✔
1468
                                        && batch.CompletedAt < batchFailedBefore))
4✔
1469
                        .ToListAsync(cancellationToken)
4✔
1470
                        .ConfigureAwait(false);
4✔
1471
                if (batches.Count != 0)
4✔
1472
                {
1473
                        var batchIds = batches.Select(static batch => batch.Id).ToArray();
×
1474
                        var memberIds = await context.Set<ImmediateJobEntity>()
×
1475
                                .Where(job => job.BatchId != null && batchIds.Contains(job.BatchId))
×
1476
                                .Select(job => job.Id)
×
1477
                                .ToListAsync(cancellationToken)
×
1478
                                .ConfigureAwait(false);
×
1479
                        var edges = await context.Set<ImmediateJobContinuationEntity>()
×
1480
                                .Where(edge =>
×
1481
                                        (batchIds.Contains(edge.ParentId) && edge.ParentKind == ContinuationParentKind.Batch)
×
1482
                                        || memberIds.Contains(edge.ChildJobId)
×
1483
                                        || (memberIds.Contains(edge.ParentId) && edge.ParentKind == ContinuationParentKind.Job)
×
1484
                                )
×
1485
                                .ToListAsync(cancellationToken)
×
1486
                                .ConfigureAwait(false);
×
1487
                        context.RemoveRange(edges);
×
1488
                        context.RemoveRange(batches);
×
1489
                }
1490

1491
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
4✔
1492
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
4✔
1493
        }
4✔
1494

1495
        /// <inheritdoc />
1496
        public async ValueTask HeartbeatAsync(JobServerSnapshot server, CancellationToken cancellationToken = default)
1497
        {
1498
                ArgumentNullException.ThrowIfNull(server);
1✔
1499
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
1✔
1500
                var cutoff = _timeProvider.GetUtcNow() - TimeSpan.FromMinutes(2);
1✔
1501
                _ = await context.Set<ImmediateJobServerEntity>()
1✔
1502
                        .Where(item => item.LastHeartbeat < cutoff)
1✔
1503
                        .ExecuteDeleteAsync(cancellationToken)
1✔
1504
                        .ConfigureAwait(false);
1✔
1505
                var entity = await context.Set<ImmediateJobServerEntity>().FindAsync([server.WorkerId], cancellationToken).ConfigureAwait(false);
1✔
1506
                if (entity is null)
1✔
1507
                {
1508
                        _ = context.Add(new ImmediateJobServerEntity
1✔
1509
                        {
1✔
1510
                                WorkerId = server.WorkerId,
1✔
1511
                                LastHeartbeat = server.LastHeartbeat,
1✔
1512
                                ActiveWorkers = server.ActiveWorkers,
1✔
1513
                                MaxWorkers = server.MaxWorkers,
1✔
1514
                        });
1✔
1515
                }
1516
                else
1517
                {
1518
                        entity.LastHeartbeat = server.LastHeartbeat;
×
1519
                        entity.ActiveWorkers = server.ActiveWorkers;
×
1520
                        entity.MaxWorkers = server.MaxWorkers;
×
1521
                }
1522

1523
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
1✔
1524
        }
1✔
1525

1526
        /// <inheritdoc />
1527
        public async ValueTask<bool> IsHealthyAsync(CancellationToken cancellationToken = default)
1528
        {
1529
                try
1530
                {
1531
                        await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
×
1532
                        return await context.Database.CanConnectAsync(cancellationToken).ConfigureAwait(false);
×
1533
                }
×
1534
                catch (Exception exception) when (exception is DbException or InvalidOperationException)
×
1535
                {
1536
                        return false;
×
1537
                }
1538
        }
×
1539

1540
        private ValueTask MutateOwnedWithDependenciesAsync(
1541
                string jobId,
1542
                string workerId,
1543
                string? error,
1544
                DateTimeOffset? nextRetryAt,
1545
                bool succeeded,
1546
                IReadOnlyList<JobContinuationAddition> additions,
1547
                CancellationToken cancellationToken
1548
        ) => RetryConcurrencyAsync(
5✔
1549
                operationCancellationToken => MutateOwnedCoreAsync(
5✔
1550
                        jobId,
5✔
1551
                        workerId,
5✔
1552
                        error,
5✔
1553
                        nextRetryAt,
5✔
1554
                        succeeded,
5✔
1555
                        additions,
5✔
1556
                        operationCancellationToken
5✔
1557
                ),
5✔
1558
                cancellationToken
5✔
1559
        );
5✔
1560

1561
        private async ValueTask RetryConcurrencyAsync(
1562
                Func<CancellationToken, Task> operation,
1563
                CancellationToken cancellationToken
1564
        )
1565
        {
1566
                for (var attempt = 0; attempt < MaxConcurrencyAttempts; attempt++)
5✔
1567
                {
1568
                        try
1569
                        {
1570
                                await ExecuteWithStrategyAsync(operation, cancellationToken).ConfigureAwait(false);
5✔
1571
                                return;
5✔
1572
                        }
1573
                        catch (DbUpdateConcurrencyException) when (attempt + 1 < MaxConcurrencyAttempts)
5✔
1574
                        {
1575
                                // The transaction rolled back, so the next attempt re-evaluates the graph from durable state.
1576
                        }
1✔
1577
                }
1578
        }
5✔
1579

1580
        private async ValueTask ExecuteWithStrategyAsync(
1581
                Func<CancellationToken, Task> operation,
1582
                CancellationToken cancellationToken
1583
        )
1584
        {
1585
                await using var strategyContext = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1586
                var strategy = strategyContext.Database.CreateExecutionStrategy();
5✔
1587
                await strategy.ExecuteAsync(operation, cancellationToken).ConfigureAwait(false);
5✔
1588
        }
5✔
1589

1590
        private async ValueTask MutateOwnedAsync(
1591
                string jobId,
1592
                string workerId,
1593
                Action<ImmediateJobEntity> mutate,
1594
                CancellationToken cancellationToken
1595
        )
1596
        {
1597
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
1✔
1598
                var job = await context.Set<ImmediateJobEntity>()
1✔
1599
                        .SingleOrDefaultAsync(item => item.Id == jobId && item.State == JobState.Active && item.WorkerId == workerId, cancellationToken)
1✔
1600
                        .ConfigureAwait(false);
1✔
1601
                if (job is null)
1✔
1602
                        return;
1603
                mutate(job);
1✔
1604
                job.ConcurrencyStamp = Guid.NewGuid();
1✔
1605
                try
1606
                {
1607
                        _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
1✔
1608
                }
1✔
1609
                catch (DbUpdateConcurrencyException)
×
1610
                {
1611
                        // A stale worker must not update a lease that has been reclaimed.
1612
                }
1✔
1613
        }
1✔
1614

1615
        private async Task MutateOwnedCoreAsync(
1616
                string jobId,
1617
                string workerId,
1618
                string? error,
1619
                DateTimeOffset? nextRetryAt,
1620
                bool succeeded,
1621
                IReadOnlyList<JobContinuationAddition> additions,
1622
                CancellationToken cancellationToken
1623
        )
1624
        {
1625
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1626
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
5✔
1627
                var job = await context.Set<ImmediateJobEntity>()
5✔
1628
                        .SingleOrDefaultAsync(item => item.Id == jobId && item.State == JobState.Active && item.WorkerId == workerId, cancellationToken)
5✔
1629
                        .ConfigureAwait(false);
5✔
1630
                if (job is null)
5✔
1631
                        throw new ImmediateJobException($"Worker '{workerId}' does not own active job '{jobId}'.");
1✔
1632

1633
                var now = _timeProvider.GetUtcNow();
5✔
1634
                job.WorkerId = null;
5✔
1635
                job.LeaseExpiresAt = null;
5✔
1636
                job.LastError = error;
5✔
1637
                job.ConcurrencyStamp = Guid.NewGuid();
5✔
1638
                if (!succeeded && nextRetryAt is { } retryAt)
5✔
1639
                {
1640
                        job.State = retryAt <= now ? JobState.Pending : JobState.Scheduled;
×
1641
                        job.DueAt = retryAt;
×
1642
                        job.CompletedAt = null;
×
1643
                        _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
×
1644
                        await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
×
1645
                        return;
×
1646
                }
1647

1648
                if (succeeded && additions.Count != 0)
5✔
1649
                {
1650
                        await FlushContinuationAdditionsAsync(context, job, additions, cancellationToken).ConfigureAwait(false);
5✔
1651
                        _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
×
1652
                }
1653

1654
                job.State = succeeded ? JobState.Succeeded : JobState.Failed;
5✔
1655
                job.CompletedAt = now;
5✔
1656
                await PropagateTerminalAsync(context, job, now, cancellationToken).ConfigureAwait(false);
5✔
1657
                var terminalGroups = GetTerminalFairQueueGroups(context);
5✔
1658
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
5✔
1659
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
5✔
1660
                foreach (var (queueName, groupId) in terminalGroups)
5✔
1661
                        await TryRemoveFairQueueCursorAsync(queueName, groupId, CancellationToken.None).ConfigureAwait(false);
5✔
1662
        }
5✔
1663

1664
        private static (string QueueName, string GroupId)[] GetTerminalFairQueueGroups(TContext context) =>
1665
                [
5✔
1666
                        .. context.ChangeTracker
5✔
1667
                                .Entries<ImmediateJobEntity>()
5✔
1668
                                .Select(static entry => entry.Entity)
5✔
1669
                                .Where(static job => job.GroupId is not null && IsTerminal(job.State))
5✔
1670
                                .Select(static job => (job.QueueName, GroupId: job.GroupId!))
5✔
1671
                                .Distinct(),
5✔
1672
                ];
5✔
1673

1674
        private async ValueTask TryRemoveFairQueueCursorAsync(
1675
                string queueName,
1676
                string groupId,
1677
                CancellationToken cancellationToken
1678
        )
1679
        {
1680
                try
1681
                {
1682
                        await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1683
                        if (await HasLiveGroupJobsAsync(context, queueName, groupId, cancellationToken).ConfigureAwait(false))
5✔
1684
                        {
1685
                                return;
1686
                        }
1687

1688
                        var cursor = await context.Set<ImmediateFairQueueGroupEntity>()
4✔
1689
                                .SingleOrDefaultAsync(
4✔
1690
                                        group => group.QueueName == queueName && group.GroupId == groupId,
4✔
1691
                                        cancellationToken
4✔
1692
                                )
4✔
1693
                                .ConfigureAwait(false);
4✔
1694
                        if (cursor is null)
4✔
1695
                                return;
1696

1697
                        _ = context.Remove(cursor);
4✔
1698
                        _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
4✔
1699
                }
4✔
1700
                catch (Exception exception) when (
×
1701
                        !cancellationToken.IsCancellationRequested
×
1702
                        && exception is DbException or DbUpdateException
×
1703
                )
×
1704
                {
1705
                        // Cleanup is best-effort metadata maintenance and must not invalidate a committed transition.
1706
                }
×
1707
        }
5✔
1708

1709
        private static Task<bool> HasLiveGroupJobsAsync(
1710
                TContext context,
1711
                string queueName,
1712
                string groupId,
1713
                CancellationToken cancellationToken
1714
        ) => context.Set<ImmediateJobEntity>().AnyAsync(
5✔
1715
                job => job.QueueName == queueName
5✔
1716
                        && job.GroupId == groupId
5✔
1717
                        && (job.State == JobState.Pending
5✔
1718
                                || job.State == JobState.Scheduled
5✔
1719
                                || job.State == JobState.Active),
5✔
1720
                cancellationToken
5✔
1721
        );
5✔
1722

1723
        private async Task AddBatchJobCoreAsync(
1724
                string currentJobId,
1725
                JobRecord record,
1726
                ContinuationOptions options,
1727
                CancellationToken cancellationToken
1728
        )
1729
        {
1730
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1731
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
5✔
1732
                var current = await context.Set<ImmediateJobEntity>()
5✔
1733
                        .SingleOrDefaultAsync(job => job.Id == currentJobId && job.State == JobState.Active, cancellationToken)
5✔
1734
                        .ConfigureAwait(false)
5✔
1735
                        ?? throw new ImmediateJobException($"The current active job '{currentJobId}' was not found.");
5✔
1736
                if (current.BatchId is not { } batchId)
5✔
1737
                        throw new ImmediateJobException("The current job does not belong to a batch.");
×
1738
                if (options is not (ContinuationOptions.BesideContinuations or ContinuationOptions.BeforeContinuations))
5✔
1739
                        throw new ArgumentOutOfRangeException(nameof(options));
×
1740
                if (!string.Equals(record.BatchId, batchId, StringComparison.Ordinal))
5✔
1741
                        throw new ImmediateJobException("The new job must belong to the current job's batch.");
5✔
1742
                if (record.State is JobState.Active or JobState.AwaitingContinuation || IsTerminal(record.State))
×
1743
                        throw new ImmediateJobException($"Concurrent batch member '{record.Id}' has invalid state '{record.State}'.");
×
1744

1745
                var batch = await context.Set<ImmediateJobBatchEntity>()
×
1746
                        .SingleAsync(item => item.Id == batchId && item.State == BatchState.Executing, cancellationToken)
×
1747
                        .ConfigureAwait(false);
×
1748
                var job = ToEntity(record);
×
1749
                _ = context.Add(job);
×
1750
                batch.TotalJobs++;
×
1751
                batch.PendingCount++;
×
1752
                batch.ConcurrencyStamp = Guid.NewGuid();
×
1753

1754
                if (options == ContinuationOptions.BeforeContinuations)
×
1755
                {
1756
                        var waiters = await GetActiveWaitersAsync(context, currentJobId, cancellationToken).ConfigureAwait(false);
×
1757
                        foreach (var waiter in waiters)
×
1758
                        {
1759
                                _ = context.Add(new ImmediateJobContinuationEntity
×
1760
                                {
×
1761
                                        ChildJobId = waiter.Id,
×
1762
                                        ParentKind = ContinuationParentKind.Job,
×
1763
                                        ParentId = job.Id,
×
1764
                                        Trigger = ContinuationTrigger.Success,
×
1765
                                });
×
1766
                                waiter.RemainingDependencies++;
×
1767
                                waiter.ConcurrencyStamp = Guid.NewGuid();
×
1768
                        }
1769
                }
1770

1771
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
×
1772
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
×
1773
        }
×
1774

1775
        private static async Task FlushContinuationAdditionsAsync(
1776
                TContext context,
1777
                ImmediateJobEntity current,
1778
                IReadOnlyList<JobContinuationAddition> additions,
1779
                CancellationToken cancellationToken
1780
        )
1781
        {
1782
                var ids = new HashSet<string>(StringComparer.Ordinal);
5✔
1783
                var trackedAdditions = 0;
5✔
1784
                foreach (var addition in additions)
5✔
1785
                {
1786
                        ArgumentNullException.ThrowIfNull(addition);
5✔
1787
                        ArgumentNullException.ThrowIfNull(addition.Job);
5✔
1788
                        if (!ids.Add(addition.Job.Id))
5✔
1789
                                throw new ImmediateJobException("Buffered continuations contain duplicate job identifiers.");
×
1790
                        if (!Enum.IsDefined(addition.Trigger))
5✔
1791
                                throw new ArgumentOutOfRangeException(nameof(additions), "Unknown continuation trigger.");
4✔
1792
                        if (addition.Job.State is not (JobState.Pending or JobState.Scheduled))
5✔
1793
                                throw new ImmediateJobException($"Dynamic continuation '{addition.Job.Id}' has invalid state '{addition.Job.State}'.");
×
1794

1795
                        if (addition.Options == ContinuationOptions.Detached)
5✔
1796
                        {
1797
                                if (addition.Job.BatchId is not null)
5✔
1798
                                        throw new ImmediateJobException("A detached continuation cannot belong to a batch.");
5✔
1799
                        }
1800
                        else if (addition.Options is ContinuationOptions.BesideContinuations or ContinuationOptions.BeforeContinuations)
5✔
1801
                        {
1802
                                if (current.BatchId is null || !string.Equals(addition.Job.BatchId, current.BatchId, StringComparison.Ordinal))
5✔
1803
                                        throw new ImmediateJobException("A batch-tracked continuation must belong to the current job's batch.");
5✔
1804
                                trackedAdditions++;
×
1805
                        }
1806
                        else
1807
                        {
1808
                                throw new ArgumentOutOfRangeException(nameof(additions), "Unknown continuation option.");
4✔
1809
                        }
1810
                }
1811

1812
                var waiters = additions.Any(static addition => addition.Options == ContinuationOptions.BeforeContinuations)
×
1813
                        ? await GetActiveWaitersAsync(context, current.Id, cancellationToken).ConfigureAwait(false)
×
1814
                        : [];
×
1815
                ImmediateJobBatchEntity? batch = null;
1816
                if (trackedAdditions != 0)
×
1817
                {
1818
                        if (current.BatchId is not { } batchId)
×
1819
                                throw new ImmediateJobException("The current job does not belong to a batch.");
×
1820
                        batch = await context.Set<ImmediateJobBatchEntity>()
×
1821
                                .SingleAsync(item => item.Id == batchId && item.State == BatchState.Executing, cancellationToken)
×
1822
                                .ConfigureAwait(false);
×
1823
                        batch.TotalJobs += trackedAdditions;
×
1824
                        batch.PendingCount += trackedAdditions;
×
1825
                        batch.ConcurrencyStamp = Guid.NewGuid();
×
1826
                }
1827

1828
                foreach (var addition in additions)
×
1829
                {
1830
                        var job = ToEntity(addition.Job with
×
1831
                        {
×
1832
                                State = JobState.AwaitingContinuation,
×
1833
                                RemainingDependencies = 1,
×
1834
                        });
×
1835
                        _ = context.Add(job);
×
1836
                        _ = context.Add(new ImmediateJobContinuationEntity
×
1837
                        {
×
1838
                                ChildJobId = job.Id,
×
1839
                                ParentKind = ContinuationParentKind.Job,
×
1840
                                ParentId = current.Id,
×
1841
                                Trigger = addition.Trigger,
×
1842
                        });
×
1843

1844
                        if (addition.Options != ContinuationOptions.BeforeContinuations)
×
1845
                                continue;
1846
                        foreach (var waiter in waiters)
×
1847
                        {
1848
                                _ = context.Add(new ImmediateJobContinuationEntity
×
1849
                                {
×
1850
                                        ChildJobId = waiter.Id,
×
1851
                                        ParentKind = ContinuationParentKind.Job,
×
1852
                                        ParentId = job.Id,
×
1853
                                        Trigger = ContinuationTrigger.Success,
×
1854
                                });
×
1855
                                waiter.RemainingDependencies++;
×
1856
                                waiter.ConcurrencyStamp = Guid.NewGuid();
×
1857
                        }
1858
                }
1859
        }
×
1860

1861
        private static async Task<List<ImmediateJobEntity>> GetActiveWaitersAsync(
1862
                TContext context,
1863
                string currentJobId,
1864
                CancellationToken cancellationToken
1865
        )
1866
        {
1867
                var waiterIds = await context.Set<ImmediateJobContinuationEntity>()
×
1868
                        .Where(edge => edge.ParentKind == ContinuationParentKind.Job && edge.ParentId == currentJobId)
×
1869
                        .Select(edge => edge.ChildJobId)
×
1870
                        .Distinct()
×
1871
                        .ToArrayAsync(cancellationToken)
×
1872
                        .ConfigureAwait(false);
×
1873
                return waiterIds.Length == 0
×
1874
                        ? []
×
1875
                        : await context.Set<ImmediateJobEntity>()
×
1876
                                .Where(job => waiterIds.Contains(job.Id) && job.State == JobState.AwaitingContinuation)
×
1877
                                .ToListAsync(cancellationToken)
×
1878
                                .ConfigureAwait(false);
×
1879
        }
1880

1881
        private static async Task PropagateTerminalAsync(
1882
                TContext context,
1883
                ImmediateJobEntity terminalJob,
1884
                DateTimeOffset now,
1885
                CancellationToken cancellationToken
1886
        )
1887
        {
1888
                var parents = new Queue<(ContinuationParentKind Kind, string Id, ContinuationParentOutcome Outcome)>();
5✔
1889
                var processed = new HashSet<(ContinuationParentKind Kind, string Id)>();
5✔
1890
                parents.Enqueue((
5✔
1891
                        ContinuationParentKind.Job,
5✔
1892
                        terminalJob.Id,
5✔
1893
                        GetParentOutcome(terminalJob.State)
5✔
1894
                ));
5✔
1895
                await UpdateBatchForTerminalJobAsync(context, terminalJob, now, parents, cancellationToken).ConfigureAwait(false);
5✔
1896

1897
                while (parents.TryDequeue(out var parent))
5✔
1898
                {
1899
                        if (!processed.Add((parent.Kind, parent.Id)))
5✔
1900
                                continue;
1901
                        var edges = await context.Set<ImmediateJobContinuationEntity>()
5✔
1902
                                .Where(edge => edge.ParentKind == parent.Kind
5✔
1903
                                        && edge.ParentId == parent.Id
5✔
1904
                                        && edge.ParentOutcome == ContinuationParentOutcome.Unsettled)
5✔
1905
                                .ToListAsync(cancellationToken)
5✔
1906
                                .ConfigureAwait(false);
5✔
1907
                        foreach (var edge in edges)
5✔
1908
                        {
1909
                                edge.ParentOutcome = parent.Outcome;
5✔
1910
                                var child = await context.Set<ImmediateJobEntity>()
5✔
1911
                                        .SingleOrDefaultAsync(job => job.Id == edge.ChildJobId, cancellationToken)
5✔
1912
                                        .ConfigureAwait(false);
5✔
1913
                                if (child is null || IsTerminal(child.State))
5✔
1914
                                        continue;
1915

1916
                                if (child.State != JobState.AwaitingContinuation || child.RemainingDependencies <= 0)
5✔
1917
                                        continue;
1918
                                child.RemainingDependencies--;
5✔
1919
                                if (parent.Outcome == ContinuationParentOutcome.Failed)
5✔
1920
                                        child.FailedDependencies++;
5✔
1921
                                if (child.RemainingDependencies == 0)
5✔
1922
                                {
1923
                                        var skip = await ShouldSkipSettledContinuationAsync(
5✔
1924
                                                context,
5✔
1925
                                                child.Id,
5✔
1926
                                                cancellationToken
5✔
1927
                                        ).ConfigureAwait(false);
5✔
1928
                                        if (skip)
5✔
1929
                                        {
1930
                                                child.State = JobState.Skipped;
5✔
1931
                                                child.CompletedAt = now;
5✔
1932
                                                parents.Enqueue((ContinuationParentKind.Job, child.Id, ContinuationParentOutcome.Other));
5✔
1933
                                                await UpdateBatchForTerminalJobAsync(context, child, now, parents, cancellationToken).ConfigureAwait(false);
5✔
1934
                                        }
1935
                                        else
1936
                                        {
1937
                                                child.State = child.DueAt <= now ? JobState.Pending : JobState.Scheduled;
5✔
1938
                                        }
1939
                                }
1940

1941
                                child.ConcurrencyStamp = Guid.NewGuid();
5✔
1942
                        }
4✔
1943
                }
4✔
1944
        }
5✔
1945

1946
        private static async Task<bool> ShouldSkipSettledContinuationAsync(
1947
                TContext context,
1948
                string childJobId,
1949
                CancellationToken cancellationToken
1950
        )
1951
        {
1952
                var edges = await context.Set<ImmediateJobContinuationEntity>()
5✔
1953
                        .Where(edge => edge.ChildJobId == childJobId)
5✔
1954
                        .ToListAsync(cancellationToken)
5✔
1955
                        .ConfigureAwait(false);
5✔
1956
                var requiresFailure = false;
5✔
1957
                var anyFailed = false;
5✔
1958
                foreach (var edge in edges)
5✔
1959
                {
1960
                        if (edge.Trigger == ContinuationTrigger.Success
5✔
1961
                                && edge.ParentOutcome != ContinuationParentOutcome.Succeeded)
5✔
1962
                                return true;
×
1963
                        requiresFailure |= edge.Trigger == ContinuationTrigger.Failure;
5✔
1964
                        anyFailed |= edge.ParentOutcome == ContinuationParentOutcome.Failed;
5✔
1965
                }
1966

1967
                return requiresFailure && !anyFailed;
5✔
1968
        }
4✔
1969

1970
        private static async Task UpdateBatchForTerminalJobAsync(
1971
                TContext context,
1972
                ImmediateJobEntity job,
1973
                DateTimeOffset now,
1974
                Queue<(ContinuationParentKind Kind, string Id, ContinuationParentOutcome Outcome)> parents,
1975
                CancellationToken cancellationToken
1976
        )
1977
        {
1978
                if (job.BatchId is not { } batchId)
5✔
1979
                        return;
5✔
1980
                var batch = await context.Set<ImmediateJobBatchEntity>()
5✔
1981
                        .SingleAsync(item => item.Id == batchId, cancellationToken)
5✔
1982
                        .ConfigureAwait(false);
5✔
1983
                batch.PendingCount = Math.Max(0, batch.PendingCount - 1);
5✔
1984
                switch (job.State)
5✔
1985
                {
1986
                        case JobState.Succeeded:
1987
                                batch.SucceededCount++;
5✔
1988
                                break;
5✔
1989
                        case JobState.Failed:
1990
                                batch.FailedCount++;
×
1991
                                break;
×
1992
                        case JobState.Cancelled:
1993
                                batch.CancelledCount++;
5✔
1994
                                break;
5✔
1995
                        case JobState.Skipped:
1996
                                batch.SkippedCount++;
1✔
1997
                                break;
1✔
1998
                        case JobState.AwaitingContinuation:
1999
                        case JobState.AwaitingParameters:
2000
                        case JobState.Scheduled:
2001
                        case JobState.Pending:
2002
                        case JobState.Active:
2003
                                throw new ImmediateJobException($"Job '{job.Id}' is not terminal.");
×
2004
                        default:
2005
                                throw new ArgumentOutOfRangeException(nameof(job), job.State, "Unknown job state.");
×
2006
                }
2007

2008
                batch.ConcurrencyStamp = Guid.NewGuid();
5✔
2009
                if (batch.PendingCount != 0)
5✔
2010
                        return;
5✔
2011
                batch.State = GetTerminalBatchState(batch.FailedCount, batch.CancelledCount);
5✔
2012
                batch.CompletedAt = now;
5✔
2013
                parents.Enqueue((
5✔
2014
                        ContinuationParentKind.Batch,
5✔
2015
                        batch.Id,
5✔
2016
                        GetParentOutcome(batch.State)
5✔
2017
                ));
5✔
2018
        }
5✔
2019

2020
        private static async Task EvaluateInitialDependenciesAsync(
2021
                TContext context,
2022
                Dictionary<string, ImmediateJobEntity> jobs,
2023
                ImmediateJobContinuationEntity[] edges,
2024
                DateTimeOffset now,
2025
                CancellationToken cancellationToken
2026
        )
2027
        {
2028
                var externalJobIds = edges
5✔
2029
                        .Where(edge => edge.ParentKind == ContinuationParentKind.Job && !jobs.ContainsKey(edge.ParentId))
5✔
2030
                        .Select(static edge => edge.ParentId)
5✔
2031
                        .Distinct(StringComparer.Ordinal)
5✔
2032
                        .Order(StringComparer.Ordinal)
5✔
2033
                        .ToArray();
5✔
2034
                var externalBatchIds = edges
5✔
2035
                        .Where(static edge => edge.ParentKind == ContinuationParentKind.Batch)
5✔
2036
                        .Select(static edge => edge.ParentId)
5✔
2037
                        .Distinct(StringComparer.Ordinal)
5✔
2038
                        .Order(StringComparer.Ordinal)
5✔
2039
                        .ToArray();
5✔
2040
                var externalJobEntities = externalJobIds.Length == 0
5✔
2041
                        ? []
5✔
2042
                        : await context.Set<ImmediateJobEntity>()
5✔
2043
                                .Where(job => externalJobIds.Contains(job.Id))
5✔
2044
                                .OrderBy(static job => job.Id)
5✔
2045
                                .ToListAsync(cancellationToken)
5✔
2046
                                .ConfigureAwait(false);
5✔
2047
                var externalBatchEntities = externalBatchIds.Length == 0
5✔
2048
                        ? []
5✔
2049
                        : await context.Set<ImmediateJobBatchEntity>()
5✔
2050
                                .Where(batch => externalBatchIds.Contains(batch.Id))
5✔
2051
                                .OrderBy(static batch => batch.Id)
5✔
2052
                                .ToListAsync(cancellationToken)
5✔
2053
                                .ConfigureAwait(false);
5✔
2054
                var externalJobs = externalJobEntities.ToDictionary(job => job.Id, StringComparer.Ordinal);
5✔
2055
                var externalBatches = externalBatchEntities.ToDictionary(batch => batch.Id, StringComparer.Ordinal);
5✔
2056
                if (externalJobs.Count != externalJobIds.Length || externalBatches.Count != externalBatchIds.Length)
5✔
2057
                        throw new ImmediateJobException("A continuation parent does not exist.");
5✔
2058
                foreach (var parent in externalJobEntities.Where(parent => !IsTerminal(parent.State)))
5✔
2059
                        parent.ConcurrencyStamp = Guid.NewGuid();
5✔
2060
                foreach (var parent in externalBatchEntities.Where(parent => parent.State == BatchState.Executing))
5✔
2061
                        parent.ConcurrencyStamp = Guid.NewGuid();
4✔
2062

2063
                var incoming = edges.ToLookup(static edge => edge.ChildJobId, StringComparer.Ordinal);
5✔
2064
                var changed = true;
5✔
2065
                while (changed)
5✔
2066
                {
2067
                        changed = false;
5✔
2068
                        foreach (var job in jobs.Values)
5✔
2069
                        {
2070
                                var dependencies = incoming[job.Id];
5✔
2071
                                if (!dependencies.Any() || IsTerminal(job.State))
5✔
2072
                                        continue;
2073
                                var remaining = 0;
5✔
2074
                                var failedDependencies = 0;
5✔
2075
                                var requiresFailure = false;
5✔
2076
                                var violated = false;
5✔
2077
                                foreach (var edge in dependencies)
5✔
2078
                                {
2079
                                        var (terminal, parentSucceeded, parentFailed) = GetParentState(
5✔
2080
                                                edge,
5✔
2081
                                                jobs,
5✔
2082
                                                externalJobs,
5✔
2083
                                                externalBatches
5✔
2084
                                        );
5✔
2085
                                        requiresFailure |= edge.Trigger == ContinuationTrigger.Failure;
5✔
2086
                                        if (!terminal)
5✔
2087
                                        {
2088
                                                remaining++;
5✔
2089
                                                continue;
5✔
2090
                                        }
2091

2092
                                        edge.ParentOutcome = GetParentOutcome(parentSucceeded, parentFailed);
1✔
2093

2094
                                        if (parentFailed)
1✔
2095
                                                failedDependencies++;
×
2096
                                        if (edge.Trigger == ContinuationTrigger.Success && !parentSucceeded)
1✔
2097
                                                violated = true;
×
2098
                                }
2099

2100
                                job.FailedDependencies = failedDependencies;
5✔
2101
                                if (violated || (remaining == 0 && requiresFailure && failedDependencies == 0))
5✔
2102
                                {
NEW
2103
                                        job.State = JobState.Skipped;
×
2104
                                        job.RemainingDependencies = 0;
×
2105
                                        job.CompletedAt = now;
×
2106
                                        changed = true;
×
2107
                                }
2108
                                else if (remaining == 0)
5✔
2109
                                {
2110
                                        job.State = job.DueAt <= now ? JobState.Pending : JobState.Scheduled;
1✔
2111
                                        job.RemainingDependencies = 0;
1✔
2112
                                }
2113
                                else
2114
                                {
2115
                                        job.State = JobState.AwaitingContinuation;
5✔
2116
                                        job.RemainingDependencies = remaining;
5✔
2117
                                }
2118
                        }
2119
                }
2120
        }
5✔
2121

2122
        private static (bool Terminal, bool Succeeded, bool Failed) GetParentState(
2123
                ImmediateJobContinuationEntity edge,
2124
                Dictionary<string, ImmediateJobEntity> jobs,
2125
                Dictionary<string, ImmediateJobEntity> externalJobs,
2126
                Dictionary<string, ImmediateJobBatchEntity> externalBatches
2127
        )
2128
        {
2129
                if (edge.ParentKind == ContinuationParentKind.Batch)
5✔
2130
                {
2131
                        var state = externalBatches[edge.ParentId].State;
5✔
2132
                        return (state != BatchState.Executing, state == BatchState.Succeeded, state == BatchState.Failed);
5✔
2133
                }
2134

2135
                var jobState = jobs.TryGetValue(edge.ParentId, out var job) ? job.State : externalJobs[edge.ParentId].State;
5✔
2136
                return (IsTerminal(jobState), jobState == JobState.Succeeded, jobState == JobState.Failed);
5✔
2137
        }
2138

2139
        private static void ThrowIfCyclic(
2140
                HashSet<string> jobIds,
2141
                IReadOnlyList<ImmediateJobContinuationEntity> edges
2142
        )
2143
        {
2144
                var indegree = jobIds.ToDictionary(static id => id, static _ => 0, StringComparer.Ordinal);
5✔
2145
                var children = new Dictionary<string, List<string>>(StringComparer.Ordinal);
5✔
2146
                foreach (var edge in edges.Where(edge =>
5✔
2147
                        edge.ParentKind == ContinuationParentKind.Job && jobIds.Contains(edge.ParentId)))
5✔
2148
                {
2149
                        indegree[edge.ChildJobId]++;
5✔
2150
                        if (!children.TryGetValue(edge.ParentId, out var values))
5✔
2151
                                children[edge.ParentId] = values = [];
5✔
2152
                        values.Add(edge.ChildJobId);
5✔
2153
                }
2154

2155
                var ready = new Queue<string>(indegree.Where(static pair => pair.Value == 0).Select(static pair => pair.Key));
5✔
2156
                var visited = 0;
5✔
2157
                while (ready.TryDequeue(out var parent))
5✔
2158
                {
2159
                        visited++;
5✔
2160
                        if (!children.TryGetValue(parent, out var values))
5✔
2161
                                continue;
2162
                        foreach (var child in values)
5✔
2163
                        {
2164
                                if (--indegree[child] == 0)
5✔
2165
                                        ready.Enqueue(child);
5✔
2166
                        }
2167
                }
2168

2169
                if (visited != jobIds.Count)
5✔
2170
                        throw new ImmediateJobException("The continuation graph contains a dependency cycle.");
×
2171
        }
5✔
2172

2173
        private static bool IsTerminal(JobState state) =>
2174
                state is JobState.Succeeded or JobState.Failed or JobState.Cancelled or JobState.Skipped;
5✔
2175

2176
        private static ContinuationParentOutcome GetParentOutcome(JobState state) => state switch
5✔
2177
        {
5✔
2178
                JobState.Succeeded => ContinuationParentOutcome.Succeeded,
5✔
2179
                JobState.Failed => ContinuationParentOutcome.Failed,
5✔
2180
                JobState.AwaitingContinuation or
5✔
2181
                JobState.AwaitingParameters or
5✔
2182
                JobState.Scheduled or
5✔
2183
                JobState.Pending or
5✔
2184
                JobState.Active or
5✔
2185
                JobState.Cancelled or
5✔
2186
                JobState.Skipped => ContinuationParentOutcome.Other,
5✔
UNCOV
2187
                _ => throw new ArgumentOutOfRangeException(nameof(state), state, "Unknown job state."),
×
2188
        };
5✔
2189

2190
        private static ContinuationParentOutcome GetParentOutcome(BatchState state) => state switch
5✔
2191
        {
5✔
2192
                BatchState.Succeeded => ContinuationParentOutcome.Succeeded,
5✔
2193
                BatchState.Failed => ContinuationParentOutcome.Failed,
×
2194
                BatchState.Executing or BatchState.Cancelled => ContinuationParentOutcome.Other,
5✔
2195
                _ => throw new ArgumentOutOfRangeException(nameof(state), state, "Unknown batch state."),
×
2196
        };
5✔
2197

2198
        private static ContinuationParentOutcome GetParentOutcome(bool succeeded, bool failed) =>
2199
                (succeeded, failed) switch
1✔
2200
                {
1✔
2201
                        (true, _) => ContinuationParentOutcome.Succeeded,
1✔
2202
                        (_, true) => ContinuationParentOutcome.Failed,
×
2203
                        _ => ContinuationParentOutcome.Other,
×
2204
                };
1✔
2205

2206
        private static BatchState GetTerminalBatchState(int failed, int cancelled) =>
2207
                failed != 0 ? BatchState.Failed : cancelled != 0 ? BatchState.Cancelled : BatchState.Succeeded;
5✔
2208

2209
        private async ValueTask MutateRecurringAsync(string name, Action<ImmediateRecurringJobEntity> mutate, CancellationToken cancellationToken)
2210
        {
2211
                ArgumentException.ThrowIfNullOrWhiteSpace(name);
1✔
2212
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
1✔
2213
                var schedule = await context.Set<ImmediateRecurringJobEntity>().FindAsync([name], cancellationToken).ConfigureAwait(false);
1✔
2214
                if (schedule is null)
1✔
2215
                        throw new KeyNotFoundException($"Recurring schedule '{name}' was not found.");
1✔
2216
                mutate(schedule);
×
2217
                schedule.ConcurrencyStamp = Guid.NewGuid();
×
2218
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
×
2219
        }
×
2220

2221
        private static Task<int> UpdateRecurringAsync(
2222
                TContext context,
2223
                RecurringJobSchedule schedule,
2224
                CancellationToken cancellationToken
2225
        )
2226
        {
2227
                var concurrencyStamp = Guid.NewGuid();
5✔
2228
                return context.Set<ImmediateRecurringJobEntity>()
5✔
2229
                        .Where(entity => entity.Name == schedule.Name && (schedule.IsCodeDefined || !entity.IsCodeDefined))
5✔
2230
                        .ExecuteUpdateAsync(setters => setters
5✔
2231
                                .SetProperty(entity => entity.JobName, schedule.JobName)
5✔
2232
                                .SetProperty(entity => entity.Cron, schedule.Cron)
5✔
2233
                                .SetProperty(entity => entity.TimeZone, schedule.TimeZone)
5✔
2234
                                .SetProperty(entity => entity.IsCodeDefined, schedule.IsCodeDefined)
5✔
2235
                                .SetProperty(entity => entity.NextRunAt, schedule.NextRunAt)
5✔
2236
                                .SetProperty(entity => entity.ConcurrencyStamp, concurrencyStamp),
5✔
2237
                                cancellationToken);
5✔
2238
        }
2239

2240
        private static async Task ThrowIfReplacingCodeDefinedScheduleAsync(
2241
                TContext context,
2242
                RecurringJobSchedule schedule,
2243
                CancellationToken cancellationToken
2244
        )
2245
        {
2246
                if (!schedule.IsCodeDefined && await context.Set<ImmediateRecurringJobEntity>()
5✔
2247
                        .AnyAsync(entity => entity.Name == schedule.Name && entity.IsCodeDefined, cancellationToken)
5✔
2248
                        .ConfigureAwait(false))
5✔
2249
                {
2250
                        throw new ImmediateJobException("Code-defined recurring schedules cannot be replaced by dynamic schedules.");
4✔
2251
                }
2252
        }
5✔
2253

2254
        private static ImmediateJobEntity ToEntity(JobRecord job) => new()
5✔
2255
        {
5✔
2256
                Id = job.Id,
5✔
2257
                QueueName = job.QueueName,
5✔
2258
                JobName = job.JobName,
5✔
2259
                GroupId = job.GroupId,
5✔
2260
                Payload = job.Payload,
5✔
2261
                Context = job.Context,
5✔
2262
                State = job.State,
5✔
2263
                DueAt = job.DueAt,
5✔
2264
                CreatedAt = job.CreatedAt,
5✔
2265
                Attempt = job.Attempt,
5✔
2266
                WorkerId = job.WorkerId,
5✔
2267
                LeaseExpiresAt = job.LeaseExpiresAt,
5✔
2268
                LastError = job.LastError,
5✔
2269
                CompletedAt = job.CompletedAt,
5✔
2270
                RecurringKey = job.RecurringKey,
5✔
2271
                TraceParent = job.TraceParent,
5✔
2272
                TraceState = job.TraceState,
5✔
2273
                ExecutionTraceId = job.ExecutionTraceId,
5✔
2274
                ExecutionSpanId = job.ExecutionSpanId,
5✔
2275
                ExecutionStartedAt = job.ExecutionStartedAt,
5✔
2276
                BatchId = job.BatchId,
5✔
2277
                RemainingDependencies = job.RemainingDependencies,
5✔
2278
                FailedDependencies = job.FailedDependencies,
5✔
2279
                ConcurrencyStamp = Guid.NewGuid(),
5✔
2280
        };
5✔
2281

2282
        private static ImmediateJobContinuationEntity ToEntity(JobContinuationEdge edge)
2283
        {
2284
                var hasJobParent = edge.ParentJobId is not null;
5✔
2285
                var hasBatchParent = edge.ParentBatchId is not null;
5✔
2286
                if (hasJobParent == hasBatchParent)
5✔
2287
                        throw new ImmediateJobException("A continuation edge must identify exactly one parent job or batch.");
×
2288
                return new()
5✔
2289
                {
5✔
2290
                        ChildJobId = edge.ChildJobId,
5✔
2291
                        ParentKind = hasJobParent ? ContinuationParentKind.Job : ContinuationParentKind.Batch,
5✔
2292
                        ParentId = edge.ParentJobId ?? edge.ParentBatchId!,
5✔
2293
                        Trigger = edge.Trigger,
5✔
2294
                };
5✔
2295
        }
2296

2297
        private static ImmediateJobEntity Copy(ImmediateJobEntity job) => new()
5✔
2298
        {
5✔
2299
                Id = job.Id,
5✔
2300
                QueueName = job.QueueName,
5✔
2301
                JobName = job.JobName,
5✔
2302
                GroupId = job.GroupId,
5✔
2303
                Payload = job.Payload,
5✔
2304
                Context = job.Context,
5✔
2305
                State = job.State,
5✔
2306
                DueAt = job.DueAt,
5✔
2307
                CreatedAt = job.CreatedAt,
5✔
2308
                Attempt = job.Attempt,
5✔
2309
                WorkerId = job.WorkerId,
5✔
2310
                LeaseExpiresAt = job.LeaseExpiresAt,
5✔
2311
                LastError = job.LastError,
5✔
2312
                CompletedAt = job.CompletedAt,
5✔
2313
                RecurringKey = job.RecurringKey,
5✔
2314
                TraceParent = job.TraceParent,
5✔
2315
                TraceState = job.TraceState,
5✔
2316
                ExecutionTraceId = job.ExecutionTraceId,
5✔
2317
                ExecutionSpanId = job.ExecutionSpanId,
5✔
2318
                ExecutionStartedAt = job.ExecutionStartedAt,
5✔
2319
                BatchId = job.BatchId,
5✔
2320
                RemainingDependencies = job.RemainingDependencies,
5✔
2321
                FailedDependencies = job.FailedDependencies,
5✔
2322
                ConcurrencyStamp = job.ConcurrencyStamp,
5✔
2323
        };
5✔
2324

2325
        private static JobRecord ToRecord(ImmediateJobEntity job) => new()
5✔
2326
        {
5✔
2327
                Id = job.Id,
5✔
2328
                QueueName = job.QueueName,
5✔
2329
                JobName = job.JobName,
5✔
2330
                GroupId = job.GroupId,
5✔
2331
                Payload = job.Payload,
5✔
2332
                Context = job.Context,
5✔
2333
                State = job.State,
5✔
2334
                DueAt = job.DueAt,
5✔
2335
                CreatedAt = job.CreatedAt,
5✔
2336
                Attempt = job.Attempt,
5✔
2337
                WorkerId = job.WorkerId,
5✔
2338
                LeaseExpiresAt = job.LeaseExpiresAt,
5✔
2339
                LastError = job.LastError,
5✔
2340
                CompletedAt = job.CompletedAt,
5✔
2341
                RecurringKey = job.RecurringKey,
5✔
2342
                TraceParent = job.TraceParent,
5✔
2343
                TraceState = job.TraceState,
5✔
2344
                ExecutionTraceId = job.ExecutionTraceId,
5✔
2345
                ExecutionSpanId = job.ExecutionSpanId,
5✔
2346
                ExecutionStartedAt = job.ExecutionStartedAt,
5✔
2347
                BatchId = job.BatchId,
5✔
2348
                RemainingDependencies = job.RemainingDependencies,
5✔
2349
                FailedDependencies = job.FailedDependencies,
5✔
2350
        };
5✔
2351

2352
        private static BatchStatus ToStatus(ImmediateJobBatchEntity batch) => new(
5✔
2353
                batch.Id,
5✔
2354
                batch.State,
5✔
2355
                batch.TotalJobs,
5✔
2356
                batch.SucceededCount,
5✔
2357
                batch.FailedCount,
5✔
2358
                batch.CancelledCount,
5✔
2359
                batch.SkippedCount,
5✔
2360
                batch.PendingCount,
5✔
2361
                batch.CreatedAt,
5✔
2362
                batch.StartedAt,
5✔
2363
                batch.CompletedAt,
5✔
2364
                BatchStatus.CalculateFractionSettled(batch.TotalJobs, batch.PendingCount)
5✔
2365
        );
5✔
2366

2367
        private static JobContinuationEdge ToContinuationEdge(ImmediateJobContinuationEntity edge) => new()
5✔
2368
        {
5✔
2369
                ChildJobId = edge.ChildJobId,
5✔
2370
                ParentJobId = edge.ParentKind == ContinuationParentKind.Job ? edge.ParentId : null,
5✔
2371
                ParentBatchId = edge.ParentKind == ContinuationParentKind.Batch ? edge.ParentId : null,
5✔
2372
                Trigger = edge.Trigger,
5✔
2373
        };
5✔
2374

2375
        private static BatchGraphEdge ToGraphEdge(ImmediateJobContinuationEntity edge) => new(
5✔
2376
                edge.ChildJobId,
5✔
2377
                edge.ParentKind == ContinuationParentKind.Job ? edge.ParentId : null,
5✔
2378
                edge.ParentKind == ContinuationParentKind.Batch ? edge.ParentId : null,
5✔
2379
                edge.Trigger
5✔
2380
        );
5✔
2381

2382
        private static ImmediateRecurringJobEntity ToEntity(RecurringJobSchedule schedule) => new()
5✔
2383
        {
5✔
2384
                Name = schedule.Name,
5✔
2385
                JobName = schedule.JobName,
5✔
2386
                Cron = schedule.Cron,
5✔
2387
                TimeZone = schedule.TimeZone,
5✔
2388
                IsCodeDefined = schedule.IsCodeDefined,
5✔
2389
                IsPaused = schedule.IsPaused,
5✔
2390
                NextRunAt = schedule.NextRunAt,
5✔
2391
                LastRunAt = schedule.LastRunAt,
5✔
2392
                ConcurrencyStamp = Guid.NewGuid(),
5✔
2393
        };
5✔
2394
}
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