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

ImmediatePlatform / Immediate.Jobs / 30566028243

30 Jul 2026 05:27PM UTC coverage: 81.482% (+0.8%) from 80.691%
30566028243

Pull #70

github

web-flow
Merge 2e76640a6 into 6da111743
Pull Request #70: Drop dead servers from the monitoring snapshot

19 of 24 new or added lines in 3 files covered. (79.17%)

7159 of 8786 relevant lines covered (81.48%)

2.72 hits per line

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

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

4
namespace Immediate.Jobs.EntityFrameworkCore;
5

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

19
        /// <inheritdoc />
20
        public ValueTask DisposeAsync() => ValueTask.CompletedTask;
5✔
21

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

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

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

61
                _ = context.Set<ImmediateJobEntity>().Add(ToEntity(job));
5✔
62
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
5✔
63
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
5✔
64
        }
5✔
65

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

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

94
        private async ValueTask ExecuteGraphInsertAsync(
95
                JobBatchRecord? batch,
96
                IReadOnlyList<JobRecord> jobs,
97
                IReadOnlyList<JobContinuationEdge> edges,
98
                CancellationToken cancellationToken
99
        )
100
        {
101
                await using var strategyContext = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
102
                var strategy = strategyContext.Database.CreateExecutionStrategy();
5✔
103
                await strategy.ExecuteAsync(
5✔
104
                        operationCancellationToken => InsertGraphCoreAsync(batch, jobs, edges, operationCancellationToken),
5✔
105
                        cancellationToken
5✔
106
                ).ConfigureAwait(false);
5✔
107
        }
5✔
108

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

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

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

140
                if (batch is not null)
5✔
141
                {
142
                        var terminal = jobEntities.Values.Where(static job => IsTerminal(job.State)).ToArray();
5✔
143
                        var pending = jobEntities.Count - terminal.Length;
5✔
144
                        var succeeded = terminal.Count(static job => job.State == JobState.Succeeded);
4✔
145
                        var failed = terminal.Count(static job => job.State == JobState.Failed);
4✔
146
                        var cancelled = terminal.Count(static job => job.State == JobState.Cancelled);
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
                                StartedAt = batch.StartedAt,
5✔
157
                                CompletedAt = pending == 0 ? batch.CompletedAt ?? _timeProvider.GetUtcNow() : null,
5✔
158
                                State = pending == 0 ? GetTerminalBatchState(failed, cancelled) : BatchState.Executing,
5✔
159
                                ConcurrencyStamp = Guid.NewGuid(),
5✔
160
                        });
5✔
161
                }
162

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

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

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

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

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

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

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

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

241
                return acquired;
5✔
242
        }
4✔
243

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

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

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

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

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

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

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

428
                return acquired;
5✔
429
        }
4✔
430

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

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

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

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

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

494
                return acquired;
4✔
495
        }
3✔
496

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

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

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

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

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

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

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

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

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

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

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

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

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

695
                return acquired;
5✔
696
        }
4✔
697

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

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

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

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

744
        /// <inheritdoc />
745
        public async ValueTask AddBatchJobAsync(
746
                string currentJobId,
747
                JobRecord job,
748
                ContinuationOptions options,
749
                CancellationToken cancellationToken = default
750
        )
751
        {
752
                ArgumentNullException.ThrowIfNull(job);
5✔
753
                if (options == ContinuationOptions.Detached)
5✔
754
                        throw new ImmediateJobException("AddToBatchAsync cannot create a detached job.");
×
755
                const int MaxConcurrencyAttempts = 5;
756
                for (var attempt = 0; attempt < MaxConcurrencyAttempts; attempt++)
5✔
757
                {
758
                        try
759
                        {
760
                                await using var strategyContext = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
761
                                var strategy = strategyContext.Database.CreateExecutionStrategy();
5✔
762
                                await strategy.ExecuteAsync(
5✔
763
                                        operationCancellationToken => AddBatchJobCoreAsync(
5✔
764
                                                currentJobId,
5✔
765
                                                job,
5✔
766
                                                options,
5✔
767
                                                operationCancellationToken
5✔
768
                                        ),
5✔
769
                                        cancellationToken
5✔
770
                                ).ConfigureAwait(false);
5✔
771
                                return;
×
772
                        }
×
773
                        catch (DbUpdateConcurrencyException) when (attempt + 1 < MaxConcurrencyAttempts)
5✔
774
                        {
775
                        }
×
776
                }
777
        }
×
778

779
        /// <inheritdoc />
780
        public ValueTask FailAsync(
781
                string jobId,
782
                string workerId,
783
                string error,
784
                DateTimeOffset? nextRetryAt,
785
                CancellationToken cancellationToken = default
786
        ) => MutateOwnedWithDependenciesAsync(jobId, workerId, error, nextRetryAt, succeeded: false, [], cancellationToken);
5✔
787

788
        /// <inheritdoc />
789
        public async ValueTask UpsertRecurringAsync(RecurringJobSchedule schedule, CancellationToken cancellationToken = default)
790
        {
791
                ArgumentNullException.ThrowIfNull(schedule);
5✔
792
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
793
                if (await UpdateRecurringAsync(context, schedule, cancellationToken).ConfigureAwait(false) != 0)
5✔
794
                        return;
795
                await ThrowIfReplacingCodeDefinedScheduleAsync(context, schedule, cancellationToken).ConfigureAwait(false);
5✔
796

797
                _ = context.Add(ToEntity(schedule));
5✔
798
                try
799
                {
800
                        _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
5✔
801
                }
5✔
802
                catch (DbUpdateException)
803
                {
804
                        // A competing node inserted the same schedule after our update attempt.
805
                        await using var retryContext = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
×
806
                        if (await UpdateRecurringAsync(retryContext, schedule, cancellationToken).ConfigureAwait(false) != 0)
×
807
                                return;
808
                        await ThrowIfReplacingCodeDefinedScheduleAsync(retryContext, schedule, cancellationToken).ConfigureAwait(false);
×
809
                        throw;
×
810
                }
811
        }
4✔
812

813
        /// <inheritdoc />
