< Summary

Information
Class: Anichron.Core.Work.EfWorkQueue
Assembly: Anichron.Core
File(s): /home/runner/work/anichron/anichron/src/Anichron.Core/Work/WorkQueue.cs
Tag: 19_45211875487
Line coverage
100%
Covered lines: 43
Uncovered lines: 0
Coverable lines: 43
Total lines: 78
Line coverage: 100%
Branch coverage
100%
Covered branches: 10
Total branches: 10
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
EnqueueAsync()100%1010100%
TryInsertAsync()100%11100%

File(s)

/home/runner/work/anichron/anichron/src/Anichron.Core/Work/WorkQueue.cs

#LineLine coverage
 1using Anichron.Core.Data;
 2using Anichron.Core.Domain;
 3using Microsoft.EntityFrameworkCore;
 4
 5namespace Anichron.Core.Work;
 6
 7public interface IWorkQueue
 8{
 9    /// <summary>
 10    /// Adds a queued item, or returns the id of the queued item that already holds the payload's
 11    /// dedup key. Saves at once, so call it on a context with no other pending changes.
 12    /// </summary>
 13    /// <typeparam name="TPayload">The payload type, which names the kind.</typeparam>
 14    /// <param name="payload">What the handler receives.</param>
 15    /// <param name="requestedBy">The requesting admin, or null when scheduled.</param>
 16    /// <param name="ct">Cancels the enqueue.</param>
 17    /// <returns>The id of the queued item.</returns>
 18    Task<Guid> EnqueueAsync<TPayload>(TPayload payload, Guid? requestedBy, CancellationToken ct)
 19        where TPayload : IWorkPayload;
 20}
 21
 2022public sealed class EfWorkQueue(AnichronDbContext db, IClock clock, IGuidFactory guids) : IWorkQueue
 23{
 24    internal const int MaxInsertAttempts = 3;
 25
 26    public async Task<Guid> EnqueueAsync<TPayload>(TPayload payload, Guid? requestedBy, CancellationToken ct)
 27        where TPayload : IWorkPayload
 1928    {
 1929        var dedupKey = payload.DedupKey;
 4830        for (var attempt = 1; attempt <= MaxInsertAttempts; attempt++)
 2331        {
 2332            if (dedupKey is not null)
 1933            {
 1934                var waiting = await db.WorkItems
 1935                    .Where(w => w.DedupKey == dedupKey && w.Status == WorkItemStatus.Queued)
 1936                    .Select(w => (Guid?)w.Id)
 1937                    .FirstOrDefaultAsync(ct);
 1938                if (waiting is { } id)
 139                    return id;
 1840            }
 41
 2242            var now = clock.GetCurrentInstant();
 2243            var item = new WorkItem
 2244            {
 2245                Id = guids.NewGuid(),
 2246                Kind = TPayload.Kind,
 2247                Payload = WorkJson.Serialize(payload),
 2248                DedupKey = dedupKey,
 2249                StorageConfigId = payload.StorageConfigId,
 2250                RequestedBy = requestedBy,
 2251                RequestedAt = now,
 2252                Status = WorkItemStatus.Queued,
 2253                UpdatedAt = now,
 2254            };
 2255            if (await TryInsertAsync(item, ct))
 1756                return item.Id;
 557        }
 58
 159        throw new InvalidOperationException(
 160            $"Enqueueing work with dedup key '{dedupKey}' lost the insert race {MaxInsertAttempts} times.");
 1861    }
 62
 63    // Stryker disable all
 64    private async Task<bool> TryInsertAsync(WorkItem item, CancellationToken ct)
 2265    {
 2266        db.WorkItems.Add(item);
 67        try
 2268        {
 2269            await db.SaveChangesAsync(ct);
 1770            return true;
 71        }
 572        catch (DbUpdateException ex) when (ex.IsUniqueViolation(WorkItemIndexNames.QueuedDedupKeyUnique))
 573        {
 574            db.Entry(item).State = EntityState.Detached;
 575            return false;
 76        }
 2277    }
 78}