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

ImmediatePlatform / Immediate.Jobs / 30405079302

28 Jul 2026 10:35PM UTC coverage: 74.395%. First build
30405079302

Pull #46

github

web-flow
Merge 79cea720d into c324de21a
Pull Request #46: Address PR comments

626 of 759 new or added lines in 11 files covered. (82.48%)

5837 of 7846 relevant lines covered (74.39%)

2.4 hits per line

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

80.74
/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 context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
507
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
5✔
508
                var entity = Copy(candidate);
5✔
509
                _ = context.Attach(entity);
5✔
510
                entity.State = JobState.Active;
5✔
511
                entity.WorkerId = workerId;
5✔
512
                entity.LeaseExpiresAt = now + lease;
5✔
513
                entity.Attempt++;
5✔
514
                entity.CompletedAt = null;
5✔
515
                entity.ExecutionTraceId = null;
5✔
516
                entity.ExecutionSpanId = null;
5✔
517
                entity.ExecutionStartedAt = null;
5✔
518
                entity.ConcurrencyStamp = Guid.NewGuid();
5✔
519

520
                if (candidate.GroupId is { } groupId)
5✔
521
                {
522
                        var group = await context.Set<ImmediateFairQueueGroupEntity>()
5✔
523
                                .SingleOrDefaultAsync(
5✔
524
                                        item => item.QueueName == candidate.QueueName && item.GroupId == groupId,
5✔
525
                                        cancellationToken
5✔
526
                                )
5✔
527
                                .ConfigureAwait(false);
5✔
528
                        if (group is null)
5✔
529
                        {
530
                                _ = context.Add(new ImmediateFairQueueGroupEntity
5✔
531
                                {
5✔
532
                                        QueueName = candidate.QueueName,
5✔
533
                                        GroupId = groupId,
5✔
534
                                        LastServedSequence = nextSequence,
5✔
535
                                        ConcurrencyStamp = Guid.NewGuid(),
5✔
536
                                });
5✔
537
                        }
538
                        else if (group.LastServedSequence >= nextSequence)
4✔
539
                        {
540
                                // Selection observed an older cursor snapshot. Re-rank instead of moving this group backward.
541
                                return null;
4✔
542
                        }
543
                        else
544
                        {
545
                                group.LastServedSequence = nextSequence;
4✔
546
                                group.ConcurrencyStamp = Guid.NewGuid();
4✔
547
                        }
548
                }
549

550
                if (entity.BatchId is { } batchId)
5✔
551
                {
552
                        var batch = await context.Set<ImmediateJobBatchEntity>()
×
553
                                .SingleOrDefaultAsync(item => item.Id == batchId, cancellationToken)
×
554
                                .ConfigureAwait(false);
×
555
                        if (batch is not null && batch.StartedAt is null)
×
556
                        {
557
                                batch.StartedAt = now;
×
558
                                batch.ConcurrencyStamp = Guid.NewGuid();
×
559
                        }
560
                }
561

562
                try
563
                {
564
                        _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
5✔
565
                        await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
5✔
566
                        return ToRecord(entity);
5✔
567
                }
568
                catch (DbUpdateException)
4✔
569
                {
570
                        // The job or its group cursor changed after candidate selection.
571
                        return null;
5✔
572
                }
573
        }
4✔
574

575
        private static JobRecord? GetFirstOrDefault(IReadOnlyList<JobRecord> jobs) =>
576
                jobs.Count == 0 ? null : jobs[0];
4✔
577

578
        private static bool IsNoisy(
579
                string? groupId,
580
                int inflight,
581
                int totalInflight,
582
                FairQueuePolicy policy
583
        )
584
        {
585
                return groupId is not null
5✔
586
                        && totalInflight > 0
5✔
587
                        && inflight >= policy.MinInflightForNoisy
5✔
588
                        && (double)inflight / totalInflight > policy.ConcurrencyShareThreshold;
5✔
589
        }
590

591
        private sealed record FairQueueCandidateState(
5✔
592
                string JobId,
5✔
593
                int Inflight,
5✔
594
                long LastServedSequence
5✔
595
        );
5✔
596

597
        /// <inheritdoc />
598
        public async ValueTask<IReadOnlyList<JobRecord>> AcquireJobsAsync(
599
                IReadOnlyCollection<string> jobIds,
600
                string workerId,
601
                TimeSpan lease,
602
                CancellationToken cancellationToken = default
603
        )
604
        {
605
                ArgumentNullException.ThrowIfNull(jobIds);
5✔
606
                ArgumentException.ThrowIfNullOrWhiteSpace(workerId);
5✔
607
                ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(lease, TimeSpan.Zero);
5✔
608
                if (jobIds.Count == 0)
5✔
609
                        return [];
×
610

611
                var now = _timeProvider.GetUtcNow();
5✔
612
                var ids = jobIds.ToArray();
5✔
613
                await using var readContext = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
614
                var candidates = await readContext.Set<ImmediateJobEntity>()
5✔
615
                        .AsNoTracking()
5✔
616
                        .Where(job => ids.Contains(job.Id) &&
5✔
617
                                (((job.State == JobState.Scheduled || job.State == JobState.Pending) && job.DueAt <= now)
5✔
618
                                || (job.State == JobState.Active && job.LeaseExpiresAt <= now)))
5✔
619
                        .ToListAsync(cancellationToken)
5✔
620
                        .ConfigureAwait(false);
5✔
621

622
                return await AcquireCandidatesAsync(candidates, workerId, lease, now, cancellationToken).ConfigureAwait(false);
5✔
623
        }
4✔
624

625
        private async ValueTask<IReadOnlyList<JobRecord>> AcquireCandidatesAsync(
626
                List<ImmediateJobEntity> candidates,
627
                string workerId,
628
                TimeSpan lease,
629
                DateTimeOffset now,
630
                CancellationToken cancellationToken
631
        )
632
        {
633
                var acquired = new List<JobRecord>(candidates.Count);
5✔
634
                foreach (var candidate in candidates)
5✔
635
                {
636
                        await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
637
                        var entity = Copy(candidate);
5✔
638
                        _ = context.Attach(entity);
5✔
639
                        entity.State = JobState.Active;
5✔
640
                        entity.WorkerId = workerId;
5✔
641
                        entity.LeaseExpiresAt = now + lease;
5✔
642
                        entity.Attempt++;
5✔
643
                        entity.CompletedAt = null;
5✔
644
                        entity.ExecutionTraceId = null;
5✔
645
                        entity.ExecutionSpanId = null;
5✔
646
                        entity.ExecutionStartedAt = null;
5✔
647
                        entity.ConcurrencyStamp = Guid.NewGuid();
5✔
648
                        if (entity.BatchId is { } batchId)
5✔
649
                        {
650
                                var batch = await context.Set<ImmediateJobBatchEntity>()
5✔
651
                                        .SingleOrDefaultAsync(item => item.Id == batchId, cancellationToken)
5✔
652
                                        .ConfigureAwait(false);
5✔
653
                                if (batch is not null && batch.StartedAt is null)
5✔
654
                                {
655
                                        batch.StartedAt = now;
5✔
656
                                        batch.ConcurrencyStamp = Guid.NewGuid();
5✔
657
                                }
658
                        }
659

660
                        try
661
                        {
662
                                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
5✔
663
                                acquired.Add(ToRecord(entity));
5✔
664
                        }
5✔
665
                        catch (DbUpdateConcurrencyException)
1✔
666
                        {
667
                                // Another scheduler claimed or changed this candidate first.
668
                        }
1✔
669
                }
4✔
670

671
                return acquired;
5✔
672
        }
4✔
673

674
        /// <inheritdoc />
675
        public ValueTask SetExecutionTelemetryAsync(
676
                string jobId,
677
                string workerId,
678
                string? traceId,
679
                string? spanId,
680
                DateTimeOffset startedAt,
681
                CancellationToken cancellationToken = default
682
        ) => MutateOwnedAsync(jobId, workerId, job =>
1✔
683
        {
1✔
684
                job.ExecutionTraceId = traceId;
1✔
685
                job.ExecutionSpanId = spanId;
1✔
686
                job.ExecutionStartedAt = startedAt;
1✔
687
        }, cancellationToken);
1✔
688

689
        /// <inheritdoc />
690
        public ValueTask RenewLeaseAsync(string jobId, string workerId, TimeSpan lease, CancellationToken cancellationToken = default)
691
        {
692
                ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(lease, TimeSpan.Zero);
×
693
                return MutateOwnedAsync(jobId, workerId, job => job.LeaseExpiresAt = _timeProvider.GetUtcNow() + lease, cancellationToken);
×
694
        }
695

696
        /// <inheritdoc />
697
        public ValueTask CompleteAsync(string jobId, string workerId, CancellationToken cancellationToken = default) =>
698
                CompleteWithContinuationsAsync(jobId, workerId, [], cancellationToken);
5✔
699

700
        /// <inheritdoc />
701
        public ValueTask CompleteWithContinuationsAsync(
702
                string jobId,
703
                string workerId,
704
                IReadOnlyList<JobContinuationAddition> additions,
705
                CancellationToken cancellationToken = default
706
        )
707
        {
708
                ArgumentNullException.ThrowIfNull(additions);
5✔
709
                return MutateOwnedWithDependenciesAsync(
5✔
710
                        jobId,
5✔
711
                        workerId,
5✔
712
                        error: null,
5✔
713
                        nextRetryAt: null,
5✔
714
                        succeeded: true,
5✔
715
                        additions,
5✔
716
                        cancellationToken
5✔
717
                );
5✔
718
        }
719

720
        /// <inheritdoc />
721
        public async ValueTask AddBatchJobAsync(
722
                string currentJobId,
723
                JobRecord job,
724
                ContinuationOptions options,
725
                CancellationToken cancellationToken = default
726
        )