814
        public async ValueTask RemoveObsoleteCodeDefinedRecurringAsync(
815
                IReadOnlyCollection<string> activeScheduleNames,
816
                CancellationToken cancellationToken = default
817
        )
818
        {
819
                ArgumentNullException.ThrowIfNull(activeScheduleNames);
4✔
820
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
4✔
821
                var schedules = context.Set<ImmediateRecurringJobEntity>()
4✔
822
                        .Where(schedule => schedule.IsCodeDefined);
4✔
823
                if (activeScheduleNames.Count != 0)
4✔
824
                        schedules = schedules.Where(schedule => !activeScheduleNames.Contains(schedule.Name));
4✔
825
                _ = await schedules.ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false);
4✔
826
        }
4✔
827

828
        /// <inheritdoc />
829
        public async ValueTask RemoveRecurringAsync(string name, CancellationToken cancellationToken = default)
830
        {
831
                ArgumentException.ThrowIfNullOrWhiteSpace(name);
5✔
832
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
833
                var removed = await context.Set<ImmediateRecurringJobEntity>()
5✔
834
                        .Where(schedule => schedule.Name == name && !schedule.IsCodeDefined)
5✔
835
                        .ExecuteDeleteAsync(cancellationToken)
5✔
836
                        .ConfigureAwait(false);
5✔
837
                if (removed != 0)
5✔
838
                        return;
839
                if (await context.Set<ImmediateRecurringJobEntity>()
5✔
840
                        .AnyAsync(schedule => schedule.Name == name, cancellationToken)
5✔
841
                        .ConfigureAwait(false))
5✔
842
                {
843
                        throw new ImmediateJobException("Code-defined recurring schedules cannot be deleted.");
4✔
844
                }
845

846
                throw new KeyNotFoundException($"Recurring schedule '{name}' was not found.");
5✔
847
        }
3✔
848

849
        /// <inheritdoc />
850
        public ValueTask PauseRecurringAsync(string name, CancellationToken cancellationToken = default)
851
                => MutateRecurringAsync(name, schedule => schedule.IsPaused = true, cancellationToken);
×
852

853
        /// <inheritdoc />
854
        public ValueTask ResumeRecurringAsync(string name, CancellationToken cancellationToken = default)
855
                => MutateRecurringAsync(name, schedule => schedule.IsPaused = false, cancellationToken);
×
856

857
        /// <inheritdoc />
858
        public async ValueTask<IReadOnlyList<RecurringJobSchedule>> GetDueRecurringAsync(DateTimeOffset now, int batchSize, CancellationToken cancellationToken = default)
859
        {
860
                ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(batchSize, 0);
×
861
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
×
862
                return await context.Set<ImmediateRecurringJobEntity>()
×
863
                        .AsNoTracking()
×
864
                        .Where(schedule => !schedule.IsPaused && schedule.NextRunAt <= now)
×
865
                        .OrderBy(schedule => schedule.NextRunAt)
×
866
                        .Take(batchSize)
×
867
                        .Select(schedule => new RecurringJobSchedule
×
868
                        {
×
869
                                Name = schedule.Name,
×
870
                                JobName = schedule.JobName,
×
871
                                Cron = schedule.Cron,
×
872
                                TimeZone = schedule.TimeZone,
×
873
                                IsCodeDefined = schedule.IsCodeDefined,
×
874
                                IsPaused = schedule.IsPaused,
×
875
                                NextRunAt = schedule.NextRunAt,
×
876
                                LastRunAt = schedule.LastRunAt,
×
877
                        })
×
878
                        .ToListAsync(cancellationToken)
×
879
                        .ConfigureAwait(false);
×
880
        }
881

882
        /// <inheritdoc />
883
        public async ValueTask<bool> MaterializeRecurringAsync(
884
                RecurringJobSchedule schedule,
885
                JobRecord job,
886
                DateTimeOffset nextRunAt,
887
                CancellationToken cancellationToken = default
888
        )
889
        {
890
                ArgumentNullException.ThrowIfNull(schedule);
5✔
891
                ArgumentNullException.ThrowIfNull(job);
5✔
892
                await using var strategyContext = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
893
                var strategy = strategyContext.Database.CreateExecutionStrategy();
5✔
894
                return await strategy.ExecuteAsync(
5✔
895
                        operationCancellationToken => MaterializeRecurringCoreAsync(
5✔
896
                                schedule,
5✔
897
                                job,
5✔
898
                                nextRunAt,
5✔
899
                                operationCancellationToken
5✔
900
                        ),
5✔
901
                        cancellationToken
5✔
902
                ).ConfigureAwait(false);
5✔
903
        }
4✔
904

905
        private async Task<bool> MaterializeRecurringCoreAsync(
906
                RecurringJobSchedule schedule,
907
                JobRecord job,
908
                DateTimeOffset nextRunAt,
909
                CancellationToken cancellationToken
910
        )
911
        {
912
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
913
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
5✔
914
                var entity = await context.Set<ImmediateRecurringJobEntity>()
5✔
915
                        .SingleOrDefaultAsync(item => item.Name == schedule.Name, cancellationToken)
5✔
916
                        .ConfigureAwait(false);
5✔
917
                if (entity is null || entity.IsPaused || entity.NextRunAt != schedule.NextRunAt)
5✔
918
                        return false;
1✔
919

920
                entity.LastRunAt = schedule.NextRunAt;
5✔
921
                entity.NextRunAt = nextRunAt;
5✔
922
                entity.ConcurrencyStamp = Guid.NewGuid();
5✔
923
                _ = context.Add(ToEntity(job));
5✔
924
                try
925
                {
926
                        _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
5✔
927
                        await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
5✔
928
                        return true;
5✔
929
                }
930
                catch (DbUpdateException)
931
                {
932
                        await transaction.RollbackAsync(cancellationToken).ConfigureAwait(false);
×
933
                        return false;
×
934
                }
935
        }
4✔
936

937
        /// <inheritdoc />
938
        public async ValueTask<JobMonitoringSnapshot> GetMonitoringSnapshotAsync(CancellationToken cancellationToken = default)
