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

ImmediatePlatform / Immediate.Jobs / 30642381675

31 Jul 2026 03:19PM UTC coverage: 83.228% (+0.01%) from 83.214%
30642381675

push

github

web-flow
Add a durable skipped job state (#81)

63 of 70 new or added lines in 8 files covered. (90.0%)

6 existing lines in 4 files now uncovered.

7493 of 9003 relevant lines covered (83.23%)

2.75 hits per line

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

83.25
/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 &&
5✔
1278
                                (item.State == JobState.Failed || item.State == JobState.Scheduled), cancellationToken)
5✔
1279
                        .ConfigureAwait(false);
5✔
1280
                if (job is null)
5✔
1281
                {
1282
                        if (await context.Set<ImmediateJobEntity>()
5✔
1283
                                .AnyAsync(item => item.Id == jobId, cancellationToken)
5✔
1284
                                .ConfigureAwait(false))
5✔
1285
                        {
1286
                                throw new ImmediateJobException("Only failed or scheduled jobs can be retried.");
4✔
1287
                        }
1288

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

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

1305
                job.State = JobState.Pending;
1✔
1306
                job.DueAt = _timeProvider.GetUtcNow();
1✔
1307
                job.WorkerId = null;
1✔
1308
                job.LeaseExpiresAt = null;
1✔
1309
                if (wasFailed)
1✔
1310
                {
1311
                        job.CompletedAt = null;
1✔
1312
                        job.LastError = null;
1✔
1313
                }
1314

1315
                job.ConcurrencyStamp = Guid.NewGuid();
1✔
1316
                try
1317
                {
1318
                        _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
1✔
1319
                }
1✔
1320
                catch (DbUpdateConcurrencyException)
1321
                {
1322
                        if (!await context.Set<ImmediateJobEntity>()
×
1323
                                .AsNoTracking()
×
1324
                                .AnyAsync(item => item.Id == jobId, cancellationToken)
×
1325
                                .ConfigureAwait(false))
×
1326
                        {
1327
                                throw new KeyNotFoundException($"Job '{jobId}' was not found.");
×
1328
                        }
1329

1330
                        throw new ImmediateJobException("Only failed or scheduled jobs can be retried.");
×
1331
                }
1332

1333
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
1✔
1334
        }
1✔
1335

1336
        /// <inheritdoc />
1337
        public ValueTask DeleteAsync(string jobId, CancellationToken cancellationToken = default)
1338
        {
1339
                ArgumentException.ThrowIfNullOrWhiteSpace(jobId);
5✔
1340
                return ExecuteWithStrategyAsync(
5✔
1341
                        operationCancellationToken => DeleteCoreAsync(jobId, operationCancellationToken),
5✔
1342
                        cancellationToken
5✔
1343
                );
5✔
1344
        }
1345

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

1364
                        throw new KeyNotFoundException($"Job '{jobId}' was not found.");
5✔
1365
                }
1366

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

1388
                        throw new KeyNotFoundException($"Job '{jobId}' was not found.");
×
1389
                }
1390

1391
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
1✔
1392
        }
1✔
1393

1394
        /// <inheritdoc />
1395
        public ValueTask PurgeJobsAsync(
1396
                TimeSpan succeededRetention,
1397
                TimeSpan failedRetention,
1398
                CancellationToken cancellationToken = default
1399
        )
1400
        {
1401
                var now = _timeProvider.GetUtcNow();
4✔
1402
                return ExecuteWithStrategyAsync(
4✔
1403
                        operationCancellationToken => PurgeJobsCoreAsync(
4✔
1404
                                now - succeededRetention,
4✔
1405
                                now - failedRetention,
4✔
1406
                                operationCancellationToken
4✔
1407
                        ),
4✔
1408
                        cancellationToken
4✔
1409
                );
4✔
1410
        }
1411

1412
        /// <inheritdoc />
1413
        public ValueTask PurgeBatchesAsync(
1414
                TimeSpan batchSucceededRetention,
1415
                TimeSpan batchFailedRetention,
1416
                CancellationToken cancellationToken = default
1417
        )