727
        {
728
                ArgumentNullException.ThrowIfNull(job);
5✔
729
                if (options == ContinuationOptions.Detached)
5✔
730
                        throw new ImmediateJobException("AddToBatchAsync cannot create a detached job.");
×
731
                const int MaxConcurrencyAttempts = 5;
732
                for (var attempt = 0; attempt < MaxConcurrencyAttempts; attempt++)
5✔
733
                {
734
                        try
735
                        {
736
                                await using var strategyContext = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
737
                                var strategy = strategyContext.Database.CreateExecutionStrategy();
5✔
738
                                await strategy.ExecuteAsync(
5✔
739
                                        operationCancellationToken => AddBatchJobCoreAsync(
5✔
740
                                                currentJobId,
5✔
741
                                                job,
5✔
742
                                                options,
5✔
743
                                                operationCancellationToken
5✔
744
                                        ),
5✔
745
                                        cancellationToken
5✔
746
                                ).ConfigureAwait(false);
5✔
747
                                return;
×
748
                        }
×
749
                        catch (DbUpdateConcurrencyException) when (attempt + 1 < MaxConcurrencyAttempts)
5✔
750
                        {
751
                        }
×
752
                }
753
        }
×
754

755
        /// <inheritdoc />
756
        public ValueTask FailAsync(
757
                string jobId,
758
                string workerId,
759
                string error,
760
                DateTimeOffset? nextRetryAt,
761
                CancellationToken cancellationToken = default
762
        ) => MutateOwnedWithDependenciesAsync(jobId, workerId, error, nextRetryAt, succeeded: false, [], cancellationToken);
5✔
763

764
        /// <inheritdoc />
765
        public async ValueTask UpsertRecurringAsync(RecurringJobSchedule schedule, CancellationToken cancellationToken = default)
766
        {
767
                ArgumentNullException.ThrowIfNull(schedule);
5✔
768
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
769
                if (await UpdateRecurringAsync(context, schedule, cancellationToken).ConfigureAwait(false) != 0)
5✔
770
                        return;
771
                await ThrowIfReplacingCodeDefinedScheduleAsync(context, schedule, cancellationToken).ConfigureAwait(false);
5✔
772

773
                _ = context.Add(ToEntity(schedule));
5✔
774
                try
775
                {
776
                        _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
5✔
777
                }
5✔
778
                catch (DbUpdateException)
779
                {
780
                        // A competing node inserted the same schedule after our update attempt.
781
                        await using var retryContext = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
×
782
                        if (await UpdateRecurringAsync(retryContext, schedule, cancellationToken).ConfigureAwait(false) != 0)
×
783
                                return;
784
                        await ThrowIfReplacingCodeDefinedScheduleAsync(retryContext, schedule, cancellationToken).ConfigureAwait(false);
×
785
                        throw;
×
786
                }
787
        }
4✔
788

789
        /// <inheritdoc />
790
        public async ValueTask RemoveObsoleteCodeDefinedRecurringAsync(
791
                IReadOnlyCollection<string> activeScheduleNames,
792
                CancellationToken cancellationToken = default
793
        )
794
        {
795
                ArgumentNullException.ThrowIfNull(activeScheduleNames);
4✔
796
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
4✔
797
                var schedules = context.Set<ImmediateRecurringJobEntity>()
4✔
798
                        .Where(schedule => schedule.IsCodeDefined);
4✔
799
                if (activeScheduleNames.Count != 0)
4✔
800
                        schedules = schedules.Where(schedule => !activeScheduleNames.Contains(schedule.Name));
4✔
801
                _ = await schedules.ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false);
4✔
802
        }
4✔
803

804
        /// <inheritdoc />
805
        public async ValueTask RemoveRecurringAsync(string name, CancellationToken cancellationToken = default)
806
        {
807
                ArgumentException.ThrowIfNullOrWhiteSpace(name);
5✔
808
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
809
                var removed = await context.Set<ImmediateRecurringJobEntity>()
5✔
810
                        .Where(schedule => schedule.Name == name && !schedule.IsCodeDefined)
5✔
811
                        .ExecuteDeleteAsync(cancellationToken)
5✔
812
                        .ConfigureAwait(false);
5✔
813
                if (removed != 0)
5✔
814
                        return;
815
                if (await context.Set<ImmediateRecurringJobEntity>()
5✔
816
                        .AnyAsync(schedule => schedule.Name == name, cancellationToken)
5✔
817
                        .ConfigureAwait(false))
5✔
818
                {
819
                        throw new ImmediateJobException("Code-defined recurring schedules cannot be deleted.");
4✔
820
                }
821

822
                throw new KeyNotFoundException($"Recurring schedule '{name}' was not found.");
5✔
823
        }
3✔
824

825
        /// <inheritdoc />
826
        public ValueTask PauseRecurringAsync(string name, CancellationToken cancellationToken = default)
827
                => MutateRecurringAsync(name, schedule => schedule.IsPaused = true, cancellationToken);
×
828

829
        /// <inheritdoc />
830
        public ValueTask ResumeRecurringAsync(string name, CancellationToken cancellationToken = default)
831
                => MutateRecurringAsync(name, schedule => schedule.IsPaused = false, cancellationToken);
×
832

833
        /// <inheritdoc />
834
        public async ValueTask<IReadOnlyList<RecurringJobSchedule>> GetDueRecurringAsync(DateTimeOffset now, int batchSize, CancellationToken cancellationToken = default)
835
        {
836
                ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(batchSize, 0);
×
837
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
×
838
                return await context.Set<ImmediateRecurringJobEntity>()
×
839
                        .AsNoTracking()
×
840
                        .Where(schedule => !schedule.IsPaused && schedule.NextRunAt <= now)
×
841
                        .OrderBy(schedule => schedule.NextRunAt)
×
842
                        .Take(batchSize)
×
843
                        .Select(schedule => new RecurringJobSchedule
×
844
                        {
×
845
                                Name = schedule.Name,
×
846
                                JobName = schedule.JobName,
×
847
                                Cron = schedule.Cron,
×
848
                                TimeZone = schedule.TimeZone,
×
849
                                IsCodeDefined = schedule.IsCodeDefined,
×
850
                                IsPaused = schedule.IsPaused,
×
851
                                NextRunAt = schedule.NextRunAt,
×
852
                                LastRunAt = schedule.LastRunAt,
×
853
                        })
×
854
                        .ToListAsync(cancellationToken)
×
855
                        .ConfigureAwait(false);
×
856
        }
857

858
        /// <inheritdoc />
859
        public async ValueTask<bool> MaterializeRecurringAsync(
860
                RecurringJobSchedule schedule,
861
                JobRecord job,
862
                DateTimeOffset nextRunAt,
863
                CancellationToken cancellationToken = default
864
        )
865
        {
866
                ArgumentNullException.ThrowIfNull(schedule);
5✔
867
                ArgumentNullException.ThrowIfNull(job);
5✔
868
                await using var strategyContext = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
869
                var strategy = strategyContext.Database.CreateExecutionStrategy();
5✔
870
                return await strategy.ExecuteAsync(
5✔
871
                        operationCancellationToken => MaterializeRecurringCoreAsync(
5✔
872
                                schedule,
5✔
873
                                job,
5✔
874
                                nextRunAt,
5✔
875
                                operationCancellationToken
5✔
876
                        ),
5✔
877
                        cancellationToken
5✔
878
                ).ConfigureAwait(false);
5✔
879
        }
4✔
880

881
        private async Task<bool> MaterializeRecurringCoreAsync(
882
                RecurringJobSchedule schedule,
883
                JobRecord job,
884
                DateTimeOffset nextRunAt,
885
                CancellationToken cancellationToken
886
        )
887
        {
888
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
889
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
5✔
890
                var entity = await context.Set<ImmediateRecurringJobEntity>()
5✔
891
                        .SingleOrDefaultAsync(item => item.Name == schedule.Name, cancellationToken)
5✔
892
                        .ConfigureAwait(false);
5✔
893
                if (entity is null || entity.IsPaused || entity.NextRunAt != schedule.NextRunAt)
5✔
894
                        return false;
1✔
895

896
                entity.LastRunAt = schedule.NextRunAt;
5✔
897
                entity.NextRunAt = nextRunAt;
5✔
898
                entity.ConcurrencyStamp = Guid.NewGuid();
5✔
899
                _ = context.Add(ToEntity(job));
5✔
900
                try
901
                {
902
                        _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
5✔
903
                        await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
5✔
904
                        return true;
5✔
905
                }
906
                catch (DbUpdateException)
907
                {
908
                        await transaction.RollbackAsync(cancellationToken).ConfigureAwait(false);
×
909
                        return false;
×
910
                }
911
        }
4✔
912

913
        /// <inheritdoc />
914
        public async ValueTask<JobMonitoringSnapshot> GetMonitoringSnapshotAsync(CancellationToken cancellationToken = default)
915
        {
916
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
917
                var rawCounts = await context.Set<ImmediateJobEntity>()
5✔
918
                        .AsNoTracking()
5✔
919
                        .GroupBy(job => job.State)
5✔
920
                        .Select(group => new { State = group.Key, Count = group.LongCount() })
5✔
921
                        .ToListAsync(cancellationToken)
5✔
922
                        .ConfigureAwait(false);
5✔
923
                var counts = Enum.GetValues<JobState>().ToDictionary(static state => state, static _ => 0L);
5✔
924
                foreach (var item in rawCounts)
5✔
925
                        counts[item.State] = item.Count;
5✔
926

927
                var recurring = await context.Set<ImmediateRecurringJobEntity>()
5✔
928
                        .AsNoTracking()
5✔
929
                        .OrderBy(schedule => schedule.Name)
5✔
930
                        .Select(schedule => new RecurringJobSchedule
5✔
931
                        {
5✔
932
                                Name = schedule.Name,
5✔
933
                                JobName = schedule.JobName,
5✔
934
                                Cron = schedule.Cron,
5✔
935
                                TimeZone = schedule.TimeZone,
5✔
936
                                IsCodeDefined = schedule.IsCodeDefined,
5✔
937
                                IsPaused = schedule.IsPaused,
5✔
938
                                NextRunAt = schedule.NextRunAt,
5✔
939
                                LastRunAt = schedule.LastRunAt,
5✔
940
                        })
5✔
941
                        .ToListAsync(cancellationToken)
5✔
942
                        .ConfigureAwait(false);
5✔
943
                var servers = await context.Set<ImmediateJobServerEntity>()
5✔
944
                        .AsNoTracking()
5✔
945
                        .OrderBy(server => server.WorkerId)
5✔
946
                        .Select(server => new JobServerSnapshot(server.WorkerId, server.LastHeartbeat, server.ActiveWorkers, server.MaxWorkers))
5✔
947
                        .ToListAsync(cancellationToken)
5✔
948
                        .ConfigureAwait(false);
5✔
949
                return new(_timeProvider.GetUtcNow(), counts, recurring, servers)
5✔
950
                {
5✔
951
                        Capabilities = this.GetCapabilities(),
5✔
952
                };
5✔
953
        }
