| | | 1 | | using Anichron.Core.Data; |
| | | 2 | | using Anichron.Core.Domain; |
| | | 3 | | using Anichron.Core.Work; |
| | | 4 | | using Microsoft.EntityFrameworkCore; |
| | | 5 | | using NodaTime; |
| | | 6 | | using Npgsql; |
| | | 7 | | |
| | | 8 | | namespace Anichron.Worker.Work; |
| | | 9 | | |
| | 12 | 10 | | public 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) |
| | 0 | 20 | | { |
| | 0 | 21 | | await using var db = await contexts.CreateDbContextAsync(ct); |
| | 0 | 22 | | var leaseUntil = now + lease; |
| | 0 | 23 | | var kinds = Enum.GetNames<WorkKind>(); |
| | | 24 | | List<ClaimRow> rows; |
| | | 25 | | try |
| | 0 | 26 | | { |
| | 0 | 27 | | rows = await db.Database.SqlQuery<ClaimRow>($""" |
| | 0 | 28 | | UPDATE "WorkItems" |
| | 0 | 29 | | SET "Status" = 'Running', "Attempt" = "Attempt" + 1, "ClaimedBy" = {claimedBy}, |
| | 0 | 30 | | "StartedAt" = {now}, "LeaseUntil" = {leaseUntil}, "UpdatedAt" = {now}, |
| | 0 | 31 | | "ProgressDone" = 0, "ProgressTotal" = NULL, "ProgressNote" = NULL |
| | 0 | 32 | | WHERE "Id" = ( |
| | 0 | 33 | | SELECT q."Id" FROM "WorkItems" q |
| | 0 | 34 | | WHERE q."Status" = 'Queued' AND q."Kind" = ANY({kinds}) |
| | 0 | 35 | | AND (q."StorageConfigId" IS NULL |
| | 0 | 36 | | OR CAST({servedUserId} AS uuid) IS NULL |
| | 0 | 37 | | OR q."StorageConfigId" IN ( |
| | 0 | 38 | | SELECT "Id" FROM "StorageConfigs" WHERE "UserId" = CAST({servedUserId} AS uuid))) |
| | 0 | 39 | | AND NOT EXISTS ( |
| | 0 | 40 | | SELECT 1 FROM "WorkItems" r |
| | 0 | 41 | | WHERE r."Status" = 'Running' AND r."StorageConfigId" = q."StorageConfigId") |
| | 0 | 42 | | ORDER BY q."RequestedAt", q."Id" |
| | 0 | 43 | | LIMIT 1 |
| | 0 | 44 | | FOR UPDATE SKIP LOCKED) |
| | 0 | 45 | | RETURNING "Id", "Kind", "Payload", "Attempt" |
| | 0 | 46 | | """).ToListAsync(ct); |
| | 0 | 47 | | } |
| | 0 | 48 | | catch (Exception ex) when (IsViolationOf(ex, WorkItemIndexNames.RunningStorageConfigUnique)) |
| | 0 | 49 | | { |
| | 0 | 50 | | return null; |
| | | 51 | | } |
| | | 52 | | |
| | 0 | 53 | | return rows is [var row] |
| | 0 | 54 | | ? new ClaimedWork(new WorkAttempt(row.Id, row.Attempt), Enum.Parse<WorkKind>(row.Kind), row.Payload) |
| | 0 | 55 | | : null; |
| | 0 | 56 | | } |
| | | 57 | | |
| | | 58 | | // Stryker disable all |
| | | 59 | | public async Task<HeartbeatOutcome> HeartbeatAsync( |
| | | 60 | | WorkAttempt attempt, WorkProgress progress, Instant now, Duration lease, CancellationToken ct) |
| | 0 | 61 | | { |
| | 0 | 62 | | await using var db = await contexts.CreateDbContextAsync(ct); |
| | 0 | 63 | | var leaseUntil = now + lease; |
| | 0 | 64 | | var cancelRequested = await db.Database.SqlQuery<bool>($""" |
| | 0 | 65 | | UPDATE "WorkItems" |
| | 0 | 66 | | SET "LeaseUntil" = {leaseUntil}, "ProgressDone" = {progress.Done}, |
| | 0 | 67 | | "ProgressTotal" = CAST({progress.Total} AS bigint), "ProgressNote" = CAST({progress.Note} AS text), |
| | 0 | 68 | | "UpdatedAt" = CASE |
| | 0 | 69 | | WHEN "ProgressDone" = {progress.Done} |
| | 0 | 70 | | AND "ProgressTotal" IS NOT DISTINCT FROM CAST({progress.Total} AS bigint) |
| | 0 | 71 | | AND "ProgressNote" IS NOT DISTINCT FROM CAST({progress.Note} AS text) |
| | 0 | 72 | | THEN "UpdatedAt" ELSE {now} END |
| | 0 | 73 | | WHERE "Id" = {attempt.Id} AND "Attempt" = {attempt.Attempt} AND "Status" = 'Running' |
| | 0 | 74 | | RETURNING "CancelRequestedAt" IS NOT NULL AS "Value" |
| | 0 | 75 | | """).ToListAsync(ct); |
| | 0 | 76 | | return cancelRequested switch |
| | 0 | 77 | | { |
| | 0 | 78 | | [] => HeartbeatOutcome.Lost, |
| | 0 | 79 | | [true] => HeartbeatOutcome.CancelRequested, |
| | 0 | 80 | | _ => HeartbeatOutcome.Held, |
| | 0 | 81 | | }; |
| | 0 | 82 | | } |
| | | 83 | | |
| | | 84 | | public Task SucceedAsync( |
| | | 85 | | WorkAttempt attempt, WorkProgress progress, string? result, Instant now, CancellationToken ct) |
| | 0 | 86 | | => 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) |
| | 0 | 90 | | => 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) |
| | 0 | 94 | | => 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) |
| | 0 | 105 | | { |
| | 0 | 106 | | await using var db = await contexts.CreateDbContextAsync(ct); |
| | 0 | 107 | | await Running(db, attempt).ExecuteUpdateAsync(s => s |
| | 0 | 108 | | .SetProperty(w => w.Status, status) |
| | 0 | 109 | | .SetProperty(w => w.ProgressDone, progress.Done) |
| | 0 | 110 | | .SetProperty(w => w.ProgressTotal, progress.Total) |
| | 0 | 111 | | .SetProperty(w => w.ProgressNote, progress.Note) |
| | 0 | 112 | | .SetProperty(w => w.Result, result) |
| | 0 | 113 | | .SetProperty(w => w.Error, error) |
| | 0 | 114 | | .SetProperty(w => w.FinishedAt, now) |
| | 0 | 115 | | .SetProperty(w => w.UpdatedAt, now), ct); |
| | 0 | 116 | | } |
| | | 117 | | |
| | | 118 | | // Stryker disable all |
| | | 119 | | public async Task ReleaseAsync(WorkAttempt attempt, Instant now, CancellationToken ct) |
| | 0 | 120 | | { |
| | 0 | 121 | | await using var db = await contexts.CreateDbContextAsync(ct); |
| | 0 | 122 | | await ReturnToQueueAsync(db, attempt, expiredBefore: null, stall: 0, now, ct); |
| | 0 | 123 | | } |
| | | 124 | | |
| | | 125 | | // Stryker disable all |
| | | 126 | | public async Task RecoverExpiredLeasesAsync(Instant now, int maxStalls, CancellationToken ct) |
| | 0 | 127 | | { |
| | 0 | 128 | | await using var db = await contexts.CreateDbContextAsync(ct); |
| | 0 | 129 | | await Expired(db, now).Where(w => w.Stalls + 1 >= maxStalls && w.CancelRequestedAt == null).ExecuteUpdateAsync(s |
| | 0 | 130 | | .SetProperty(w => w.Status, WorkItemStatus.Failed) |
| | 0 | 131 | | .SetProperty(w => w.Stalls, w => w.Stalls + 1) |
| | 0 | 132 | | .SetProperty(w => w.Error, StalledError) |
| | 0 | 133 | | .SetProperty(w => w.FinishedAt, now) |
| | 0 | 134 | | .SetProperty(w => w.UpdatedAt, now), ct); |
| | 0 | 135 | | var expired = await Expired(db, now).Select(w => new WorkAttempt(w.Id, w.Attempt)).ToListAsync(ct); |
| | 0 | 136 | | foreach (var attempt in expired) |
| | 0 | 137 | | await ReturnToQueueAsync(db, attempt, expiredBefore: now, stall: 1, now, ct); |
| | 0 | 138 | | } |
| | | 139 | | |
| | | 140 | | // Stryker disable all |
| | | 141 | | private static async Task ReturnToQueueAsync( |
| | | 142 | | AnichronDbContext db, WorkAttempt attempt, Instant? expiredBefore, int stall, Instant now, CancellationToken ct) |
| | 0 | 143 | | { |
| | 0 | 144 | | var running = Running(db, attempt); |
| | 0 | 145 | | if (expiredBefore is { } before) |
| | 0 | 146 | | running = running.Where(w => w.LeaseUntil < before); |
| | | 147 | | |
| | 0 | 148 | | for (var tries = 0; tries < 3; tries++) |
| | 0 | 149 | | { |
| | 0 | 150 | | if (await TryReturnToQueueOnceAsync(running, db, stall, now, ct)) |
| | 0 | 151 | | return; |
| | 0 | 152 | | } |
| | | 153 | | |
| | 0 | 154 | | throw new InvalidOperationException( |
| | 0 | 155 | | $"Work item {attempt.Id} kept colliding with a queued item while returning to the queue."); |
| | 0 | 156 | | } |
| | | 157 | | |
| | | 158 | | // Stryker disable all |
| | | 159 | | private static async Task<bool> TryReturnToQueueOnceAsync( |
| | | 160 | | IQueryable<WorkItem> running, AnichronDbContext db, int stall, Instant now, CancellationToken ct) |
| | 0 | 161 | | { |
| | | 162 | | try |
| | 0 | 163 | | { |
| | 0 | 164 | | var requeued = await running |
| | 0 | 165 | | .Where(w => w.CancelRequestedAt == null && !db.WorkItems.Any(q => |
| | 0 | 166 | | q.Status == WorkItemStatus.Queued && q.DedupKey != null && q.DedupKey == w.DedupKey)) |
| | 0 | 167 | | .ExecuteUpdateAsync(s => s |
| | 0 | 168 | | .SetProperty(w => w.Status, WorkItemStatus.Queued) |
| | 0 | 169 | | .SetProperty(w => w.Stalls, w => w.Stalls + stall) |
| | 0 | 170 | | .SetProperty(w => w.ClaimedBy, (string?)null) |
| | 0 | 171 | | .SetProperty(w => w.StartedAt, (Instant?)null) |
| | 0 | 172 | | .SetProperty(w => w.LeaseUntil, (Instant?)null) |
| | 0 | 173 | | .SetProperty(w => w.UpdatedAt, now), ct); |
| | 0 | 174 | | if (requeued == 0) |
| | 0 | 175 | | { |
| | 0 | 176 | | await running.ExecuteUpdateAsync(s => s |
| | 0 | 177 | | .SetProperty(w => w.Status, WorkItemStatus.Cancelled) |
| | 0 | 178 | | .SetProperty(w => w.Stalls, w => w.Stalls + stall) |
| | 0 | 179 | | .SetProperty(w => w.Error, w => w.CancelRequestedAt == null ? SupersededError : null) |
| | 0 | 180 | | .SetProperty(w => w.FinishedAt, now) |
| | 0 | 181 | | .SetProperty(w => w.UpdatedAt, now), ct); |
| | 0 | 182 | | } |
| | | 183 | | |
| | 0 | 184 | | return true; |
| | | 185 | | } |
| | 0 | 186 | | catch (Exception ex) when (IsViolationOf(ex, WorkItemIndexNames.QueuedDedupKeyUnique)) |
| | 0 | 187 | | { |
| | 0 | 188 | | return false; |
| | | 189 | | } |
| | 0 | 190 | | } |
| | | 191 | | |
| | | 192 | | // Stryker disable all |
| | | 193 | | private static bool IsViolationOf(Exception ex, string index) |
| | 0 | 194 | | => (ex as PostgresException ?? ex.InnerException as PostgresException) is |
| | 0 | 195 | | { |
| | 0 | 196 | | SqlState: PostgresErrorCodes.UniqueViolation, |
| | 0 | 197 | | } violation && violation.ConstraintName == index; |
| | | 198 | | |
| | | 199 | | public async Task<bool> IsDueAsync(string dedupKey, Instant finishedBefore, CancellationToken ct) |
| | 11 | 200 | | { |
| | 11 | 201 | | await using var db = await contexts.CreateDbContextAsync(ct); |
| | 11 | 202 | | return !await db.WorkItems.AnyAsync(w => w.DedupKey == dedupKey |
| | 11 | 203 | | && (w.Status == WorkItemStatus.Queued |
| | 11 | 204 | | || w.Status == WorkItemStatus.Running |
| | 11 | 205 | | || w.FinishedAt > finishedBefore), ct); |
| | 11 | 206 | | } |
| | | 207 | | |
| | | 208 | | // Stryker disable all |
| | | 209 | | public async Task<int> DeleteFinishedBeforeAsync(Instant cutoff, CancellationToken ct) |
| | 0 | 210 | | { |
| | 0 | 211 | | await using var db = await contexts.CreateDbContextAsync(ct); |
| | 0 | 212 | | return await db.WorkItems.Where(w => w.FinishedAt < cutoff).ExecuteDeleteAsync(ct); |
| | 0 | 213 | | } |
| | | 214 | | |
| | | 215 | | // Stryker disable all |
| | | 216 | | private static IQueryable<WorkItem> Running(AnichronDbContext db, WorkAttempt attempt) |
| | 0 | 217 | | => db.WorkItems.Where(w => |
| | 0 | 218 | | 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) |
| | 0 | 222 | | => db.WorkItems.Where(w => w.Status == WorkItemStatus.Running && w.LeaseUntil < now); |
| | | 223 | | } |