939
        {
940
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
941
                var rawCounts = await context.Set<ImmediateJobEntity>()
5✔
942
                        .AsNoTracking()
5✔
943
                        .GroupBy(job => job.State)
5✔
944
                        .Select(group => new { State = group.Key, Count = group.LongCount() })
5✔
945
                        .ToListAsync(cancellationToken)
5✔
946
                        .ConfigureAwait(false);
5✔
947
                var counts = Enum.GetValues<JobState>().ToDictionary(static state => state, static _ => 0L);
5✔
948
                foreach (var item in rawCounts)
5✔
949
                        counts[item.State] = item.Count;
5✔
950

951
                var recurring = await context.Set<ImmediateRecurringJobEntity>()
5✔
952
                        .AsNoTracking()
5✔
953
                        .OrderBy(schedule => schedule.Name)
5✔
954
                        .Select(schedule => new RecurringJobSchedule
5✔
955
                        {
5✔
956
                                Name = schedule.Name,
5✔
957
                                JobName = schedule.JobName,
5✔
958
                                Cron = schedule.Cron,
5✔
959
                                TimeZone = schedule.TimeZone,
5✔
960
                                IsCodeDefined = schedule.IsCodeDefined,
5✔
961
                                IsPaused = schedule.IsPaused,
5✔
962
                                NextRunAt = schedule.NextRunAt,
5✔
963
                                LastRunAt = schedule.LastRunAt,
5✔
964
                        })
5✔
965
                        .ToListAsync(cancellationToken)
5✔
966
                        .ConfigureAwait(false);
5✔
967
                var cutoff = _timeProvider.GetUtcNow() - TimeSpan.FromMinutes(2);
5✔
968
                var servers = await context.Set<ImmediateJobServerEntity>()
5✔
969
                        .AsNoTracking()
5✔
970
                        .Where(server => server.LastHeartbeat >= cutoff)
5✔
971
                        .OrderBy(server => server.WorkerId)
5✔
972
                        .Select(server => new JobServerSnapshot(server.WorkerId, server.LastHeartbeat, server.ActiveWorkers, server.MaxWorkers))
5✔
973
                        .ToListAsync(cancellationToken)
5✔
974
                        .ConfigureAwait(false);
5✔
975
                return new(_timeProvider.GetUtcNow(), counts, recurring, servers)
5✔
976
                {
5✔
977
                        Capabilities = this.GetCapabilities(),
5✔
978
                };
5✔
979
        }
4✔
980

981
        /// <inheritdoc />
982
        public async ValueTask<IReadOnlyList<JobRecord>> QueryJobsAsync(JobQuery query, CancellationToken cancellationToken = default)
983
        {
984
                ArgumentNullException.ThrowIfNull(query);
5✔
985
                ArgumentOutOfRangeException.ThrowIfNegative(query.Skip);
5✔
986
                ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(query.Take, 0);
5✔
987
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
988
                IQueryable<ImmediateJobEntity> jobs = context.Set<ImmediateJobEntity>().AsNoTracking();
5✔
989
                if (query.Id is { } id)
5✔
990
                        jobs = jobs.Where(job => job.Id == id);
5✔
991
                if (query.State is { } state)
5✔
992
                        jobs = jobs.Where(job => job.State == state);
4✔
993
                if (!string.IsNullOrWhiteSpace(query.QueueName))
5✔
994
                        jobs = jobs.Where(job => job.QueueName == query.QueueName);
×
995
                if (!string.IsNullOrWhiteSpace(query.JobName))
5✔
996
                        jobs = jobs.Where(job => job.JobName == query.JobName);
×
997
                if (!string.IsNullOrWhiteSpace(query.Search))
5✔
998
                {
999
                        var search = query.Search.ToUpperInvariant();
×
1000
                        // The parameterless form is intentionally used because relational providers translate it to SQL.
1001
#pragma warning disable CA1304, CA1311, CA1862
1002
                        jobs = jobs.Where(job => job.JobName.ToUpper().Contains(search));
×
1003
#pragma warning restore CA1304, CA1311, CA1862
1004
                }
1005

1006
                var entities = await jobs.OrderByDescending(job => job.CreatedAt)
5✔
1007
                        .Skip(query.Skip)
5✔
1008
                        .Take(query.Take)
5✔
1009
                        .ToListAsync(cancellationToken)
5✔
1010
                        .ConfigureAwait(false);
5✔
1011
                return [.. entities.Select(ToRecord)];
5✔
1012
        }
4✔
1013

1014
        /// <inheritdoc />
1015
        public async ValueTask<BatchStatus?> GetBatchStatusAsync(
1016
                string batchId,
1017
                CancellationToken cancellationToken = default
1018
        )
1019
        {
1020
                ArgumentException.ThrowIfNullOrWhiteSpace(batchId);
5✔
1021
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1022
                var batch = await context.Set<ImmediateJobBatchEntity>()
5✔
1023
                        .AsNoTracking()
5✔
1024
                        .SingleOrDefaultAsync(item => item.Id == batchId, cancellationToken)
5✔
1025
                        .ConfigureAwait(false);
5✔
1026
                return batch is null ? null : ToStatus(batch);
5✔
1027
        }
4✔
1028

1029
        /// <inheritdoc />
1030
        public async ValueTask<IReadOnlyList<JobContinuationEdge>> GetIncomingEdgesAsync(
1031
                IReadOnlyCollection<string> childJobIds,
1032
                CancellationToken cancellationToken = default
1033
        )
1034
        {
1035
                ArgumentNullException.ThrowIfNull(childJobIds);
5✔
1036
                foreach (var childJobId in childJobIds)
5✔
1037
                        ArgumentException.ThrowIfNullOrWhiteSpace(childJobId);
5✔
1038
                if (childJobIds.Count == 0)
5✔
1039
                        return [];
5✔
1040

1041
                var ids = childJobIds.Distinct(StringComparer.Ordinal).ToArray();
5✔
1042
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1043
                var edges = await context.Set<ImmediateJobContinuationEntity>()
5✔
1044
                        .AsNoTracking()
5✔
1045
                        .Where(edge => ids.Contains(edge.ChildJobId))
5✔
1046
                        .OrderBy(edge => edge.ChildJobId)
5✔
1047
                        .ThenBy(edge => edge.ParentKind)
5✔
1048
                        .ThenBy(edge => edge.ParentId)
5✔
1049
                        .ToListAsync(cancellationToken)
5✔
1050
                        .ConfigureAwait(false);
5✔
1051
                return [.. edges.Select(ToContinuationEdge)];
5✔
1052
        }