4✔
954

955
        /// <inheritdoc />
956
        public async ValueTask<IReadOnlyList<JobRecord>> QueryJobsAsync(JobQuery query, CancellationToken cancellationToken = default)
957
        {
958
                ArgumentNullException.ThrowIfNull(query);
5✔
959
                ArgumentOutOfRangeException.ThrowIfNegative(query.Skip);
5✔
960
                ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(query.Take, 0);
5✔
961
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
962
                IQueryable<ImmediateJobEntity> jobs = context.Set<ImmediateJobEntity>().AsNoTracking();
5✔
963
                if (query.Id is { } id)
5✔
964
                        jobs = jobs.Where(job => job.Id == id);
5✔
965
                if (query.State is { } state)
5✔
966
                        jobs = jobs.Where(job => job.State == state);
4✔
967
                if (!string.IsNullOrWhiteSpace(query.QueueName))
5✔
968
                        jobs = jobs.Where(job => job.QueueName == query.QueueName);
×
969
                if (!string.IsNullOrWhiteSpace(query.JobName))
5✔
NEW
970
                        jobs = jobs.Where(job => job.JobName == query.JobName);
×
971
                if (!string.IsNullOrWhiteSpace(query.Search))
5✔
972
                {
973
                        var search = query.Search.ToUpperInvariant();
×
974
                        // The parameterless form is intentionally used because relational providers translate it to SQL.
975
#pragma warning disable CA1304, CA1311, CA1862
976
                        jobs = jobs.Where(job => job.JobName.ToUpper().Contains(search));
×
977
#pragma warning restore CA1304, CA1311, CA1862
978
                }
979

980
                var entities = await jobs.OrderByDescending(job => job.CreatedAt)
5✔
981
                        .Skip(query.Skip)
5✔
982
                        .Take(query.Take)
5✔
983
                        .ToListAsync(cancellationToken)
5✔
984
                        .ConfigureAwait(false);
5✔
985
                return [.. entities.Select(ToRecord)];
5✔
986
        }
4✔
987

988
        /// <inheritdoc />
989
        public async ValueTask<BatchStatus?> GetBatchStatusAsync(
990
                string batchId,
991
                CancellationToken cancellationToken = default
992
        )
993
        {
994
                ArgumentException.ThrowIfNullOrWhiteSpace(batchId);
5✔
995
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
996
                var batch = await context.Set<ImmediateJobBatchEntity>()
5✔
997
                        .AsNoTracking()
5✔
998
                        .SingleOrDefaultAsync(item => item.Id == batchId, cancellationToken)
5✔
999
                        .ConfigureAwait(false);
5✔
1000
                return batch is null ? null : ToStatus(batch);
5✔
1001
        }
4✔
1002

1003
        /// <inheritdoc />
1004
        public async ValueTask<IReadOnlyList<JobContinuationEdge>> GetIncomingEdgesAsync(
1005
                IReadOnlyCollection<string> childJobIds,
1006
                CancellationToken cancellationToken = default
1007
        )
1008
        {
1009
                ArgumentNullException.ThrowIfNull(childJobIds);
5✔
1010
                foreach (var childJobId in childJobIds)
5✔
1011
                        ArgumentException.ThrowIfNullOrWhiteSpace(childJobId);
5✔
1012
                if (childJobIds.Count == 0)
5✔
1013
                        return [];
5✔
1014

1015
                var ids = childJobIds.Distinct(StringComparer.Ordinal).ToArray();
5✔
1016
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1017
                var edges = await context.Set<ImmediateJobContinuationEntity>()
5✔
1018
                        .AsNoTracking()
5✔
1019
                        .Where(edge => ids.Contains(edge.ChildJobId))
5✔
1020
                        .OrderBy(edge => edge.ChildJobId)
5✔
1021
                        .ThenBy(edge => edge.ParentKind)
5✔
1022
                        .ThenBy(edge => edge.ParentId)
5✔
1023
                        .ToListAsync(cancellationToken)
5✔
1024
                        .ConfigureAwait(false);
5✔
1025
                return [.. edges.Select(ToContinuationEdge)];
5✔
1026
        }
4✔
1027

1028
        /// <inheritdoc />
1029
        public async ValueTask<IReadOnlyList<BatchStatus>> QueryBatchesAsync(
1030
                JobBatchQuery query,
1031
                CancellationToken cancellationToken = default
1032
        )
1033
        {
1034
                ArgumentNullException.ThrowIfNull(query);
×
1035
                ArgumentOutOfRangeException.ThrowIfNegative(query.Skip);
×
1036
                ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(query.Take, 0);
×
1037
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
×
1038
                IQueryable<ImmediateJobBatchEntity> batches = context.Set<ImmediateJobBatchEntity>().AsNoTracking();
×
1039
                if (query.State is { } state)
×
1040
                        batches = batches.Where(batch => batch.State == state);
×
1041
                var entities = await batches.OrderByDescending(batch => batch.CreatedAt)
×
1042
                        .ThenBy(batch => batch.Id)
×
1043
                        .Skip(query.Skip)
×
1044
                        .Take(query.Take)
×
1045
                        .ToListAsync(cancellationToken)
×
1046
                        .ConfigureAwait(false);
×
1047
                return [.. entities.Select(ToStatus)];
×
1048
        }
1049

1050
        /// <inheritdoc />
1051
        public async ValueTask<IReadOnlyList<BatchMemberStatus>> QueryBatchMembersAsync(
1052
                string batchId,
1053
                BatchMemberQuery query,
1054
                CancellationToken cancellationToken = default
1055
        )
1056
        {
1057
                ArgumentException.ThrowIfNullOrWhiteSpace(batchId);
4✔
1058
                ArgumentNullException.ThrowIfNull(query);
4✔
1059
                ArgumentOutOfRangeException.ThrowIfNegative(query.Skip);
4✔
1060
                ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(query.Take, 0);
4✔
1061
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
4✔
1062
                IQueryable<ImmediateJobEntity> jobs = context.Set<ImmediateJobEntity>()
4✔
1063
                        .AsNoTracking()
4✔
1064
                        .Where(job => job.BatchId == batchId);
4✔
1065
                if (query.State is { } state)
4✔
1066
                        jobs = jobs.Where(job => job.State == state);
×
1067
                return await jobs.OrderBy(job => job.CreatedAt)
4✔
1068
                        .ThenBy(job => job.Id)
4✔
1069
                        .Skip(query.Skip)
4✔
1070
                        .Take(query.Take)
4✔
1071
                        .Select(job => new BatchMemberStatus(
4✔
1072
                                job.Id,
4✔
1073
                                job.JobName,
4✔
1074
                                job.QueueName,
4✔
1075
                                job.State,
4✔
1076
                                job.Attempt,
4✔
1077
                                job.CreatedAt,
4✔
1078
                                job.CompletedAt,
4✔
1079
                                job.LastError
4✔
1080
                        ))
4✔
1081
                        .ToListAsync(cancellationToken)
4✔
1082
                        .ConfigureAwait(false);
4✔
1083
        }
3✔
1084

1085
        /// <inheritdoc />
1086
        public async ValueTask<BatchGraph?> GetBatchGraphAsync(
1087
                string batchId,
1088
                CancellationToken cancellationToken = default
1089
        )
1090
        {
1091
                ArgumentException.ThrowIfNullOrWhiteSpace(batchId);
4✔
1092
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
4✔
1093
                if (!await context.Set<ImmediateJobBatchEntity>()
4✔
1094
                        .AnyAsync(batch => batch.Id == batchId, cancellationToken)
4✔
1095
                        .ConfigureAwait(false))
4✔
1096
                {
1097
                        return null;
4✔
1098
                }
1099

1100
                var jobs = await context.Set<ImmediateJobEntity>()
×
1101
                        .AsNoTracking()
×
1102
                        .Where(job => job.BatchId == batchId)
×
1103
                        .OrderBy(job => job.CreatedAt)
×
1104
                        .ThenBy(job => job.Id)
×
1105
                        .Select(job => new BatchGraphNode(job.Id, job.JobName, job.State))
×
1106
                        .ToListAsync(cancellationToken)
×
1107
                        .ConfigureAwait(false);
×
1108
                var ids = jobs.Select(static job => job.JobId).ToArray();
×
1109
                var edges = ids.Length == 0
×
1110
                        ? []
×
1111
                        : await context.Set<ImmediateJobContinuationEntity>()
×
1112
                                .AsNoTracking()
×
1113
                                .Where(edge => ids.Contains(edge.ChildJobId))
×
1114
                                .OrderBy(edge => edge.ChildJobId)
×
1115
                                .ThenBy(edge => edge.ParentKind)
×
1116
                                .ThenBy(edge => edge.ParentId)
×
1117
                                .ToListAsync(cancellationToken)
×
1118
                                .ConfigureAwait(false);
×
1119
                return new(batchId, jobs, [.. edges.Select(ToGraphEdge)]);
4✔
1120
        }
3✔
1121

1122
        /// <inheritdoc />
1123
        public async ValueTask<JobStatus?> GetJobStatusAsync(
1124
                string jobId,
1125
                CancellationToken cancellationToken = default
1126
        )
