< Summary

Information
Class: Anichron.Worker.Work.EfWorkItemStore
Assembly: Anichron.Worker
File(s): /home/runner/work/anichron/anichron/src/Anichron.Worker/Work/EfWorkItemStore.cs
Tag: 19_45211875487
Line coverage
5%
Covered lines: 8
Uncovered lines: 135
Coverable lines: 143
Total lines: 223
Line coverage: 5.5%
Branch coverage
0%
Covered branches: 0
Total branches: 30
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
ClaimAsync()0%2040%
HeartbeatAsync()0%7280%
SucceedAsync(...)100%210%
FailAsync(...)100%210%
CancelAsync(...)100%210%
FinishAsync()100%210%
ReleaseAsync()100%210%
RecoverExpiredLeasesAsync()0%620%
ReturnToQueueAsync()0%7280%
TryReturnToQueueOnceAsync()0%620%
IsViolationOf(...)0%4260%
IsDueAsync()100%11100%
DeleteFinishedBeforeAsync()100%210%
Running(...)100%210%
Expired(...)100%210%

File(s)

/home/runner/work/anichron/anichron/src/Anichron.Worker/Work/EfWorkItemStore.cs

#LineLine coverage
 1using Anichron.Core.Data;
 2using Anichron.Core.Domain;
 3using Anichron.Core.Work;
 4using Microsoft.EntityFrameworkCore;
 5using NodaTime;
 6using Npgsql;
 7
 8namespace Anichron.Worker.Work;
 9
 1210public sealed class EfWorkItemStore(IDbContextFactory<AnichronDbContext> contexts) : IWorkItemStore
 11{
 12    internal const string StalledError = "Stalled: the lease expired without a heartbeat too many times.";
 13    internal const string SupersededError = "Superseded by the queued item with the same dedup key.";
 14
 15    private sealed record ClaimRow(Guid Id, string Kind, string Payload, int Attempt);
 16
 17    // Stryker disable all
 18    public async Task<ClaimedWork?> ClaimAsync(
 19        string claimedBy, Guid? servedUserId, Instant now, Duration lease, CancellationToken ct)
 020    {
 021        await using var db = await contexts.CreateDbContextAsync(ct);
 022        var leaseUntil = now + lease;
 023        var kinds = Enum.GetNames<WorkKind>();
 24        List<ClaimRow> rows;
 25        try
 026        {
 027            rows = await db.Database.SqlQuery<ClaimRow>($"""
 028                UPDATE "WorkItems"
 029                SET "Status" = 'Running', "Attempt" = "Attempt" + 1, "ClaimedBy" = {claimedBy},
 030                    "StartedAt" = {now}, "LeaseUntil" = {leaseUntil}, "UpdatedAt" = {now},
 031                    "ProgressDone" = 0, "ProgressTotal" = NULL, "ProgressNote" = NULL
 032                WHERE "Id" = (
 033                    SELECT q."Id" FROM "WorkItems" q
 034                    WHERE q."Status" = 'Queued' AND q."Kind" = ANY({kinds})
 035                      AND (q."StorageConfigId" IS NULL
 036                        OR CAST({servedUserId} AS uuid) IS NULL
 037                        OR q."StorageConfigId" IN (
 038                            SELECT "Id" FROM "StorageConfigs" WHERE "UserId" = CAST({servedUserId} AS uuid)))
 039                      AND NOT EXISTS (
 040                        SELECT 1 FROM "WorkItems" r
 041                        WHERE r."Status" = 'Running' AND r."StorageConfigId" = q."StorageConfigId")
 042                    ORDER BY q."RequestedAt", q."Id"
 043                    LIMIT 1
 044                    FOR UPDATE SKIP LOCKED)
 045                RETURNING "Id", "Kind", "Payload", "Attempt"
 046                """).ToListAsync(ct);
 047        }
 048        catch (Exception ex) when (IsViolationOf(ex, WorkItemIndexNames.RunningStorageConfigUnique))
 049        {
 050            return null;
 51        }
 52
 053        return rows is [var row]
 054            ? new ClaimedWork(new WorkAttempt(row.Id, row.Attempt), Enum.Parse<WorkKind>(row.Kind), row.Payload)
 055            : null;
 056    }
 57
 58    // Stryker disable all
 59    public async Task<HeartbeatOutcome> HeartbeatAsync(
 60        WorkAttempt attempt, WorkProgress progress, Instant now, Duration lease, CancellationToken ct)
 061    {
 062        await using var db = await contexts.CreateDbContextAsync(ct);
 063        var leaseUntil = now + lease;
 064        var cancelRequested = await db.Database.SqlQuery<bool>($"""
 065            UPDATE "WorkItems"
 066            SET "LeaseUntil" = {leaseUntil}, "ProgressDone" = {progress.Done},
 067                "ProgressTotal" = CAST({progress.Total} AS bigint), "ProgressNote" = CAST({progress.Note} AS text),
 068                "UpdatedAt" = CASE
 069                    WHEN "ProgressDone" = {progress.Done}
 070                      AND "ProgressTotal" IS NOT DISTINCT FROM CAST({progress.Total} AS bigint)
 071                      AND "ProgressNote" IS NOT DISTINCT FROM CAST({progress.Note} AS text)
 072                    THEN "UpdatedAt" ELSE {now} END
 073            WHERE "Id" = {attempt.Id} AND "Attempt" = {attempt.Attempt} AND "Status" = 'Running'
 074            RETURNING "CancelRequestedAt" IS NOT NULL AS "Value"
 075            """).ToListAsync(ct);
 076        return cancelRequested switch
 077        {
 078            [] => HeartbeatOutcome.Lost,
 079            [true] => HeartbeatOutcome.CancelRequested,
 080            _ => HeartbeatOutcome.Held,
 081        };
 082    }
 83
 84    public Task SucceedAsync(
 85        WorkAttempt attempt, WorkProgress progress, string? result, Instant now, CancellationToken ct)
 086        => FinishAsync(attempt, WorkItemStatus.Succeeded, progress, result, error: null, now, ct);
 87
 88    public Task FailAsync(
 89        WorkAttempt attempt, WorkProgress progress, string error, Instant now, CancellationToken ct)
 090        => FinishAsync(attempt, WorkItemStatus.Failed, progress, result: null, error, now, ct);
 91
 92    public Task CancelAsync(
 93        WorkAttempt attempt, WorkProgress progress, string? result, Instant now, CancellationToken ct)
 094        => FinishAsync(attempt, WorkItemStatus.Cancelled, progress, result, error: null, now, ct);
 95
 96    // Stryker disable all
 97    private async Task FinishAsync(
 98        WorkAttempt attempt,
 99        WorkItemStatus status,
 100        WorkProgress progress,
 101        string? result,
 102        string? error,
 103        Instant now,
 104        CancellationToken ct)
 0105    {
 0106        await using var db = await contexts.CreateDbContextAsync(ct);
 0107        await Running(db, attempt).ExecuteUpdateAsync(s => s
 0108            .SetProperty(w => w.Status, status)
 0109            .SetProperty(w => w.ProgressDone, progress.Done)
 0110            .SetProperty(w => w.ProgressTotal, progress.Total)
 0111            .SetProperty(w => w.ProgressNote, progress.Note)
 0112            .SetProperty(w => w.Result, result)
 0113            .SetProperty(w => w.Error, error)
 0114            .SetProperty(w => w.FinishedAt, now)
 0115            .SetProperty(w => w.UpdatedAt, now), ct);
 0116    }
 117
 118    // Stryker disable all
 119    public async Task ReleaseAsync(WorkAttempt attempt, Instant now, CancellationToken ct)
 0120    {
 0121        await using var db = await contexts.CreateDbContextAsync(ct);
 0122        await ReturnToQueueAsync(db, attempt, expiredBefore: null, stall: 0, now, ct);
 0123    }
 124
 125    // Stryker disable all
 126    public async Task RecoverExpiredLeasesAsync(Instant now, int maxStalls, CancellationToken ct)
 0127    {
 0128        await using var db = await contexts.CreateDbContextAsync(ct);
 0129        await Expired(db, now).Where(w => w.Stalls + 1 >= maxStalls && w.CancelRequestedAt == null).ExecuteUpdateAsync(s
 0130            .SetProperty(w => w.Status, WorkItemStatus.Failed)
 0131            .SetProperty(w => w.Stalls, w => w.Stalls + 1)
 0132            .SetProperty(w => w.Error, StalledError)
 0133            .SetProperty(w => w.FinishedAt, now)
 0134            .SetProperty(w => w.UpdatedAt, now), ct);
 0135        var expired = await Expired(db, now).Select(w => new WorkAttempt(w.Id, w.Attempt)).ToListAsync(ct);
 0136        foreach (var attempt in expired)
 0137            await ReturnToQueueAsync(db, attempt, expiredBefore: now, stall: 1, now, ct);
 0138    }
 139
 140    // Stryker disable all
 141    private static async Task ReturnToQueueAsync(
 142        AnichronDbContext db, WorkAttempt attempt, Instant? expiredBefore, int stall, Instant now, CancellationToken ct)
 0143    {
 0144        var running = Running(db, attempt);
 0145        if (expiredBefore is { } before)
 0146            running = running.Where(w => w.LeaseUntil < before);
 147
 0148        for (var tries = 0; tries < 3; tries++)
 0149        {
 0150            if (await TryReturnToQueueOnceAsync(running, db, stall, now, ct))
 0151                return;
 0152        }
 153
 0154        throw new InvalidOperationException(
 0155            $"Work item {attempt.Id} kept colliding with a queued item while returning to the queue.");
 0156    }
 157
 158    // Stryker disable all
 159    private static async Task<bool> TryReturnToQueueOnceAsync(
 160        IQueryable<WorkItem> running, AnichronDbContext db, int stall, Instant now, CancellationToken ct)
 0161    {
 162        try
 0163        {
 0164            var requeued = await running
 0165                .Where(w => w.CancelRequestedAt == null && !db.WorkItems.Any(q =>
 0166                    q.Status == WorkItemStatus.Queued && q.DedupKey != null && q.DedupKey == w.DedupKey))
 0167                .ExecuteUpdateAsync(s => s
 0168                    .SetProperty(w => w.Status, WorkItemStatus.Queued)
 0169                    .SetProperty(w => w.Stalls, w => w.Stalls + stall)
 0170                    .SetProperty(w => w.ClaimedBy, (string?)null)
 0171                    .SetProperty(w => w.StartedAt, (Instant?)null)
 0172                    .SetProperty(w => w.LeaseUntil, (Instant?)null)
 0173                    .SetProperty(w => w.UpdatedAt, now), ct);
 0174            if (requeued == 0)
 0175            {
 0176                await running.ExecuteUpdateAsync(s => s
 0177                    .SetProperty(w => w.Status, WorkItemStatus.Cancelled)
 0178                    .SetProperty(w => w.Stalls, w => w.Stalls + stall)
 0179                    .SetProperty(w => w.Error, w => w.CancelRequestedAt == null ? SupersededError : null)
 0180                    .SetProperty(w => w.FinishedAt, now)
 0181                    .SetProperty(w => w.UpdatedAt, now), ct);
 0182            }
 183
 0184            return true;
 185        }
 0186        catch (Exception ex) when (IsViolationOf(ex, WorkItemIndexNames.QueuedDedupKeyUnique))
 0187        {
 0188            return false;
 189        }
 0190    }
 191
 192    // Stryker disable all
 193    private static bool IsViolationOf(Exception ex, string index)
 0194        => (ex as PostgresException ?? ex.InnerException as PostgresException) is
 0195        {
 0196            SqlState: PostgresErrorCodes.UniqueViolation,
 0197        } violation && violation.ConstraintName == index;
 198
 199    public async Task<bool> IsDueAsync(string dedupKey, Instant finishedBefore, CancellationToken ct)
 11200    {
 11201        await using var db = await contexts.CreateDbContextAsync(ct);
 11202        return !await db.WorkItems.AnyAsync(w => w.DedupKey == dedupKey
 11203            && (w.Status == WorkItemStatus.Queued
 11204                || w.Status == WorkItemStatus.Running
 11205                || w.FinishedAt > finishedBefore), ct);
 11206    }
 207
 208    // Stryker disable all
 209    public async Task<int> DeleteFinishedBeforeAsync(Instant cutoff, CancellationToken ct)
 0210    {
 0211        await using var db = await contexts.CreateDbContextAsync(ct);
 0212        return await db.WorkItems.Where(w => w.FinishedAt < cutoff).ExecuteDeleteAsync(ct);
 0213    }
 214
 215    // Stryker disable all
 216    private static IQueryable<WorkItem> Running(AnichronDbContext db, WorkAttempt attempt)
 0217        => db.WorkItems.Where(w =>
 0218            w.Id == attempt.Id && w.Attempt == attempt.Attempt && w.Status == WorkItemStatus.Running);
 219
 220    // Stryker disable all
 221    private static IQueryable<WorkItem> Expired(AnichronDbContext db, Instant now)
 0222        => db.WorkItems.Where(w => w.Status == WorkItemStatus.Running && w.LeaseUntil < now);
 223}