4✔
1053

1054
        /// <inheritdoc />
1055
        public async ValueTask<IReadOnlyList<BatchStatus>> QueryBatchesAsync(
1056
                JobBatchQuery query,
1057
                CancellationToken cancellationToken = default
1058
        )
1059
        {
1060
                ArgumentNullException.ThrowIfNull(query);
×
1061
                ArgumentOutOfRangeException.ThrowIfNegative(query.Skip);
×
1062
                ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(query.Take, 0);
×
1063
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
×
1064
                IQueryable<ImmediateJobBatchEntity> batches = context.Set<ImmediateJobBatchEntity>().AsNoTracking();
×
1065
                if (query.State is { } state)
×
1066
                        batches = batches.Where(batch => batch.State == state);
×
1067
                var entities = await batches.OrderByDescending(batch => batch.CreatedAt)
×
1068
                        .ThenBy(batch => batch.Id)
×
1069
                        .Skip(query.Skip)
×
1070
                        .Take(query.Take)
×
1071
                        .ToListAsync(cancellationToken)
×
1072
                        .ConfigureAwait(false);
×
1073
                return [.. entities.Select(ToStatus)];
×
1074
        }
1075

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

1111
        /// <inheritdoc />
1112
        public async ValueTask<BatchGraph?> GetBatchGraphAsync(
1113
                string batchId,
1114
                CancellationToken cancellationToken = default
1115
        )
1116
        {
1117
                ArgumentException.ThrowIfNullOrWhiteSpace(batchId);
4✔
1118
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
4✔
1119
                if (!await context.Set<ImmediateJobBatchEntity>()
4✔
1120
                        .AnyAsync(batch => batch.Id == batchId, cancellationToken)
4✔
1121
                        .ConfigureAwait(false))
4✔
1122
                {
1123
                        return null;
4✔
1124
                }
1125

1126
                var jobs = await context.Set<ImmediateJobEntity>()
×
1127
                        .AsNoTracking()
×
1128
                        .Where(job => job.BatchId == batchId)
×
1129
                        .OrderBy(job => job.CreatedAt)
×
1130
                        .ThenBy(job => job.Id)
×
1131
                        .Select(job => new BatchGraphNode(job.Id, job.JobName, job.State))
×
1132
                        .ToListAsync(cancellationToken)
×
1133
                        .ConfigureAwait(false);
×
1134
                var ids = jobs.Select(static job => job.JobId).ToArray();
×
1135
                var edges = ids.Length == 0
×
1136
                        ? []
×
1137
                        : await context.Set<ImmediateJobContinuationEntity>()
×
1138
                                .AsNoTracking()
×
1139
                                .Where(edge => ids.Contains(edge.ChildJobId))
×
1140
                                .OrderBy(edge => edge.ChildJobId)
×
1141
                                .ThenBy(edge => edge.ParentKind)
×
1142
                                .ThenBy(edge => edge.ParentId)
×
1143
                                .ToListAsync(cancellationToken)
×
1144
                                .ConfigureAwait(false);
×
1145
                return new(batchId, jobs, [.. edges.Select(ToGraphEdge)]);
4✔
1146
        }
3✔
1147

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

1185
        /// <inheritdoc />
1186
        public ValueTask CancelBatchAsync(string batchId, CancellationToken cancellationToken = default)
1187
        {
1188
                ArgumentException.ThrowIfNullOrWhiteSpace(batchId);
5✔
1189
                return ExecuteWithStrategyAsync(
5✔
1190
                        operationCancellationToken => CancelBatchCoreAsync(batchId, operationCancellationToken),
5✔
1191
                        cancellationToken
5✔
1192
                );
5✔
1193
        }
1194

1195
        private async Task CancelBatchCoreAsync(string batchId, CancellationToken cancellationToken)
1196
        {
1197
                var now = _timeProvider.GetUtcNow();
5✔
1198
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1199
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
5✔
1200
                var batch = await context.Set<ImmediateJobBatchEntity>()
5✔
1201
                        .SingleOrDefaultAsync(item => item.Id == batchId, cancellationToken)
5✔
1202
                        .ConfigureAwait(false)
5✔
1203
                        ?? throw new KeyNotFoundException($"Batch '{batchId}' was not found.");
5✔
1204
                if (batch.State != BatchState.Executing)
4✔
1205
                        throw new ImmediateJobException("Only an executing batch can be cancelled.");
×
1206

1207
                var jobs = await context.Set<ImmediateJobEntity>()
4✔
1208
                        .Where(job => job.BatchId == batchId)
4✔
1209
                        .ToListAsync(cancellationToken)
4✔
1210
                        .ConfigureAwait(false);
4✔
1211
                foreach (var job in jobs)
4✔
1212
                {
1213
                        if (IsTerminal(job.State))
4✔
1214
                                continue;
1215
                        job.State = JobState.Cancelled;
4✔
1216
                        job.CompletedAt = now;
4✔
1217
                        job.WorkerId = null;
4✔
1218
                        job.LeaseExpiresAt = null;
4✔
1219
                        job.ConcurrencyStamp = Guid.NewGuid();
4✔
1220
                        await PropagateTerminalAsync(context, job, now, cancellationToken).ConfigureAwait(false);
4✔
1221
                }
1222

1223
                var terminalGroups = GetTerminalFairQueueGroups(context);
4✔
1224
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
4✔
1225
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
4✔
1226
                foreach (var (queueName, groupId) in terminalGroups)
4✔
1227
                {
1228
                        await TryRemoveFairQueueCursorAsync(queueName, groupId, CancellationToken.None).ConfigureAwait(false);
×
1229
                }
1230
        }
4✔
1231

1232
        /// <inheritdoc />
1233
        public ValueTask DeleteBatchAsync(string batchId, CancellationToken cancellationToken = default)