1127
        {
1128
                ArgumentException.ThrowIfNullOrWhiteSpace(jobId);
5✔
1129
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1130
                var job = await context.Set<ImmediateJobEntity>()
5✔
1131
                        .AsNoTracking()
5✔
1132
                        .SingleOrDefaultAsync(item => item.Id == jobId, cancellationToken)
5✔
1133
                        .ConfigureAwait(false);
5✔
1134
                if (job is null)
5✔
1135
                        return null;
5✔
1136
                var edges = await context.Set<ImmediateJobContinuationEntity>()
5✔
1137
                        .AsNoTracking()
5✔
1138
                        .Where(edge => edge.ChildJobId == jobId)
5✔
1139
                        .OrderBy(edge => edge.ParentKind)
5✔
1140
                        .ThenBy(edge => edge.ParentId)
5✔
1141
                        .ToListAsync(cancellationToken)
5✔
1142
                        .ConfigureAwait(false);
5✔
1143
                return new(
5✔
1144
                        job.Id,
5✔
1145
                        job.JobName,
5✔
1146
                        job.QueueName,
5✔
1147
                        job.State,
5✔
1148
                        job.Attempt,
5✔
1149
                        MaxAttempts: null,
5✔
1150
                        job.CreatedAt,
5✔
1151
                        job.DueAt,
5✔
1152
                        job.CompletedAt,
5✔
1153
                        job.LastError,
5✔
1154
                        job.BatchId,
5✔
1155
                        [.. edges.Select(ToGraphEdge)]
5✔
1156
                );
5✔
1157
        }
4✔
1158

1159
        /// <inheritdoc />
1160
        public ValueTask CancelBatchAsync(string batchId, CancellationToken cancellationToken = default)
1161
        {
1162
                ArgumentException.ThrowIfNullOrWhiteSpace(batchId);
5✔
1163
                return ExecuteWithStrategyAsync(
5✔
1164
                        operationCancellationToken => CancelBatchCoreAsync(batchId, operationCancellationToken),
5✔
1165
                        cancellationToken
5✔
1166
                );
5✔
1167
        }
1168

1169
        private async Task CancelBatchCoreAsync(string batchId, CancellationToken cancellationToken)
1170
        {
1171
                var now = _timeProvider.GetUtcNow();
5✔
1172
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1173
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
5✔
1174
                var batch = await context.Set<ImmediateJobBatchEntity>()
5✔
1175
                        .SingleOrDefaultAsync(item => item.Id == batchId, cancellationToken)
5✔
1176
                        .ConfigureAwait(false)
5✔
1177
                        ?? throw new KeyNotFoundException($"Batch '{batchId}' was not found.");
5✔
1178
                if (batch.State != BatchState.Executing)
4✔
1179
                        throw new ImmediateJobException("Only an executing batch can be cancelled.");
×
1180

1181
                var jobs = await context.Set<ImmediateJobEntity>()
4✔
1182
                        .Where(job => job.BatchId == batchId)
4✔
1183
                        .ToListAsync(cancellationToken)
4✔
1184
                        .ConfigureAwait(false);
4✔
1185
                foreach (var job in jobs)
4✔
1186
                {
1187
                        if (IsTerminal(job.State))
4✔
1188
                                continue;
1189
                        job.State = JobState.Cancelled;
4✔
1190
                        job.CompletedAt = now;
4✔
1191
                        job.WorkerId = null;
4✔
1192
                        job.LeaseExpiresAt = null;
4✔
1193
                        job.ConcurrencyStamp = Guid.NewGuid();
4✔
1194
                        await PropagateTerminalAsync(context, job, now, cancellationToken).ConfigureAwait(false);
4✔
1195
                }
1196

1197
                var terminalGroups = GetTerminalFairQueueGroups(context);
4✔
1198
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
4✔
1199
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
4✔
1200
                foreach (var (queueName, groupId) in terminalGroups)
4✔
1201
                {
1202
                        await TryRemoveFairQueueCursorAsync(queueName, groupId, CancellationToken.None).ConfigureAwait(false);
×
1203
                }
1204
        }
4✔
1205

1206
        /// <inheritdoc />
1207
        public ValueTask DeleteBatchAsync(string batchId, CancellationToken cancellationToken = default)
1208
        {
1209
                ArgumentException.ThrowIfNullOrWhiteSpace(batchId);
5✔
1210
                return ExecuteWithStrategyAsync(
5✔
1211
                        operationCancellationToken => DeleteBatchCoreAsync(batchId, operationCancellationToken),
5✔
1212
                        cancellationToken
5✔
1213
                );
5✔
1214
        }
1215

1216
        private async Task DeleteBatchCoreAsync(string batchId, CancellationToken cancellationToken)
1217
        {
1218
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1219
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
5✔
1220
                var batch = await context.Set<ImmediateJobBatchEntity>()
5✔
1221
                        .SingleOrDefaultAsync(item => item.Id == batchId, cancellationToken)
5✔
1222
                        .ConfigureAwait(false)
5✔
1223
                        ?? throw new KeyNotFoundException($"Batch '{batchId}' was not found.");
5✔
1224
                if (batch.State == BatchState.Executing)
4✔
1225
                        throw new ImmediateJobException("Only a terminal batch can be deleted.");
×
1226

1227
                var jobs = await context.Set<ImmediateJobEntity>()
4✔
1228
                        .Where(job => job.BatchId == batchId)
4✔
1229
                        .ToListAsync(cancellationToken)
4✔
1230
                        .ConfigureAwait(false);
4✔
1231
                var jobIds = jobs.Select(static job => job.Id).ToArray();
4✔
1232
                var edges = await context.Set<ImmediateJobContinuationEntity>()
4✔
1233
                        .Where(edge => jobIds.Contains(edge.ChildJobId)
4✔
1234
                                || edge.ParentKind == ContinuationParentKind.Job && jobIds.Contains(edge.ParentId)
4✔
1235
                                || edge.ParentKind == ContinuationParentKind.Batch && edge.ParentId == batchId)
4✔
1236
                        .ToListAsync(cancellationToken)
4✔
1237
                        .ConfigureAwait(false);
4✔
1238
                context.RemoveRange(edges);
4✔
1239
                context.RemoveRange(jobs);
4✔
1240
                _ = context.Remove(batch);
4✔
1241
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
4✔
1242
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
4✔
1243
        }
4✔
1244

1245
        /// <inheritdoc />
1246
        public ValueTask RetryAsync(string jobId, CancellationToken cancellationToken = default)
1247
        {
1248
                ArgumentException.ThrowIfNullOrWhiteSpace(jobId);
5✔
1249
                return ExecuteWithStrategyAsync(
5✔
1250
                        operationCancellationToken => RetryCoreAsync(jobId, operationCancellationToken),
5✔
1251
                        cancellationToken
5✔
1252
                );
5✔
1253
        }
1254

1255
        private async Task RetryCoreAsync(string jobId, CancellationToken cancellationToken)
1256
        {
1257
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1258
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
5✔
1259
                var job = await context.Set<ImmediateJobEntity>()
5✔
1260
                        .SingleOrDefaultAsync(item => item.Id == jobId && item.State == JobState.Failed, cancellationToken)
5✔
1261
                        .ConfigureAwait(false);
5✔
1262
                if (job is null)
5✔
1263
                {
1264
                        if (await context.Set<ImmediateJobEntity>()
5✔
1265
                                .AnyAsync(item => item.Id == jobId, cancellationToken)
5✔
1266
                                .ConfigureAwait(false))
5✔
1267
                        {
1268
                                throw new ImmediateJobException("Only failed jobs can be retried.");
4✔
1269
                        }
1270

1271
                        throw new KeyNotFoundException($"Job '{jobId}' was not found.");
5✔
1272
                }
1273

1274
                if (job.BatchId is { } batchId)
×
1275
                {
1276
                        var batch = await context.Set<ImmediateJobBatchEntity>()
×
1277
                                .SingleAsync(item => item.Id == batchId, cancellationToken)
×
1278
                                .ConfigureAwait(false);
×
1279
                        batch.PendingCount++;
×
1280
                        batch.FailedCount = Math.Max(0, batch.FailedCount - 1);
×
1281
                        batch.State = BatchState.Executing;
×
1282
                        batch.CompletedAt = null;
×
1283
                        batch.ConcurrencyStamp = Guid.NewGuid();
×
1284
                }
1285

1286
                job.State = JobState.Pending;
×
1287
                job.DueAt = _timeProvider.GetUtcNow();
×
1288
                job.WorkerId = null;
×
1289
                job.LeaseExpiresAt = null;
×
1290
                job.CompletedAt = null;
×
1291
                job.LastError = null;
×
1292
                job.ConcurrencyStamp = Guid.NewGuid();
×
1293
                try
1294
                {
NEW
1295
                        _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
×
NEW
1296
                }
×
1297
                catch (DbUpdateConcurrencyException)
1298
                {
NEW
1299
                        if (!await context.Set<ImmediateJobEntity>()
×
NEW
1300
                                .AsNoTracking()
×
NEW
1301
                                .AnyAsync(item => item.Id == jobId, cancellationToken)
×
NEW
1302
                                .ConfigureAwait(false))
×
1303
                        {
NEW
1304
                                throw new KeyNotFoundException($"Job '{jobId}' was not found.");
×
1305
                        }
1306

NEW
1307
                        throw new ImmediateJobException("Only failed jobs can be retried.");
×
1308
                }
1309

1310
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
×
1311
        }
×
1312

1313
        /// <inheritdoc />
1314
        public ValueTask DeleteAsync(string jobId, CancellationToken cancellationToken = default)
1315
        {
1316
                ArgumentException.ThrowIfNullOrWhiteSpace(jobId);
5✔
1317
                return ExecuteWithStrategyAsync(
5✔
1318
                        operationCancellationToken => DeleteCoreAsync(jobId, operationCancellationToken),
5✔
1319
                        cancellationToken
5✔
1320
                );
5✔
1321
        }
1322

1323
        private async Task DeleteCoreAsync(string jobId, CancellationToken cancellationToken)
