Build ErsatzTV Image / CI image pin matches docker/ci (pull_request) Successful in 8s
Build ErsatzTV Image / API docs in sync (OpenAPI + endpoint index) (pull_request) Successful in 12s
Build ErsatzTV Image / Docs update reminder (pull_request) Successful in 8s
Build ErsatzTV Image / decisions.md append-only (pull_request) Successful in 40s
Build ErsatzTV Image / Formatting (changed .cs conform to .editorconfig) (pull_request) Successful in 7m25s
Build ErsatzTV Image / Functional E2E (curl contracts) (pull_request) Successful in 14m59s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 19m3s
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 19m47s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
Two concurrent adds of the same item both membership-check it absent, both insert the CollectionItem composite key, and the loser's SaveChangesForcingVersion threw an uncaught DbUpdateException (SQLite 19 / MySQL 1062) -> 500. Now the loser is an idempotent no-op. - ConcurrencyExtensions.TrySaveChangesForcingVersion: bool-returning sibling that catches only a classified unique/PK violation and returns false. - 10 single-item Add*ToCollection handlers: return Unit.Default (no-op, skip fan-out) on false — the racing winner already inserted + rotated + rebuilt. - Bulk AddItemsToCollection: retry on a fresh context against recomputed membership so a partial-overlap collision doesn't drop the non-colliding items (bounded loop; common no-collision path runs once). - Provider detection via a TvContext.IsUniqueConstraintViolation static delegate (matches the existing IsSqlite/LastInsertedRowId provider seam), wired from Startup to SqliteErrorClassifier / MySqlErrorClassifier. - Add*ToPlaylist is NOT affected (PlaylistItem has its own identity PK; a playlist may legitimately contain the same item more than once). Tests: a negative-control anchor proves the race genuinely throws a classified exception; end-to-end handler tests reproduce a real cross-connection race via a shared-cache SQLite harness + a SavingChanges interceptor (the single-conn in-memory fixture cannot). Every fix-dependent test verified to fail with the catch disabled. Docs: api-conventions.md §7a (idempotent insert under concurrency) + decisions/optimistic-concurrency.md. fixes #308 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
125 lines
6.0 KiB
C#
125 lines
6.0 KiB
C#
using ErsatzTV.Core;
|
|
using ErsatzTV.Core.Domain;
|
|
using ErsatzTV.Core.Errors;
|
|
using ErsatzTV.Infrastructure.Data;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.EntityFrameworkCore.ChangeTracking;
|
|
|
|
namespace ErsatzTV.Application;
|
|
|
|
public static class ConcurrencyExtensions
|
|
{
|
|
/// <summary>
|
|
/// Persist changes that touch a versioned root but do <b>not</b> participate in the If-Match
|
|
/// contract (e.g. a playout's settings/schedule-file/on-demand-checkpoint writer, a collection's
|
|
/// name edit). Because the root's <c>Version</c> is an <c>IsConcurrencyToken</c>, EF guards every
|
|
/// UPDATE of that row with <c>WHERE Version=@orig</c>, so a concurrent bump from a replace-all
|
|
/// editor would otherwise surface as an unhandled <see cref="DbUpdateConcurrencyException" /> →
|
|
/// 500 (issue #253 / #269). Phase-1 semantics for a missing <c>If-Match</c> is <b>force-write</b>,
|
|
/// so on a concurrency failure we rebase onto the stored token: original becomes the stored value
|
|
/// (the retry's WHERE then matches) and current becomes stored + our pending delta (a bumper's ++
|
|
/// still advances the ETag past the concurrent writer's value — #269 rotation; a non-bumper adopts
|
|
/// it unchanged) and retry; our own modified scalars still win. Bounded to avoid a livelock; if the row
|
|
/// was deleted out from under us, that's a genuine conflict and rethrows.
|
|
/// </summary>
|
|
public static async Task<int> SaveChangesForcingVersion(
|
|
this DbContext dbContext,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
for (var attempt = 0; ; attempt++)
|
|
{
|
|
try
|
|
{
|
|
return await dbContext.SaveChangesAsync(cancellationToken);
|
|
}
|
|
catch (DbUpdateConcurrencyException ex) when (attempt < 5)
|
|
{
|
|
var resolvedAny = false;
|
|
foreach (EntityEntry entry in ex.Entries)
|
|
{
|
|
if (entry.Entity is not IVersionedAggregate)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
PropertyValues databaseValues = await entry.GetDatabaseValuesAsync(cancellationToken);
|
|
if (databaseValues is null)
|
|
{
|
|
// The row was deleted out from under us — a genuine conflict, not a token race.
|
|
throw;
|
|
}
|
|
|
|
PropertyEntry version = entry.Property(nameof(IVersionedAggregate.Version));
|
|
int dbVersion = (int)databaseValues[nameof(IVersionedAggregate.Version)]!;
|
|
|
|
// Rebase our pending delta on top of the stored token instead of adopting it verbatim:
|
|
// a Version-bumping sibling (pending current = original + 1) must still advance the
|
|
// ETag PAST the concurrent writer's value, or an editor holding that writer's ETag is
|
|
// never invalidated by our change (#269 rotation silently lost under race). Non-bumpers
|
|
// (delta 0, e.g. ErasePlayoutHistory) still adopt the stored token unchanged.
|
|
int pendingDelta = (int)version.CurrentValue! - (int)version.OriginalValue!;
|
|
version.OriginalValue = dbVersion;
|
|
version.CurrentValue = dbVersion + pendingDelta;
|
|
resolvedAny = true;
|
|
}
|
|
|
|
if (!resolvedAny)
|
|
{
|
|
throw;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Like <see cref="SaveChangesForcingVersion" />, but additionally treats a unique / primary-key
|
|
/// constraint violation as an idempotent no-op: returns <c>false</c> instead of throwing when the
|
|
/// save fails because a concurrent request inserted a row we had membership-checked absent (the
|
|
/// composite-PK race on <c>CollectionItem</c> — issue #308). A <c>false</c> means "the desired row
|
|
/// already exists because a racing writer won; the winner ran the ETag rotation + fan-out, so skip
|
|
/// ours." <c>true</c> means our own change committed. Every other <see cref="DbUpdateException" />
|
|
/// (and the genuine deleted-row concurrency conflict rethrown by <see cref="SaveChangesForcingVersion" />)
|
|
/// still propagates. The only insert these callers stage is the <c>CollectionItem</c> join row, so the
|
|
/// sole unique/PK constraint that can fire here is that composite key.
|
|
/// </summary>
|
|
public static async Task<bool> TrySaveChangesForcingVersion(
|
|
this DbContext dbContext,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
try
|
|
{
|
|
await dbContext.SaveChangesForcingVersion(cancellationToken);
|
|
return true;
|
|
}
|
|
catch (DbUpdateException ex) when (TvContext.IsUniqueConstraintViolation(ex))
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Persist pending changes, mapping the EF optimistic-concurrency failure to
|
|
/// <see cref="PreconditionFailedError" /> (→ 412). When a versioned root carries an
|
|
/// <c>IsConcurrencyToken</c> column and its <c>Version</c> is bumped before saving, EF emits
|
|
/// <c>UPDATE … WHERE Id=@id AND Version=@original</c>; a zero-row result (another writer won
|
|
/// the race between our load and save) throws <see cref="DbUpdateConcurrencyException" />.
|
|
/// This is the backstop that closes the load→save TOCTOU the handler pre-check cannot.
|
|
/// Issue #253.
|
|
/// </summary>
|
|
public static async Task<Either<BaseError, Unit>> SaveChangesWithConcurrencyGuard(
|
|
this DbContext dbContext,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
try
|
|
{
|
|
await dbContext.SaveChangesAsync(cancellationToken);
|
|
return Unit.Default;
|
|
}
|
|
catch (DbUpdateConcurrencyException)
|
|
{
|
|
return new PreconditionFailedError(
|
|
"The resource was modified by another request. Reload and try again.");
|
|
}
|
|
}
|
|
}
|