1234
        {
1235
                ArgumentException.ThrowIfNullOrWhiteSpace(batchId);
5✔
1236
                return ExecuteWithStrategyAsync(
5✔
1237
                        operationCancellationToken => DeleteBatchCoreAsync(batchId, operationCancellationToken),
5✔
1238
                        cancellationToken
5✔
1239
                );
5✔
1240
        }
1241

1242
        private async Task DeleteBatchCoreAsync(string batchId, CancellationToken cancellationToken)
1243
        {
1244
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1245
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
5✔
1246
                var batch = await context.Set<ImmediateJobBatchEntity>()
5✔
1247
                        .SingleOrDefaultAsync(item => item.Id == batchId, cancellationToken)
5✔
1248
                        .ConfigureAwait(false)
5✔
1249
                        ?? throw new KeyNotFoundException($"Batch '{batchId}' was not found.");
5✔
1250
                if (batch.State == BatchState.Executing)
4✔
1251
                        throw new ImmediateJobException("Only a terminal batch can be deleted.");
×
1252

1253
                var jobs = await context.Set<ImmediateJobEntity>()
4✔
1254
                        .Where(job => job.BatchId == batchId)
4✔
1255
                        .ToListAsync(cancellationToken)
4✔
1256
                        .ConfigureAwait(false);
4✔
1257
                var jobIds = jobs.Select(static job => job.Id).ToArray();
4✔
1258
                var edges = await context.Set<ImmediateJobContinuationEntity>()
4✔
1259
                        .Where(edge => jobIds.Contains(edge.ChildJobId)
4✔
1260
                                || edge.ParentKind == ContinuationParentKind.Job && jobIds.Contains(edge.ParentId)
4✔
1261
                                || edge.ParentKind == ContinuationParentKind.Batch && edge.ParentId == batchId)
4✔
1262
                        .ToListAsync(cancellationToken)
4✔
1263
                        .ConfigureAwait(false);
4✔
1264
                context.RemoveRange(edges);
4✔
1265
                context.RemoveRange(jobs);
4✔
1266
                _ = context.Remove(batch);
4✔
1267
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
4✔
1268
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
4✔
1269
        }
4✔
1270

1271
        /// <inheritdoc />
1272
        public ValueTask RetryAsync(string jobId, CancellationToken cancellationToken = default)
1273
        {
1274
                ArgumentException.ThrowIfNullOrWhiteSpace(jobId);
5✔
1275
                return ExecuteWithStrategyAsync(
5✔
1276
                        operationCancellationToken => RetryCoreAsync(jobId, operationCancellationToken),
5✔
1277
                        cancellationToken
5✔
1278
                );
5✔
1279
        }
1280

1281
        private async Task RetryCoreAsync(string jobId, CancellationToken cancellationToken)
1282
        {
1283
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1284
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
5✔
1285
                var job = await context.Set<ImmediateJobEntity>()
5✔
1286
                        .SingleOrDefaultAsync(item => item.Id == jobId && item.State == JobState.Failed, cancellationToken)
5✔
1287
                        .ConfigureAwait(false);
5✔
1288
                if (job is null)
5✔
1289
                {
1290
                        if (await context.Set<ImmediateJobEntity>()
5✔
1291
                                .AnyAsync(item => item.Id == jobId, cancellationToken)
5✔
1292
                                .ConfigureAwait(false))
5✔
1293
                        {
1294
                                throw new ImmediateJobException("Only failed jobs can be retried.");
4✔
1295
                        }
1296

1297
                        throw new KeyNotFoundException($"Job '{jobId}' was not found.");
5✔
1298
                }
1299

1300
                if (job.BatchId is { } batchId)
×
1301
                {
1302
                        var batch = await context.Set<ImmediateJobBatchEntity>()
×
1303
                                .SingleAsync(item => item.Id == batchId, cancellationToken)
×
1304
                                .ConfigureAwait(false);
×
1305
                        batch.PendingCount++;
×
1306
                        batch.FailedCount = Math.Max(0, batch.FailedCount - 1);
×
1307
                        batch.State = BatchState.Executing;
×
1308
                        batch.CompletedAt = null;
×
1309
                        batch.ConcurrencyStamp = Guid.NewGuid();
×
1310
                }
1311

1312
                job.State = JobState.Pending;
×
1313
                job.DueAt = _timeProvider.GetUtcNow();
×
1314
                job.WorkerId = null;
×
1315
                job.LeaseExpiresAt = null;
×
1316
                job.CompletedAt = null;
×
1317
                job.LastError = null;
×
1318
                job.ConcurrencyStamp = Guid.NewGuid();
×
1319
                try
1320
                {
1321
                        _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
×
1322
                }
×
1323
                catch (DbUpdateConcurrencyException)
1324
                {
1325
                        if (!await context.Set<ImmediateJobEntity>()
×
1326
                                .AsNoTracking()
×
1327
                                .AnyAsync(item => item.Id == jobId, cancellationToken)
×
1328
                                .ConfigureAwait(false))
×
1329
                        {
1330
                                throw new KeyNotFoundException($"Job '{jobId}' was not found.");
×
1331
                        }
1332

1333
                        throw new ImmediateJobException("Only failed jobs can be retried.");
×
1334
                }
1335

1336
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
×
1337
        }
×
1338

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

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

1367
                        throw new KeyNotFoundException($"Job '{jobId}' was not found.");
5✔
1368
                }
1369

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

1391
                        throw new KeyNotFoundException($"Job '{jobId}' was not found.");
×
1392
                }
1393

1394
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
1✔
1395
        }
1✔
1396

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

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

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

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

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

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

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

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

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

1545
        private async ValueTask MutateOwnedWithDependenciesAsync(
1546
                string jobId,
1547
                string workerId,
1548
                string? error,
1549
                DateTimeOffset? nextRetryAt,
1550
                bool succeeded,
1551
                IReadOnlyList<JobContinuationAddition> additions,
1552
                CancellationToken cancellationToken
1553
        )