1324
        {
1325
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1326
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
5✔
1327
                var job = await context.Set<ImmediateJobEntity>()
5✔
1328
                        .AsNoTracking()
5✔
1329
                        .SingleOrDefaultAsync(item => item.Id == jobId
5✔
1330
                                && (item.State == JobState.Succeeded || item.State == JobState.Failed || item.State == JobState.Cancelled), cancellationToken)
5✔
1331
                        .ConfigureAwait(false);
5✔
1332
                if (job is null)
5✔
1333
                {
1334
                        if (await context.Set<ImmediateJobEntity>()
5✔
1335
                                .AnyAsync(item => item.Id == jobId, cancellationToken)
5✔
1336
                                .ConfigureAwait(false))
5✔
1337
                        {
1338
                                throw new ImmediateJobException("Only terminal jobs can be deleted.");
4✔
1339
                        }
1340

1341
                        throw new KeyNotFoundException($"Job '{jobId}' was not found.");
5✔
1342
                }
1343

1344
                if (job.BatchId is not null)
1✔
NEW
1345
                        throw new ImmediateJobException("Batch members are deleted with their batch so the workflow remains coherent.");
×
1346
                _ = await context.Set<ImmediateJobContinuationEntity>()
1✔
1347
                        .Where(edge => edge.ChildJobId == jobId ||
1✔
1348
                                (edge.ParentKind == ContinuationParentKind.Job && edge.ParentId == jobId))
1✔
1349
                        .ExecuteDeleteAsync(cancellationToken)
1✔
1350
                        .ConfigureAwait(false);
1✔
1351
                var removed = await context.Set<ImmediateJobEntity>()
1✔
1352
                        .Where(item => item.Id == jobId &&
1✔
1353
                                (item.State == JobState.Succeeded || item.State == JobState.Failed || item.State == JobState.Cancelled))
1✔
1354
                        .ExecuteDeleteAsync(cancellationToken)
1✔
1355
                        .ConfigureAwait(false);
1✔
1356
                if (removed == 0)
1✔
1357
                {
NEW
1358
                        if (await context.Set<ImmediateJobEntity>()
×
NEW
1359
                                .AnyAsync(item => item.Id == jobId, cancellationToken)
×
NEW
1360
                                .ConfigureAwait(false))
×
1361
                        {
NEW
1362
                                throw new ImmediateJobException("Only terminal jobs can be deleted.");
×
1363
                        }
1364

NEW
1365
                        throw new KeyNotFoundException($"Job '{jobId}' was not found.");
×
1366
                }
1367

1368
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
1✔
1369
        }
1✔
1370

1371
        /// <inheritdoc />
1372
        public ValueTask PurgeJobsAsync(
1373
                TimeSpan succeededRetention,
1374
                TimeSpan failedRetention,
1375
                CancellationToken cancellationToken = default
1376
        )
1377
        {
1378
                var now = _timeProvider.GetUtcNow();
4✔
1379
                return ExecuteWithStrategyAsync(
4✔
1380
                        operationCancellationToken => PurgeJobsCoreAsync(
4✔
1381
                                now - succeededRetention,
4✔
1382
                                now - failedRetention,
4✔
1383
                                operationCancellationToken
4✔
1384
                        ),
4✔
1385
                        cancellationToken
4✔
1386
                );
4✔
1387
        }
1388

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

1407
        private async Task PurgeJobsCoreAsync(
1408
                DateTimeOffset succeededBefore,
1409
                DateTimeOffset failedBefore,
1410
                CancellationToken cancellationToken
1411
        )
1412
        {
1413
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
4✔
1414
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
4✔
1415
                var jobs = await context.Set<ImmediateJobEntity>()
4✔
1416
                        .Where(job => job.BatchId == null
4✔
1417
                                && ((job.State == JobState.Succeeded && job.CompletedAt < succeededBefore)
4✔
1418
                                || ((job.State == JobState.Failed || job.State == JobState.Cancelled) && job.CompletedAt < failedBefore))
4✔
1419
                        )
4✔
1420
                        .ToListAsync(cancellationToken)
4✔
1421
                        .ConfigureAwait(false);
4✔
1422
                if (jobs.Count != 0)
4✔
1423
                {
1424
                        var jobIds = jobs.Select(static job => job.Id).ToArray();
×
1425
                        var edges = await context.Set<ImmediateJobContinuationEntity>()
×
1426
                                .Where(edge => jobIds.Contains(edge.ChildJobId)
×
1427
                                        || jobIds.Contains(edge.ParentId) && edge.ParentKind == ContinuationParentKind.Job)
×
1428
                                .ToListAsync(cancellationToken)
×
1429
                                .ConfigureAwait(false);
×
1430
                        context.RemoveRange(edges);
×
1431
                }
1432

1433
                context.RemoveRange(jobs);
4✔
1434
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
4✔
1435
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
4✔
1436
        }
4✔
1437

1438
        private async Task PurgeBatchesCoreAsync(
1439
                DateTimeOffset batchSucceededBefore,
1440
                DateTimeOffset batchFailedBefore,
1441
                CancellationToken cancellationToken
1442
        )
1443
        {
1444
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
4✔
1445
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
4✔
1446
                var batches = await context.Set<ImmediateJobBatchEntity>()
4✔
1447
                        .Where(batch => (batch.State == BatchState.Succeeded && batch.CompletedAt < batchSucceededBefore)
4✔
1448
                                || ((batch.State == BatchState.Failed || batch.State == BatchState.Cancelled)
4✔
1449
                                        && batch.CompletedAt < batchFailedBefore))
4✔
1450
                        .ToListAsync(cancellationToken)
4✔
1451
                        .ConfigureAwait(false);
4✔
1452
                if (batches.Count != 0)
4✔
1453
                {
1454
                        var batchIds = batches.Select(static batch => batch.Id).ToArray();
×
1455
                        var memberIds = await context.Set<ImmediateJobEntity>()
×
1456
                                .Where(job => job.BatchId != null && batchIds.Contains(job.BatchId))
×
1457
                                .Select(job => job.Id)
×
1458
                                .ToListAsync(cancellationToken)
×
1459
                                .ConfigureAwait(false);
×
1460
                        var edges = await context.Set<ImmediateJobContinuationEntity>()
×
1461
                                .Where(edge => batchIds.Contains(edge.ParentId) && edge.ParentKind == ContinuationParentKind.Batch
×
1462
                                        || memberIds.Contains(edge.ChildJobId)
×
1463
                                        || memberIds.Contains(edge.ParentId) && edge.ParentKind == ContinuationParentKind.Job)
×
1464
                                .ToListAsync(cancellationToken)
×
1465
                                .ConfigureAwait(false);
×
1466
                        context.RemoveRange(edges);
×
1467
                        context.RemoveRange(batches);
×
1468
                }
1469

1470
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
4✔
1471
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
4✔
1472
        }
4✔
1473

1474
        /// <inheritdoc />
1475
        public async ValueTask HeartbeatAsync(JobServerSnapshot server, CancellationToken cancellationToken = default)
1476
        {
1477
                ArgumentNullException.ThrowIfNull(server);
×
1478
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
×
1479
                var entity = await context.Set<ImmediateJobServerEntity>().FindAsync([server.WorkerId], cancellationToken).ConfigureAwait(false);
×
1480
                if (entity is null)
×
1481
                {
1482
                        _ = context.Add(new ImmediateJobServerEntity
×
1483
                        {
×
1484
                                WorkerId = server.WorkerId,
×
1485
                                LastHeartbeat = server.LastHeartbeat,
×
1486
                                ActiveWorkers = server.ActiveWorkers,
×
1487
                                MaxWorkers = server.MaxWorkers,
×
1488
                        });
×
1489
                }
1490
                else
1491
                {
1492
                        entity.LastHeartbeat = server.LastHeartbeat;
×
1493
                        entity.ActiveWorkers = server.ActiveWorkers;
×
1494
                        entity.MaxWorkers = server.MaxWorkers;
×
1495
                }
1496

1497
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
×
1498
        }
×
1499

1500
        /// <inheritdoc />
1501
        public async ValueTask<bool> IsHealthyAsync(CancellationToken cancellationToken = default)
1502
        {
1503
                try
1504
                {
1505
                        await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
×
1506
                        return await context.Database.CanConnectAsync(cancellationToken).ConfigureAwait(false);
×
1507
                }
×
1508
                catch (Exception exception) when (exception is DbException or InvalidOperationException)
×
1509
                {
1510
                        return false;
×
1511
                }
1512
        }
×
1513

1514
        private async ValueTask MutateOwnedWithDependenciesAsync(
1515
                string jobId,
1516
                string workerId,
1517
                string? error,
1518
                DateTimeOffset? nextRetryAt,
1519
                bool succeeded,
1520
                IReadOnlyList<JobContinuationAddition> additions,
1521
                CancellationToken cancellationToken
1522
        )
1523
        {
1524
                const int MaxConcurrencyAttempts = 5;
1525
                for (var attempt = 0; attempt < MaxConcurrencyAttempts; attempt++)
5✔
1526
                {
1527
                        try
1528
                        {
1529
                                await using var strategyContext = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1530
                                var strategy = strategyContext.Database.CreateExecutionStrategy();
5✔
1531
                                await strategy.ExecuteAsync(
5✔
1532
                                        operationCancellationToken => MutateOwnedCoreAsync(
5✔
1533
                                                jobId,
5✔
1534
                                                workerId,
5✔
1535
                                                error,
5✔
1536
                                                nextRetryAt,
5✔
1537
                                                succeeded,
5✔
1538
                                                additions,
5✔
1539
                                                operationCancellationToken
5✔
1540
                                        ),
5✔
1541
                                        cancellationToken
5✔
1542
                                ).ConfigureAwait(false);
5✔
1543
                                return;
5✔
1544
                        }
×
1545
                        catch (DbUpdateConcurrencyException) when (attempt + 1 < MaxConcurrencyAttempts)
5✔
1546
                        {
1547
                                // A competing parent completion changed a shared child or batch counter. The whole
1548
                                // transaction rolled back, so retrying re-evaluates the graph from durable state.
1549
                        }
×
1550
                }
1551
        }
5✔
1552

1553
        private async ValueTask ExecuteWithStrategyAsync(
1554
                Func<CancellationToken, Task> operation,
1555
                CancellationToken cancellationToken
1556
        )
1557
        {
1558
                await using var strategyContext = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1559
                var strategy = strategyContext.Database.CreateExecutionStrategy();
5✔
1560
                await strategy.ExecuteAsync(operation, cancellationToken).ConfigureAwait(false);
5✔
1561
        }
5✔
1562

1563
        private async ValueTask MutateOwnedAsync(
1564
                string jobId,
1565
                string workerId,
1566
                Action<ImmediateJobEntity> mutate,
1567
                CancellationToken cancellationToken
1568
        )