1418
        {
1419
                var now = _timeProvider.GetUtcNow();
4✔
1420
                return ExecuteWithStrategyAsync(
4✔
1421
                        operationCancellationToken => PurgeBatchesCoreAsync(
4✔
1422
                                now - batchSucceededRetention,
4✔
1423
                                now - batchFailedRetention,
4✔
1424
                                operationCancellationToken
4✔
1425
                        ),
4✔
1426
                        cancellationToken
4✔
1427
                );
4✔
1428
        }
1429

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

1458
                context.RemoveRange(jobs);
4✔
1459
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
4✔
1460
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
4✔
1461
        }
4✔
1462

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

1497
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
4✔
1498
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
4✔
1499
        }
4✔
1500

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

1529
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
1✔
1530
        }
1✔
1531

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

1546
        private ValueTask MutateOwnedWithDependenciesAsync(
1547
                string jobId,
1548
                string workerId,
1549
                string? error,
1550
                DateTimeOffset? nextRetryAt,
1551
                bool succeeded,
1552
                IReadOnlyList<JobContinuationAddition> additions,
1553
                CancellationToken cancellationToken
1554
        ) => RetryConcurrencyAsync(
5✔
1555
                operationCancellationToken => MutateOwnedCoreAsync(
5✔
1556
                        jobId,
5✔
1557
                        workerId,
5✔
1558
                        error,
5✔
1559
                        nextRetryAt,
5✔
1560
                        succeeded,
5✔
1561
                        additions,
5✔
1562
                        operationCancellationToken
5✔
1563
                ),
5✔
1564
                cancellationToken
5✔
1565
        );
5✔
1566

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

1586
        private async ValueTask ExecuteWithStrategyAsync(
1587
                Func<CancellationToken, Task> operation,
1588
                CancellationToken cancellationToken
1589
        )
1590
        {
1591
                await using var strategyContext = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1592
                var strategy = strategyContext.Database.CreateExecutionStrategy();
5✔
1593
                await strategy.ExecuteAsync(operation, cancellationToken).ConfigureAwait(false);
5✔
1594
        }
5✔
1595

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

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

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

1654
                if (succeeded && additions.Count != 0)
5✔
1655
                {
1656
                        await FlushContinuationAdditionsAsync(context, job, additions, cancellationToken).ConfigureAwait(false);
5✔
1657
                        _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
×
1658
                }
1659

1660
                job.State = succeeded ? JobState.Succeeded : JobState.Failed;
5✔
1661
                job.CompletedAt = now;
5✔
1662
                await PropagateTerminalAsync(context, job, now, cancellationToken).ConfigureAwait(false);
5✔
1663
                var terminalGroups = GetTerminalFairQueueGroups(context);
5✔
1664
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
5✔
1665
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
5✔
1666
                foreach (var (queueName, groupId) in terminalGroups)
5✔
1667
                        await TryRemoveFairQueueCursorAsync(queueName, groupId, CancellationToken.None).ConfigureAwait(false);
5✔
1668
        }
5✔
1669

1670
        private static (string QueueName, string GroupId)[] GetTerminalFairQueueGroups(TContext context) =>
1671
                [
5✔
1672
                        .. context.ChangeTracker
5✔
1673
                                .Entries<ImmediateJobEntity>()
5✔
1674
                                .Select(static entry => entry.Entity)
5✔
1675
                                .Where(static job => job.GroupId is not null && IsTerminal(job.State))
5✔
1676
                                .Select(static job => (job.QueueName, GroupId: job.GroupId!))
5✔
1677
                                .Distinct(),
5✔
1678
                ];
5✔
1679

1680
        private async ValueTask TryRemoveFairQueueCursorAsync(
1681
                string queueName,
1682
                string groupId,
1683
                CancellationToken cancellationToken
1684
        )