1554
        {
1555
                const int MaxConcurrencyAttempts = 5;
1556
                for (var attempt = 0; attempt < MaxConcurrencyAttempts; attempt++)
5✔
1557
                {
1558
                        try
1559
                        {
1560
                                await using var strategyContext = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1561
                                var strategy = strategyContext.Database.CreateExecutionStrategy();
5✔
1562
                                await strategy.ExecuteAsync(
5✔
1563
                                        operationCancellationToken => MutateOwnedCoreAsync(
5✔
1564
                                                jobId,
5✔
1565
                                                workerId,
5✔
1566
                                                error,
5✔
1567
                                                nextRetryAt,
5✔
1568
                                                succeeded,
5✔
1569
                                                additions,
5✔
1570
                                                operationCancellationToken
5✔
1571
                                        ),
5✔
1572
                                        cancellationToken
5✔
1573
                                ).ConfigureAwait(false);
5✔
1574
                                return;
5✔
1575
                        }
×
1576
                        catch (DbUpdateConcurrencyException) when (attempt + 1 < MaxConcurrencyAttempts)
5✔
1577
                        {
1578
                                // A competing parent completion changed a shared child or batch counter. The whole
1579
                                // transaction rolled back, so retrying re-evaluates the graph from durable state.
1580
                        }
×
1581
                }
1582
        }
5✔
1583

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

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

1619
        private async Task MutateOwnedCoreAsync(
1620
                string jobId,
1621
                string workerId,
1622
                string? error,
1623
                DateTimeOffset? nextRetryAt,
1624
                bool succeeded,
1625
                IReadOnlyList<JobContinuationAddition> additions,
1626
                CancellationToken cancellationToken
1627
        )