1569
        {
1570
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
1✔
1571
                var job = await context.Set<ImmediateJobEntity>()
1✔
1572
                        .SingleOrDefaultAsync(item => item.Id == jobId && item.State == JobState.Active && item.WorkerId == workerId, cancellationToken)
1✔
1573
                        .ConfigureAwait(false);
1✔
1574
                if (job is null)
1✔
1575
                        return;
1576
                mutate(job);
1✔
1577
                job.ConcurrencyStamp = Guid.NewGuid();
1✔
1578
                try
1579
                {
1580
                        _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
1✔
1581
                }
1✔
1582
                catch (DbUpdateConcurrencyException)
×
1583
                {
1584
                        // A stale worker must not update a lease that has been reclaimed.
1585
                }
1✔
1586
        }
1✔
1587

1588
        private async Task MutateOwnedCoreAsync(
1589
                string jobId,
1590
                string workerId,
1591
                string? error,
1592
                DateTimeOffset? nextRetryAt,
1593
                bool succeeded,
1594
                IReadOnlyList<JobContinuationAddition> additions,
1595
                CancellationToken cancellationToken
1596
        )
1597
        {
1598
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1599
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
5✔
1600
                var job = await context.Set<ImmediateJobEntity>()
5✔
1601
                        .SingleOrDefaultAsync(item => item.Id == jobId && item.State == JobState.Active && item.WorkerId == workerId, cancellationToken)
5✔
1602
                        .ConfigureAwait(false);
5✔
1603
                if (job is null)
5✔
1604
                        return;
1605

1606
                var now = _timeProvider.GetUtcNow();
5✔
1607
                job.WorkerId = null;
5✔
1608
                job.LeaseExpiresAt = null;
5✔
1609
                job.LastError = error;
5✔
1610
                job.ConcurrencyStamp = Guid.NewGuid();
5✔
1611
                if (!succeeded && nextRetryAt is { } retryAt)
5✔
1612
                {
1613
                        job.State = retryAt <= now ? JobState.Pending : JobState.Scheduled;
×
1614
                        job.DueAt = retryAt;
×
1615
                        job.CompletedAt = null;
×
1616
                        _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
×
1617
                        await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
×
1618
                        return;
×
1619
                }
1620

1621
                if (succeeded && additions.Count != 0)
5✔
1622
                {
1623
                        await FlushContinuationAdditionsAsync(context, job, additions, cancellationToken).ConfigureAwait(false);
5✔
1624
                        _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
×
1625
                }
1626

1627
                job.State = succeeded ? JobState.Succeeded : JobState.Failed;
5✔
1628
                job.CompletedAt = now;
5✔
1629
                await PropagateTerminalAsync(context, job, now, cancellationToken).ConfigureAwait(false);
5✔
1630
                var terminalGroups = GetTerminalFairQueueGroups(context);
5✔
1631
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
5✔
1632
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
5✔
1633
                foreach (var (queueName, groupId) in terminalGroups)
5✔
1634
                        await TryRemoveFairQueueCursorAsync(queueName, groupId, CancellationToken.None).ConfigureAwait(false);
5✔
1635
        }
5✔
1636

1637
        private static (string QueueName, string GroupId)[] GetTerminalFairQueueGroups(TContext context) =>
1638
                [
5✔
1639
                        .. context.ChangeTracker
5✔
1640
                                .Entries<ImmediateJobEntity>()
5✔
1641
                                .Select(static entry => entry.Entity)
5✔
1642
                                .Where(static job => job.GroupId is not null && IsTerminal(job.State))
5✔
1643
                                .Select(static job => (job.QueueName, GroupId: job.GroupId!))
5✔
1644
                                .Distinct(),
5✔
1645
                ];
5✔
1646

1647
        private async ValueTask TryRemoveFairQueueCursorAsync(
1648
                string queueName,
1649
                string groupId,
1650
                CancellationToken cancellationToken
1651
        )
1652
        {
1653
                try
1654
                {
1655
                        await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1656
                        if (await HasLiveGroupJobsAsync(context, queueName, groupId, cancellationToken).ConfigureAwait(false))
5✔
1657
                        {
1658
                                return;
1659
                        }
1660

1661
                        var cursor = await context.Set<ImmediateFairQueueGroupEntity>()
4✔
1662
                                .SingleOrDefaultAsync(
4✔
1663
                                        group => group.QueueName == queueName && group.GroupId == groupId,
4✔
1664
                                        cancellationToken
4✔
1665
                                )
4✔
1666
                                .ConfigureAwait(false);
4✔
1667
                        if (cursor is null)
4✔
1668
                                return;
1669

1670
                        _ = context.Remove(cursor);
4✔
1671
                        _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
4✔
1672
                }
4✔
1673
                catch (Exception exception) when (
×
1674
                        !cancellationToken.IsCancellationRequested
×
1675
                        && exception is DbException or DbUpdateException
×
1676
                )
×
1677
                {
1678
                        // Cleanup is best-effort metadata maintenance and must not invalidate a committed transition.
1679
                }
×
1680
        }
5✔
1681

1682
        private static Task<bool> HasLiveGroupJobsAsync(
1683
                TContext context,
1684
                string queueName,
1685
                string groupId,
1686
                CancellationToken cancellationToken
1687
        ) => context.Set<ImmediateJobEntity>().AnyAsync(
5✔
1688
                job => job.QueueName == queueName
5✔
1689
                        && job.GroupId == groupId
5✔
1690
                        && (job.State == JobState.Pending
5✔
1691
                                || job.State == JobState.Scheduled
5✔
1692
                                || job.State == JobState.Active),
5✔
1693
                cancellationToken
5✔
1694
        );
5✔
1695

1696
        private async Task AddBatchJobCoreAsync(
1697
                string currentJobId,
1698
                JobRecord record,
1699
                ContinuationOptions options,
1700
                CancellationToken cancellationToken
1701
        )
1702
        {
1703
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
5✔
1704
                await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
5✔
1705
                var current = await context.Set<ImmediateJobEntity>()
5✔
1706
                        .SingleOrDefaultAsync(job => job.Id == currentJobId && job.State == JobState.Active, cancellationToken)
5✔
1707
                        .ConfigureAwait(false)
5✔
1708
                        ?? throw new ImmediateJobException($"The current active job '{currentJobId}' was not found.");
5✔
1709
                if (current.BatchId is not { } batchId)
5✔
1710
                        throw new ImmediateJobException("The current job does not belong to a batch.");
×
1711
                if (options is not (ContinuationOptions.BesideContinuations or ContinuationOptions.BeforeContinuations))
5✔
NEW
1712
                        throw new ArgumentOutOfRangeException(nameof(options));
×
1713
                if (record.BatchId != batchId)
5✔
1714
                        throw new ImmediateJobException("The new job must belong to the current job's batch.");
5✔
NEW
1715
                if (record.State is JobState.Active or JobState.AwaitingContinuation || IsTerminal(record.State))
×
NEW
1716
                        throw new ImmediateJobException($"Concurrent batch member '{record.Id}' has invalid state '{record.State}'.");
×
1717

1718
                var batch = await context.Set<ImmediateJobBatchEntity>()
×
1719
                        .SingleAsync(item => item.Id == batchId && item.State == BatchState.Executing, cancellationToken)
×
1720
                        .ConfigureAwait(false);
×
NEW
1721
                var job = ToEntity(record);
×
1722
                _ = context.Add(job);
×
1723
                batch.TotalJobs++;
×
1724
                batch.PendingCount++;
×
1725
                batch.ConcurrencyStamp = Guid.NewGuid();
×
1726

1727
                if (options == ContinuationOptions.BeforeContinuations)
×
1728
                {
1729
                        var waiters = await GetActiveWaitersAsync(context, currentJobId, cancellationToken).ConfigureAwait(false);
×
1730
                        foreach (var waiter in waiters)
×
1731
                        {
1732
                                _ = context.Add(new ImmediateJobContinuationEntity
×
1733
                                {
×
1734
                                        ChildJobId = waiter.Id,
×
1735
                                        ParentKind = ContinuationParentKind.Job,
×
1736
                                        ParentId = job.Id,
×
1737
                                        Trigger = ContinuationTrigger.Success,
×
1738
                                });
×
1739
                                waiter.RemainingDependencies++;
×
1740
                                waiter.ConcurrencyStamp = Guid.NewGuid();
×
1741
                        }
1742
                }
1743

1744
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
×
1745
                await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
×
1746
        }
×
1747

1748
        private static async Task FlushContinuationAdditionsAsync(
1749
                TContext context,
1750
                ImmediateJobEntity current,
1751
                IReadOnlyList<JobContinuationAddition> additions,
1752
                CancellationToken cancellationToken
1753
        )