1685
        {
1686
                try
1687
                {
1688
                        await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1689
                        if (await HasLiveGroupJobsAsync(context, queueName, groupId, cancellationToken).ConfigureAwait(false))
5✔
1690
                        {
1691
                                return;
1692
                        }
1693

1694
                        var cursor = await context.Set<ImmediateFairQueueGroupEntity>()
4✔
1695
                                .SingleOrDefaultAsync(
4✔
1696
                                        group => group.QueueName == queueName && group.GroupId == groupId,
4✔
1697
                                        cancellationToken
4✔
1698
                                )
4✔
1699
                                .ConfigureAwait(false);
4✔
1700
                        if (cursor is null)
4✔
1701
                                return;
1702

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

1715
        private static Task<bool> HasLiveGroupJobsAsync(
1716
                TContext context,
1717
                string queueName,
1718
                string groupId,
1719
                CancellationToken cancellationToken
1720
        ) => context.Set<ImmediateJobEntity>().AnyAsync(
5✔
1721
                job => job.QueueName == queueName
5✔
1722
                        && job.GroupId == groupId
5✔
1723
                        && (job.State == JobState.Pending
5✔
1724
                                || job.State == JobState.Scheduled
5✔
1725
                                || job.State == JobState.Active),
5✔
1726
                cancellationToken
5✔
1727
        );
5✔
1728

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

1751
                var batch = await context.Set<ImmediateJobBatchEntity>()
×
1752
                        .SingleAsync(item => item.Id == batchId && item.State == BatchState.Executing, cancellationToken)
×
1753
                        .ConfigureAwait(false);
×
1754
                var job = ToEntity(record);
×
1755
                _ = context.Add(job);
×
1756
                batch.TotalJobs++;
×
1757
                batch.PendingCount++;
×
1758
                batch.ConcurrencyStamp = Guid.NewGuid();
×
1759

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

1777
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
×
1778
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
×
1779
        }
×
1780

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

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

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

1834
                foreach (var addition in additions)
×
1835
                {
1836
                        var job = ToEntity(addition.Job with
×
1837
                        {
×
1838
                                State = JobState.AwaitingContinuation,
×
1839
                                RemainingDependencies = 1,
×
1840
                        });
×
1841
                        _ = context.Add(job);
×
1842
                        _ = context.Add(new ImmediateJobContinuationEntity
×
1843
                        {
×
1844
                                ChildJobId = job.Id,
×
1845
                                ParentKind = ContinuationParentKind.Job,
×
1846
                                ParentId = current.Id,
×
1847
                                Trigger = addition.Trigger,
×
1848
                        });
×
1849

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

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

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

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

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

1947
                                child.ConcurrencyStamp = Guid.NewGuid();
5✔
1948
                        }
4✔
1949
                }
4✔
1950
        }
5✔
1951

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

1973
                return requiresFailure && !anyFailed;
5✔
1974
        }
4✔
1975

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

2014
                batch.ConcurrencyStamp = Guid.NewGuid();
5✔
2015
                if (batch.PendingCount != 0)
5✔
2016
                        return;
5✔
2017
                batch.State = GetTerminalBatchState(batch.FailedCount, batch.CancelledCount);
5✔
2018
                batch.CompletedAt = now;
5✔
2019
                parents.Enqueue((
5✔
2020
                        ContinuationParentKind.Batch,
5✔
2021
                        batch.Id,
5✔
2022
                        GetParentOutcome(batch.State)
5✔
2023
                ));
5✔
2024
        }
5✔
2025

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

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

2098
                                        edge.ParentOutcome = GetParentOutcome(parentSucceeded, parentFailed);
1✔
2099

2100
                                        if (parentFailed)
1✔
2101
                                                failedDependencies++;
×
2102
                                        if (edge.Trigger == ContinuationTrigger.Success && !parentSucceeded)
1✔
2103
                                                violated = true;
×
2104
                                }
2105

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

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

2141
                var jobState = jobs.TryGetValue(edge.ParentId, out var job) ? job.State : externalJobs[edge.ParentId].State;
5✔
2142
                return (IsTerminal(jobState), jobState == JobState.Succeeded, jobState == JobState.Failed);
5✔
2143
        }
2144

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

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

2175
                if (visited != jobIds.Count)
5✔
2176
                        throw new ImmediateJobException("The continuation graph contains a dependency cycle.");
×
2177
        }
5✔
2178

2179
        private static bool IsTerminal(JobState state) =>
2180
                state is JobState.Succeeded or JobState.Failed or JobState.Cancelled or JobState.Skipped;
5✔
2181

2182
        private static ContinuationParentOutcome GetParentOutcome(JobState state) => state switch