1628
        {
1629
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1630
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
5✔
1631
                var job = await context.Set<ImmediateJobEntity>()
5✔
1632
                        .SingleOrDefaultAsync(item => item.Id == jobId && item.State == JobState.Active && item.WorkerId == workerId, cancellationToken)
5✔
1633
                        .ConfigureAwait(false);
5✔
1634
                if (job is null)
5✔
1635
                        return;
1636

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1947
        private static async Task<bool> ShouldCancelSettledContinuationAsync(
1948
                TContext context,
1949
                string childJobId,
1950
                CancellationToken cancellationToken
1951
        )
1952
        {
1953
                var edges = await context.Set<ImmediateJobContinuationEntity>()
5✔
1954
                        .Where(edge => edge.ChildJobId == childJobId)
5✔
1955
                        .ToListAsync(cancellationToken)
5✔
1956
                        .ConfigureAwait(false);
5✔
1957
                var parentJobIds = edges
5✔
1958
                        .Where(static edge => edge.ParentKind == ContinuationParentKind.Job)
5✔
1959
                        .Select(static edge => edge.ParentId)
5✔
1960
                        .Distinct(StringComparer.Ordinal)
5✔
1961
                        .ToArray();
5✔
1962
                var parentBatchIds = edges
5✔
1963
                        .Where(static edge => edge.ParentKind == ContinuationParentKind.Batch)
5✔
1964
                        .Select(static edge => edge.ParentId)
×
1965
                        .Distinct(StringComparer.Ordinal)
5✔
1966
                        .ToArray();
5✔
1967
                var parentJobs = parentJobIds.Length == 0
5✔
1968
                        ? []
5✔
1969
                        : await context.Set<ImmediateJobEntity>()
5✔
1970
                                .Where(job => parentJobIds.Contains(job.Id))
5✔
1971
                                .ToDictionaryAsync(job => job.Id, StringComparer.Ordinal, cancellationToken)
5✔
1972
                                .ConfigureAwait(false);
5✔
1973
                var parentBatches = parentBatchIds.Length == 0
5✔
1974
                        ? []
5✔
1975
                        : await context.Set<ImmediateJobBatchEntity>()
5✔
1976
                                .Where(batch => parentBatchIds.Contains(batch.Id))
5✔
1977
                                .ToDictionaryAsync(batch => batch.Id, StringComparer.Ordinal, cancellationToken)
×
1978
                                .ConfigureAwait(false);
5✔
1979
                var requiresFailure = false;
5✔
1980
                var anyFailed = false;
5✔
1981
                // A missing parent has no success or failure outcome; Complete continuations can still proceed.
1982
                foreach (var edge in edges)
5✔
1983
                {
1984
                        bool succeeded;
1985
                        bool failed;
1986
                        if (edge.ParentKind == ContinuationParentKind.Job)
5✔
1987
                        {
1988
                                var state = parentJobs.TryGetValue(edge.ParentId, out var parentJob) ? parentJob?.State : null;
5✔
1989
                                succeeded = state == JobState.Succeeded;
5✔
1990
                                failed = state == JobState.Failed;
5✔
1991
                        }
1992
                        else
1993
                        {
1994
                                var state = parentBatches.TryGetValue(edge.ParentId, out var parentBatch) ? parentBatch?.State : null;
×
1995
                                succeeded = state == BatchState.Succeeded;
×
1996
                                failed = state == BatchState.Failed;
×
1997
                        }
1998

1999
                        if (edge.Trigger == ContinuationTrigger.Success && !succeeded)
5✔
2000
                                return true;
×
2001
                        requiresFailure |= edge.Trigger == ContinuationTrigger.Failure;
5✔
2002
                        anyFailed |= failed;
5✔
2003
                }
2004

2005
                return requiresFailure && !anyFailed;
5✔
2006
        }
4✔
2007

2008
        private static async Task UpdateBatchForTerminalJobAsync(
2009
                TContext context,
2010
                ImmediateJobEntity job,
2011
                DateTimeOffset now,
2012
                Queue<(ContinuationParentKind Kind, string Id, bool Failed)> parents,
2013
                CancellationToken cancellationToken
2014
        )
2015
        {
2016
                if (job.BatchId is not { } batchId)
5✔
2017
                        return;
5✔
2018
                var batch = await context.Set<ImmediateJobBatchEntity>()
5✔
2019
                        .SingleAsync(item => item.Id == batchId, cancellationToken)
5✔
2020
                        .ConfigureAwait(false);
5✔
2021
                batch.PendingCount = Math.Max(0, batch.PendingCount - 1);
5✔
2022
                switch (job.State)
5✔
2023
                {
2024
                        case JobState.Succeeded:
2025
                                batch.SucceededCount++;
5✔
2026
                                break;
5✔
2027
                        case JobState.Failed:
2028
                                batch.FailedCount++;
×
2029
                                break;
×
2030
                        case JobState.Cancelled:
2031
                                batch.CancelledCount++;
4✔
2032
                                break;
4✔
2033
                        case JobState.AwaitingContinuation:
2034
                        case JobState.AwaitingParameters:
2035
                        case JobState.Scheduled:
2036
                        case JobState.Pending:
2037
                        case JobState.Active:
2038
                                throw new ImmediateJobException($"Job '{job.Id}' is not terminal.");
×
2039
                        default:
2040
                                throw new ArgumentOutOfRangeException(nameof(job), job.State, "Unknown job state.");
×
2041
                }
2042

2043
                batch.ConcurrencyStamp = Guid.NewGuid();
5✔
2044
                if (batch.PendingCount != 0)
5✔
2045
                        return;
5✔
2046
                batch.State = GetTerminalBatchState(batch.FailedCount, batch.CancelledCount);
5✔
2047
                batch.CompletedAt = now;
5✔
2048
                parents.Enqueue((
5✔
2049
                        ContinuationParentKind.Batch,
5✔
2050
                        batch.Id,
5✔
2051
                        batch.State == BatchState.Failed
5✔
2052
                ));
5✔
2053
        }
5✔
2054

2055
        private static async Task EvaluateInitialDependenciesAsync(
2056
                TContext context,
2057
                Dictionary<string, ImmediateJobEntity> jobs,
2058
                ImmediateJobContinuationEntity[] edges,
2059
                DateTimeOffset now,
2060
                CancellationToken cancellationToken
2061
        )
2062
        {
2063
                var externalJobIds = edges
5✔
2064
                        .Where(edge => edge.ParentKind == ContinuationParentKind.Job && !jobs.ContainsKey(edge.ParentId))
5✔
2065
                        .Select(static edge => edge.ParentId)
5✔
2066
                        .Distinct(StringComparer.Ordinal)
5✔
2067
                        .ToArray();
5✔
2068
                var externalBatchIds = edges
5✔
2069
                        .Where(static edge => edge.ParentKind == ContinuationParentKind.Batch)
5✔
2070
                        .Select(static edge => edge.ParentId)
5✔
2071
                        .Distinct(StringComparer.Ordinal)
5✔
2072
                        .ToArray();
5✔
2073
                var externalJobs = externalJobIds.Length == 0
5✔
2074
                        ? []
5✔
2075
                        : await context.Set<ImmediateJobEntity>()
5✔
2076
                                .AsNoTracking()
5✔
2077
                                .Where(job => externalJobIds.Contains(job.Id))
5✔
2078
                                .ToDictionaryAsync(job => job.Id, job => job.State, StringComparer.Ordinal, cancellationToken)
5✔
2079
                                .ConfigureAwait(false);
5✔
2080
                var externalBatches = externalBatchIds.Length == 0
5✔
2081
                        ? []
5✔
2082
                        : await context.Set<ImmediateJobBatchEntity>()
5✔
2083
                                .AsNoTracking()
5✔
2084
                                .Where(batch => externalBatchIds.Contains(batch.Id))
5✔
2085
                                .ToDictionaryAsync(batch => batch.Id, batch => batch.State, StringComparer.Ordinal, cancellationToken)
5✔
2086
                                .ConfigureAwait(false);
5✔
2087
                if (externalJobs.Count != externalJobIds.Length || externalBatches.Count != externalBatchIds.Length)
5✔
2088
                        throw new ImmediateJobException("A continuation parent does not exist.");
5✔
2089

2090
                var incoming = edges.ToLookup(static edge => edge.ChildJobId, StringComparer.Ordinal);
5✔
2091
                var changed = true;
5✔
2092
                while (changed)
5✔
2093
                {
2094
                        changed = false;
5✔
2095
                        foreach (var job in jobs.Values)
5✔
2096
                        {
2097
                                var dependencies = incoming[job.Id];
5✔
2098
                                if (!dependencies.Any() || IsTerminal(job.State))
5✔
2099
                                        continue;
2100
                                var remaining = 0;
5✔
2101
                                var failedDependencies = 0;
5✔
2102
                                var requiresFailure = false;
5✔
2103
                                var violated = false;
5✔
2104
                                foreach (var edge in dependencies)
5✔
2105
                                {
2106
                                        var (terminal, parentSucceeded, parentFailed) = GetParentState(
5✔
2107
                                                edge,
5✔
2108
                                                jobs,
5✔
2109
                                                externalJobs,
5✔
2110
                                                externalBatches
5✔
2111
                                        );
5✔
2112
                                        requiresFailure |= edge.Trigger == ContinuationTrigger.Failure;
5✔
2113
                                        if (!terminal)
5✔
2114
                                        {
2115
                                                remaining++;
5✔
2116
                                                continue;
5✔
2117
                                        }
2118

2119
                                        if (parentFailed)
1✔
2120
                                                failedDependencies++;
×
2121
                                        if (edge.Trigger == ContinuationTrigger.Success && !parentSucceeded)
1✔
2122
                                                violated = true;
×
2123
                                }
2124

2125
                                job.FailedDependencies = failedDependencies;
5✔
2126
                                if (violated || remaining == 0 && requiresFailure && failedDependencies == 0)
5✔
2127
                                {
2128
                                        job.State = JobState.Cancelled;
×
2129
                                        job.RemainingDependencies = 0;
×
2130
                                        job.CompletedAt = now;
×
2131
                                        changed = true;
×
2132
                                }
2133
                                else if (remaining == 0)
5✔
2134
                                {
2135
                                        job.State = job.DueAt <= now ? JobState.Pending : JobState.Scheduled;
×
2136
                                        job.RemainingDependencies = 0;
×
2137
                                }
2138
                                else
2139
                                {
2140
                                        job.State = JobState.AwaitingContinuation;
5✔
2141
                                        job.RemainingDependencies = remaining;
5✔
2142
                                }
2143
                        }
2144
                }
2145
        }
5✔
2146

2147
        private static (bool Terminal, bool Succeeded, bool Failed) GetParentState(
2148
                ImmediateJobContinuationEntity edge,
2149
                Dictionary<string, ImmediateJobEntity> jobs,
2150
                Dictionary<string, JobState> externalJobs,
2151
                Dictionary<string, BatchState> externalBatches
2152
        )
2153
        {
2154
                if (edge.ParentKind == ContinuationParentKind.Batch)
5✔
2155
                {
2156
                        var state = externalBatches[edge.ParentId];
5✔
2157
                        return (state != BatchState.Executing, state == BatchState.Succeeded, state == BatchState.Failed);
5✔
2158
                }
2159

2160
                var jobState = jobs.TryGetValue(edge.ParentId, out var job) ? job.State : externalJobs[edge.ParentId];
5✔
2161
                return (IsTerminal(jobState), jobState == JobState.Succeeded, jobState == JobState.Failed);
5✔
2162
        }
2163

2164
        private static void ThrowIfCyclic(
2165
                HashSet<string> jobIds,
2166
                IReadOnlyList<ImmediateJobContinuationEntity> edges
2167
        )
2168
        {
2169
                var indegree = jobIds.ToDictionary(static id => id, static _ => 0, StringComparer.Ordinal);
5✔
2170
                var children = new Dictionary<string, List<string>>(StringComparer.Ordinal);
5✔
2171
                foreach (var edge in edges.Where(edge =>
5✔
2172
                        edge.ParentKind == ContinuationParentKind.Job && jobIds.Contains(edge.ParentId)))
5✔
2173
                {
2174
                        indegree[edge.ChildJobId]++;
5✔
2175
                        if (!children.TryGetValue(edge.ParentId, out var values))
5✔
2176
                                children[edge.ParentId] = values = [];
5✔
2177
                        values.Add(edge.ChildJobId);
5✔
2178
                }
2179

2180
                var ready = new Queue<string>(indegree.Where(static pair => pair.Value == 0).Select(static pair => pair.Key));
5✔
2181
                var visited = 0;
5✔
2182
                while (ready.TryDequeue(out var parent))
5✔
2183
                {
2184
                        visited++;
5✔
2185
                        if (!children.TryGetValue(parent, out var values))
5✔
2186
                                continue;
2187
                        foreach (var child in values)
5✔
2188
                        {
2189
                                if (--indegree[child] == 0)
5✔
2190
                                        ready.Enqueue(child);
5✔
2191
                        }
2192
                }
2193

2194
                if (visited != jobIds.Count)
5✔
2195
                        throw new ImmediateJobException("The continuation graph contains a dependency cycle.");
×
2196
        }
5✔
2197

2198
        private static bool IsTerminal(JobState state) =>
2199
                state is JobState.Succeeded or JobState.Failed or JobState.Cancelled;
5✔
2200

2201
        private static BatchState GetTerminalBatchState(int failed, int cancelled) =>
2202
                failed != 0 ? BatchState.Failed : cancelled != 0 ? BatchState.Cancelled : BatchState.Succeeded;
5✔
2203

2204
        private async ValueTask MutateRecurringAsync(string name, Action<ImmediateRecurringJobEntity> mutate, CancellationToken cancellationToken)
2205
        {
2206
                ArgumentException.ThrowIfNullOrWhiteSpace(name);
×
2207
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
×
2208
                var schedule = await context.Set<ImmediateRecurringJobEntity>().FindAsync([name], cancellationToken).ConfigureAwait(false);
×
2209
                if (schedule is null)
×
2210
                        return;
2211
                mutate(schedule);
×
2212
                schedule.ConcurrencyStamp = Guid.NewGuid();
×
2213
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
×
2214
        }
×
2215

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

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

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

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

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

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

2347
        private static BatchStatus ToStatus(ImmediateJobBatchEntity batch) => new(
5✔
2348
                batch.Id,
5✔
2349
                batch.State,
5✔
2350
                batch.TotalJobs,
5✔
2351
                batch.SucceededCount,
5✔
2352
                batch.FailedCount,
5✔
2353
                batch.CancelledCount,
5✔
2354
                batch.PendingCount,
5✔
2355
                batch.CreatedAt,
5✔
2356
                batch.StartedAt,
5✔
2357
                batch.CompletedAt,
5✔
2358
                BatchStatus.CalculateFractionSettled(batch.TotalJobs, batch.PendingCount)
5✔
2359
        );
5✔
2360

2361
        private static JobContinuationEdge ToContinuationEdge(ImmediateJobContinuationEntity edge) => new()
5✔
2362
        {
5✔
2363
                ChildJobId = edge.ChildJobId,
5✔
2364
                ParentJobId = edge.ParentKind == ContinuationParentKind.Job ? edge.ParentId : null,
5✔
2365
                ParentBatchId = edge.ParentKind == ContinuationParentKind.Batch ? edge.ParentId : null,
5✔
2366
                Trigger = edge.Trigger,
5✔
2367
        };
5✔
2368

2369
        private static BatchGraphEdge ToGraphEdge(ImmediateJobContinuationEntity edge) => new(
5✔
2370
                edge.ChildJobId,
5✔
2371
                edge.ParentKind == ContinuationParentKind.Job ? edge.ParentId : null,
5✔
2372
                edge.ParentKind == ContinuationParentKind.Batch ? edge.ParentId : null,
5✔
2373
                edge.Trigger
5✔
2374
        );
5✔
2375

2376
        private static ImmediateRecurringJobEntity ToEntity(RecurringJobSchedule schedule) => new()
5✔
2377
        {
5✔
2378
                Name = schedule.Name,
5✔
2379
                JobName = schedule.JobName,
5✔
2380
                Cron = schedule.Cron,
5✔
2381
                TimeZone = schedule.TimeZone,
5✔
2382
                IsCodeDefined = schedule.IsCodeDefined,
5✔
2383
                IsPaused = schedule.IsPaused,
5✔
2384
                NextRunAt = schedule.NextRunAt,
5✔
2385
                LastRunAt = schedule.LastRunAt,
5✔
2386
                ConcurrencyStamp = Guid.NewGuid(),
5✔
2387
        };
5✔
2388
}
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