1754
        {
1755
                var ids = new HashSet<string>(StringComparer.Ordinal);
5✔
1756
                var trackedAdditions = 0;
5✔
1757
                foreach (var addition in additions)
5✔
1758
                {
1759
                        ArgumentNullException.ThrowIfNull(addition);
5✔
1760
                        ArgumentNullException.ThrowIfNull(addition.Job);
5✔
1761
                        if (!ids.Add(addition.Job.Id))
5✔
NEW
1762
                                throw new ImmediateJobException("Buffered continuations contain duplicate job identifiers.");
×
1763
                        if (!Enum.IsDefined(addition.Trigger))
5✔
1764
                                throw new ArgumentOutOfRangeException(nameof(additions), "Unknown continuation trigger.");
4✔
1765
                        if (addition.Job.State is not (JobState.Pending or JobState.Scheduled))
5✔
NEW
1766
                                throw new ImmediateJobException($"Dynamic continuation '{addition.Job.Id}' has invalid state '{addition.Job.State}'.");
×
1767

1768
                        if (addition.Options == ContinuationOptions.Detached)
5✔
1769
                        {
1770
                                if (addition.Job.BatchId is not null)
5✔
1771
                                        throw new ImmediateJobException("A detached continuation cannot belong to a batch.");
5✔
1772
                        }
1773
                        else if (addition.Options is ContinuationOptions.BesideContinuations or ContinuationOptions.BeforeContinuations)
5✔
1774
                        {
1775
                                if (current.BatchId is null || addition.Job.BatchId != current.BatchId)
5✔
1776
                                        throw new ImmediateJobException("A batch-tracked continuation must belong to the current job's batch.");
5✔
NEW
1777
                                trackedAdditions++;
×
1778
                        }
1779
                        else
1780
                        {
1781
                                throw new ArgumentOutOfRangeException(nameof(additions), "Unknown continuation option.");
4✔
1782
                        }
1783
                }
1784

1785
                var waiters = additions.Any(static addition => addition.Options == ContinuationOptions.BeforeContinuations)
×
1786
                        ? await GetActiveWaitersAsync(context, current.Id, cancellationToken).ConfigureAwait(false)
×
1787
                        : [];
×
1788
                ImmediateJobBatchEntity? batch = null;
1789
                if (trackedAdditions != 0)
×
1790
                {
1791
                        if (current.BatchId is not { } batchId)
×
1792
                                throw new ImmediateJobException("The current job does not belong to a batch.");
×
1793
                        batch = await context.Set<ImmediateJobBatchEntity>()
×
1794
                                .SingleAsync(item => item.Id == batchId && item.State == BatchState.Executing, cancellationToken)
×
1795
                                .ConfigureAwait(false);
×
1796
                        batch.TotalJobs += trackedAdditions;
×
1797
                        batch.PendingCount += trackedAdditions;
×
1798
                        batch.ConcurrencyStamp = Guid.NewGuid();
×
1799
                }
1800

1801
                foreach (var addition in additions)
×
1802
                {
1803
                        var job = ToEntity(addition.Job with
×
1804
                        {
×
1805
                                State = JobState.AwaitingContinuation,
×
1806
                                RemainingDependencies = 1,
×
1807
                        });
×
1808
                        _ = context.Add(job);
×
1809
                        _ = context.Add(new ImmediateJobContinuationEntity
×
1810
                        {
×
1811
                                ChildJobId = job.Id,
×
1812
                                ParentKind = ContinuationParentKind.Job,
×
1813
                                ParentId = current.Id,
×
1814
                                Trigger = addition.Trigger,
×
1815
                        });
×
1816

1817
                        if (addition.Options != ContinuationOptions.BeforeContinuations)
×
1818
                                continue;
1819
                        foreach (var waiter in waiters)
×
1820
                        {
1821
                                _ = context.Add(new ImmediateJobContinuationEntity
×
1822
                                {
×
1823
                                        ChildJobId = waiter.Id,
×
1824
                                        ParentKind = ContinuationParentKind.Job,
×
1825
                                        ParentId = job.Id,
×
1826
                                        Trigger = ContinuationTrigger.Success,
×
1827
                                });
×
1828
                                waiter.RemainingDependencies++;
×
1829
                                waiter.ConcurrencyStamp = Guid.NewGuid();
×
1830
                        }
1831
                }
1832
        }
×
1833

1834
        private static async Task<List<ImmediateJobEntity>> GetActiveWaitersAsync(
1835
                TContext context,
1836
                string currentJobId,
1837
                CancellationToken cancellationToken
1838
        )
1839
        {
1840
                var waiterIds = await context.Set<ImmediateJobContinuationEntity>()
×
1841
                        .Where(edge => edge.ParentKind == ContinuationParentKind.Job && edge.ParentId == currentJobId)
×
1842
                        .Select(edge => edge.ChildJobId)
×
1843
                        .Distinct()
×
1844
                        .ToArrayAsync(cancellationToken)
×
1845
                        .ConfigureAwait(false);
×
1846
                return waiterIds.Length == 0
×
1847
                        ? []
×
1848
                        : await context.Set<ImmediateJobEntity>()
×
1849
                                .Where(job => waiterIds.Contains(job.Id) && job.State == JobState.AwaitingContinuation)
×
1850
                                .ToListAsync(cancellationToken)
×
1851
                                .ConfigureAwait(false);
×
1852
        }
1853

1854
        private static async Task PropagateTerminalAsync(
1855
                TContext context,
1856
                ImmediateJobEntity terminalJob,
1857
                DateTimeOffset now,
1858
                CancellationToken cancellationToken
1859
        )
1860
        {
1861
                var parents = new Queue<(ContinuationParentKind Kind, string Id, bool Failed)>();
5✔
1862
                var processed = new HashSet<(ContinuationParentKind Kind, string Id)>();
5✔
1863
                parents.Enqueue((
5✔
1864
                        ContinuationParentKind.Job,
5✔
1865
                        terminalJob.Id,
5✔
1866
                        terminalJob.State == JobState.Failed
5✔
1867
                ));
5✔
1868
                await UpdateBatchForTerminalJobAsync(context, terminalJob, now, parents, cancellationToken).ConfigureAwait(false);
5✔
1869

1870
                while (parents.TryDequeue(out var parent))
5✔
1871
                {
1872
                        if (!processed.Add((parent.Kind, parent.Id)))
5✔
1873
                                continue;
1874
                        var edges = await context.Set<ImmediateJobContinuationEntity>()
5✔
1875
                                .Where(edge => edge.ParentKind == parent.Kind && edge.ParentId == parent.Id)
5✔
1876
                                .ToListAsync(cancellationToken)
5✔
1877
                                .ConfigureAwait(false);
5✔
1878
                        foreach (var edge in edges)
5✔
1879
                        {
1880
                                var child = await context.Set<ImmediateJobEntity>()
5✔
1881
                                        .SingleOrDefaultAsync(job => job.Id == edge.ChildJobId, cancellationToken)
5✔
1882
                                        .ConfigureAwait(false);
5✔
1883
                                if (child is null || IsTerminal(child.State))
5✔
1884
                                        continue;
1885

1886
                                if (child.State != JobState.AwaitingContinuation || child.RemainingDependencies <= 0)
5✔
1887
                                        continue;
1888
                                child.RemainingDependencies--;
5✔
1889
                                if (parent.Failed)
5✔
1890
                                        child.FailedDependencies++;
5✔
1891
                                if (child.RemainingDependencies == 0)
5✔
1892
                                {
1893
                                        var cancel = await ShouldCancelSettledContinuationAsync(
5✔
1894
                                                context,
5✔
1895
                                                child.Id,
5✔
1896
                                                cancellationToken
5✔
1897
                                        ).ConfigureAwait(false);
5✔
1898
                                        if (cancel)
5✔
1899
                                        {
1900
                                                child.State = JobState.Cancelled;
5✔
1901
                                                child.CompletedAt = now;
5✔
1902
                                                parents.Enqueue((ContinuationParentKind.Job, child.Id, Failed: false));
5✔
1903
                                                await UpdateBatchForTerminalJobAsync(context, child, now, parents, cancellationToken).ConfigureAwait(false);
5✔
1904
                                        }
1905
                                        else
1906
                                        {
1907
                                                child.State = child.DueAt <= now ? JobState.Pending : JobState.Scheduled;
5✔
1908
                                        }
1909
                                }
1910

1911
                                child.ConcurrencyStamp = Guid.NewGuid();
5✔
1912
                        }
4✔
1913
                }
4✔
1914
        }
5✔
1915

1916
        private static async Task<bool> ShouldCancelSettledContinuationAsync(
1917
                TContext context,
1918
                string childJobId,
1919
                CancellationToken cancellationToken
1920
        )
1921
        {
1922
                var edges = await context.Set<ImmediateJobContinuationEntity>()
5✔
1923
                        .Where(edge => edge.ChildJobId == childJobId)
5✔
1924
                        .ToListAsync(cancellationToken)
5✔
1925
                        .ConfigureAwait(false);
5✔
1926
                var parentJobIds = edges
5✔
1927
                        .Where(static edge => edge.ParentKind == ContinuationParentKind.Job)
5✔
1928
                        .Select(static edge => edge.ParentId)
5✔
1929
                        .Distinct(StringComparer.Ordinal)
5✔
1930
                        .ToArray();
5✔
1931
                var parentBatchIds = edges
5✔
1932
                        .Where(static edge => edge.ParentKind == ContinuationParentKind.Batch)
5✔
NEW
1933
                        .Select(static edge => edge.ParentId)
×
1934
                        .Distinct(StringComparer.Ordinal)
5✔
1935
                        .ToArray();
5✔
1936
                var parentJobs = parentJobIds.Length == 0
5✔
1937
                        ? []
5✔
1938
                        : await context.Set<ImmediateJobEntity>()
5✔
1939
                                .Where(job => parentJobIds.Contains(job.Id))
5✔
1940
                                .ToDictionaryAsync(job => job.Id, StringComparer.Ordinal, cancellationToken)
5✔
1941
                                .ConfigureAwait(false);
5✔
1942
                var parentBatches = parentBatchIds.Length == 0
5✔
1943
                        ? []
5✔
1944
                        : await context.Set<ImmediateJobBatchEntity>()
5✔
1945
                                .Where(batch => parentBatchIds.Contains(batch.Id))
5✔
NEW
1946
                                .ToDictionaryAsync(batch => batch.Id, StringComparer.Ordinal, cancellationToken)
×
1947
                                .ConfigureAwait(false);
5✔
1948
                var requiresFailure = false;
5✔
1949
                var anyFailed = false;
5✔
1950
                // A missing parent has no success or failure outcome; Complete continuations can still proceed.
1951
                foreach (var edge in edges)
5✔
1952
                {
1953
                        bool succeeded;
1954
                        bool failed;
1955
                        if (edge.ParentKind == ContinuationParentKind.Job)
5✔
1956
                        {
1957
                                var state = parentJobs.TryGetValue(edge.ParentId, out var parentJob) ? parentJob?.State : null;
5✔
1958
                                succeeded = state == JobState.Succeeded;
5✔
1959
                                failed = state == JobState.Failed;
5✔
1960
                        }
1961
                        else
1962
                        {
NEW
1963
                                var state = parentBatches.TryGetValue(edge.ParentId, out var parentBatch) ? parentBatch?.State : null;
×
NEW
1964
                                succeeded = state == BatchState.Succeeded;
×
NEW
1965
                                failed = state == BatchState.Failed;
×
1966
                        }
1967

1968
                        if (edge.Trigger == ContinuationTrigger.Success && !succeeded)
5✔
NEW
1969
                                return true;
×
1970
                        requiresFailure |= edge.Trigger == ContinuationTrigger.Failure;
5✔
1971
                        anyFailed |= failed;
5✔
1972
                }
1973

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

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

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

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

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

2088
                                        if (parentFailed)
1✔
2089
                                                failedDependencies++;
×
2090
                                        if (edge.Trigger == ContinuationTrigger.Success && !parentSucceeded)
1✔
2091
                                                violated = true;
×
2092
                                }