5✔
2183
        {
5✔
2184
                JobState.Succeeded => ContinuationParentOutcome.Succeeded,
5✔
2185
                JobState.Failed => ContinuationParentOutcome.Failed,
5✔
2186
                JobState.AwaitingContinuation or
5✔
2187
                JobState.AwaitingParameters or
5✔
2188
                JobState.Scheduled or
5✔
2189
                JobState.Pending or
5✔
2190
                JobState.Active or
5✔
2191
                JobState.Cancelled or
5✔
2192
                JobState.Skipped => ContinuationParentOutcome.Other,
5✔
UNCOV
2193
                _ => throw new ArgumentOutOfRangeException(nameof(state), state, "Unknown job state."),
×
2194
        };
5✔
2195

2196
        private static ContinuationParentOutcome GetParentOutcome(BatchState state) => state switch
5✔
2197
        {
5✔
2198
                BatchState.Succeeded => ContinuationParentOutcome.Succeeded,
5✔
2199
                BatchState.Failed => ContinuationParentOutcome.Failed,
×
2200
                BatchState.Executing or BatchState.Cancelled => ContinuationParentOutcome.Other,
5✔
2201
                _ => throw new ArgumentOutOfRangeException(nameof(state), state, "Unknown batch state."),
×
2202
        };
5✔
2203

2204
        private static ContinuationParentOutcome GetParentOutcome(bool succeeded, bool failed) =>
2205
                (succeeded, failed) switch
1✔
2206
                {
1✔
2207
                        (true, _) => ContinuationParentOutcome.Succeeded,
1✔
2208
                        (_, true) => ContinuationParentOutcome.Failed,
×
2209
                        _ => ContinuationParentOutcome.Other,
×
2210
                };
1✔
2211

2212
        private static BatchState GetTerminalBatchState(int failed, int cancelled) =>
2213
                failed != 0 ? BatchState.Failed : cancelled != 0 ? BatchState.Cancelled : BatchState.Succeeded;
5✔
2214

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

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

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

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

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

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

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

2358
        private static BatchStatus ToStatus(ImmediateJobBatchEntity batch) => new(
5✔
2359
                batch.Id,
5✔
2360
                batch.State,
5✔
2361
                batch.TotalJobs,
5✔
2362
                batch.SucceededCount,
5✔
2363
                batch.FailedCount,
5✔
2364
                batch.CancelledCount,
5✔
2365
                batch.SkippedCount,
5✔
2366
                batch.PendingCount,
5✔
2367
                batch.CreatedAt,
5✔
2368
                batch.StartedAt,
5✔
2369
                batch.CompletedAt,
5✔
2370
                BatchStatus.CalculateFractionSettled(batch.TotalJobs, batch.PendingCount)
5✔
2371
        );
5✔
2372

2373
        private static JobContinuationEdge ToContinuationEdge(ImmediateJobContinuationEntity edge) => new()
5✔
2374
        {
5✔
2375
                ChildJobId = edge.ChildJobId,
5✔
2376
                ParentJobId = edge.ParentKind == ContinuationParentKind.Job ? edge.ParentId : null,
5✔
2377
                ParentBatchId = edge.ParentKind == ContinuationParentKind.Batch ? edge.ParentId : null,
5✔
2378
                Trigger = edge.Trigger,
5✔
2379
        };
5✔
2380

2381
        private static BatchGraphEdge ToGraphEdge(ImmediateJobContinuationEntity edge) => new(
5✔
2382
                edge.ChildJobId,
5✔
2383
                edge.ParentKind == ContinuationParentKind.Job ? edge.ParentId : null,
5✔
2384
                edge.ParentKind == ContinuationParentKind.Batch ? edge.ParentId : null,
5✔
2385
                edge.Trigger
5✔
2386
        );
5✔
2387

2388
        private static ImmediateRecurringJobEntity ToEntity(RecurringJobSchedule schedule) => new()
5✔
2389
        {
5✔
2390
                Name = schedule.Name,
5✔
2391
                JobName = schedule.JobName,
5✔
2392
                Cron = schedule.Cron,
5✔
2393
                TimeZone = schedule.TimeZone,
5✔
2394
                IsCodeDefined = schedule.IsCodeDefined,
5✔
2395
                IsPaused = schedule.IsPaused,
5✔
2396
                NextRunAt = schedule.NextRunAt,
5✔
2397
                LastRunAt = schedule.LastRunAt,
5✔
2398
                ConcurrencyStamp = Guid.NewGuid(),
5✔
2399
        };
5✔
2400
}
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