2093

2094
                                job.FailedDependencies = failedDependencies;
5✔
2095
                                if (violated || remaining == 0 && requiresFailure && failedDependencies == 0)
5✔
2096
                                {
2097
                                        job.State = JobState.Cancelled;
×
2098
                                        job.RemainingDependencies = 0;
×
2099
                                        job.CompletedAt = now;
×
2100
                                        changed = true;
×
2101
                                }
2102
                                else if (remaining == 0)
5✔
2103
                                {
2104
                                        job.State = job.DueAt <= now ? JobState.Pending : JobState.Scheduled;
×
2105
                                        job.RemainingDependencies = 0;
×
2106
                                }
2107
                                else
2108
                                {
2109
                                        job.State = JobState.AwaitingContinuation;
5✔
2110
                                        job.RemainingDependencies = remaining;
5✔
2111
                                }
2112
                        }
2113
                }
2114
        }
5✔
2115

2116
        private static (bool Terminal, bool Succeeded, bool Failed) GetParentState(
2117
                ImmediateJobContinuationEntity edge,
2118
                Dictionary<string, ImmediateJobEntity> jobs,
2119
                Dictionary<string, JobState> externalJobs,
2120
                Dictionary<string, BatchState> externalBatches
2121
        )
2122
        {
2123
                if (edge.ParentKind == ContinuationParentKind.Batch)
5✔
2124
                {
2125
                        var state = externalBatches[edge.ParentId];
5✔
2126
                        return (state != BatchState.Executing, state == BatchState.Succeeded, state == BatchState.Failed);
5✔
2127
                }
2128

2129
                var jobState = jobs.TryGetValue(edge.ParentId, out var job) ? job.State : externalJobs[edge.ParentId];
5✔
2130
                return (IsTerminal(jobState), jobState == JobState.Succeeded, jobState == JobState.Failed);
5✔
2131
        }
2132

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

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

2163
                if (visited != jobIds.Count)
5✔
2164
                        throw new ImmediateJobException("The continuation graph contains a dependency cycle.");
×
2165
        }
5✔
2166

2167
        private static bool IsTerminal(JobState state) =>
2168
                state is JobState.Succeeded or JobState.Failed or JobState.Cancelled;
5✔
2169

2170
        private static BatchState GetTerminalBatchState(int failed, int cancelled) =>
2171
                failed != 0 ? BatchState.Failed : cancelled != 0 ? BatchState.Cancelled : BatchState.Succeeded;
5✔
2172

2173
        private async ValueTask MutateRecurringAsync(string name, Action<ImmediateRecurringJobEntity> mutate, CancellationToken cancellationToken)
2174
        {
2175
                ArgumentException.ThrowIfNullOrWhiteSpace(name);
×
2176
                await using var context = await contextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
×
2177
                var schedule = await context.Set<ImmediateRecurringJobEntity>().FindAsync([name], cancellationToken).ConfigureAwait(false);
×
2178
                if (schedule is null)
×
2179
                        return;
2180
                mutate(schedule);
×
2181
                schedule.ConcurrencyStamp = Guid.NewGuid();
×
2182
                _ = await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
×
2183
        }
×
2184

2185
        private static Task<int> UpdateRecurringAsync(
2186
                TContext context,
2187
                RecurringJobSchedule schedule,
2188
                CancellationToken cancellationToken
2189
        )
2190
        {
2191
                var concurrencyStamp = Guid.NewGuid();
5✔
2192
                return context.Set<ImmediateRecurringJobEntity>()
5✔
2193
                        .Where(entity => entity.Name == schedule.Name && (schedule.IsCodeDefined || !entity.IsCodeDefined))
5✔
2194
                        .ExecuteUpdateAsync(setters => setters
5✔
2195
                                .SetProperty(entity => entity.JobName, schedule.JobName)
5✔
2196
                                .SetProperty(entity => entity.Cron, schedule.Cron)
5✔
2197
                                .SetProperty(entity => entity.TimeZone, schedule.TimeZone)
5✔
2198
                                .SetProperty(entity => entity.IsCodeDefined, schedule.IsCodeDefined)
5✔
2199
                                .SetProperty(entity => entity.NextRunAt, schedule.NextRunAt)
5✔
2200
                                .SetProperty(entity => entity.ConcurrencyStamp, concurrencyStamp),
5✔
2201
                                cancellationToken);
5✔
2202
        }
2203

2204
        private static async Task ThrowIfReplacingCodeDefinedScheduleAsync(
2205
                TContext context,
2206
                RecurringJobSchedule schedule,
2207
                CancellationToken cancellationToken
2208
        )
2209
        {
2210
                if (!schedule.IsCodeDefined && await context.Set<ImmediateRecurringJobEntity>()
5✔
2211
                        .AnyAsync(entity => entity.Name == schedule.Name && entity.IsCodeDefined, cancellationToken)
5✔
2212
                        .ConfigureAwait(false))
5✔
2213
                {
2214
                        throw new ImmediateJobException("Code-defined recurring schedules cannot be replaced by dynamic schedules.");
4✔
2215
                }
2216
        }
5✔
2217

2218
        private static ImmediateJobEntity ToEntity(JobRecord job) => new()
5✔
2219
        {
5✔
2220
                Id = job.Id,
5✔
2221
                QueueName = job.QueueName,
5✔
2222
                JobName = job.JobName,
5✔
2223
                GroupId = job.GroupId,
5✔
2224
                Payload = job.Payload,
5✔
2225
                Context = job.Context,
5✔
2226
                State = job.State,
5✔
2227
                DueAt = job.DueAt,
5✔
2228
                CreatedAt = job.CreatedAt,
5✔
2229
                Attempt = job.Attempt,
5✔
2230
                WorkerId = job.WorkerId,
5✔
2231
                LeaseExpiresAt = job.LeaseExpiresAt,
5✔
2232
                LastError = job.LastError,
5✔
2233
                CompletedAt = job.CompletedAt,
5✔
2234
                RecurringKey = job.RecurringKey,
5✔
2235
                TraceParent = job.TraceParent,
5✔
2236
                TraceState = job.TraceState,
5✔
2237
                ExecutionTraceId = job.ExecutionTraceId,
5✔
2238
                ExecutionSpanId = job.ExecutionSpanId,
5✔
2239
                ExecutionStartedAt = job.ExecutionStartedAt,
5✔
2240
                BatchId = job.BatchId,
5✔
2241
                RemainingDependencies = job.RemainingDependencies,
5✔
2242
                FailedDependencies = job.FailedDependencies,
5✔
2243
                ConcurrencyStamp = Guid.NewGuid(),
5✔
2244
        };
5✔
2245

2246
        private static ImmediateJobContinuationEntity ToEntity(JobContinuationEdge edge)
2247
        {
2248
                var hasJobParent = edge.ParentJobId is not null;
5✔
2249
                var hasBatchParent = edge.ParentBatchId is not null;
5✔
2250
                if (hasJobParent == hasBatchParent)
5✔
2251
                        throw new ImmediateJobException("A continuation edge must identify exactly one parent job or batch.");
×
2252
                return new()
5✔
2253
                {
5✔
2254
                        ChildJobId = edge.ChildJobId,
5✔
2255
                        ParentKind = hasJobParent ? ContinuationParentKind.Job : ContinuationParentKind.Batch,
5✔
2256
                        ParentId = edge.ParentJobId ?? edge.ParentBatchId!,
5✔
2257
                        Trigger = edge.Trigger,
5✔
2258
                };
5✔
2259
        }
2260

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

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

2316
        private static BatchStatus ToStatus(ImmediateJobBatchEntity batch) => new(
5✔
2317
                batch.Id,
5✔
2318
                batch.State,
5✔
2319
                batch.TotalJobs,
5✔
2320
                batch.SucceededCount,
5✔
2321
                batch.FailedCount,
5✔
2322
                batch.CancelledCount,
5✔
2323
                batch.PendingCount,
5✔
2324
                batch.CreatedAt,
5✔
2325
                batch.StartedAt,
5✔
2326
                batch.CompletedAt,
5✔
2327
                BatchStatus.CalculateFractionSettled(batch.TotalJobs, batch.PendingCount)
5✔
2328
        );
5✔
2329

2330
        private static JobContinuationEdge ToContinuationEdge(ImmediateJobContinuationEntity edge) => new()
5✔
2331
        {
5✔
2332
                ChildJobId = edge.ChildJobId,
5✔
2333
                ParentJobId = edge.ParentKind == ContinuationParentKind.Job ? edge.ParentId : null,
5✔
2334
                ParentBatchId = edge.ParentKind == ContinuationParentKind.Batch ? edge.ParentId : null,
5✔
2335
                Trigger = edge.Trigger,
5✔
2336
        };
5✔
2337

2338
        private static BatchGraphEdge ToGraphEdge(ImmediateJobContinuationEntity edge) => new(
5✔
2339
                edge.ChildJobId,
5✔
2340
                edge.ParentKind == ContinuationParentKind.Job ? edge.ParentId : null,
5✔
2341
                edge.ParentKind == ContinuationParentKind.Batch ? edge.ParentId : null,
5✔
2342
                edge.Trigger
5✔
2343
        );
5✔
2344

2345
        private static ImmediateRecurringJobEntity ToEntity(RecurringJobSchedule schedule) => new()
5✔
2346
        {
5✔
2347
                Name = schedule.Name,
5✔
2348
                JobName = schedule.JobName,
5✔
2349
                Cron = schedule.Cron,
5✔
2350
                TimeZone = schedule.TimeZone,
5✔
2351
                IsCodeDefined = schedule.IsCodeDefined,
5✔
2352
                IsPaused = schedule.IsPaused,
5✔
2353
                NextRunAt = schedule.NextRunAt,
5✔
2354
                LastRunAt = schedule.LastRunAt,
5✔
2355
                ConcurrencyStamp = Guid.NewGuid(),
5✔
2356
        };
5✔
2357
}
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