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>
90 lines
3.7 KiB
C#
90 lines
3.7 KiB
C#
using ErsatzTV.Infrastructure;
|
|
using ErsatzTV.Infrastructure.Data;
|
|
using ErsatzTV.Infrastructure.Sqlite.Data;
|
|
using Microsoft.Data.Sqlite;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.EntityFrameworkCore.Diagnostics;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
|
|
namespace ErsatzTV.Tests.Support;
|
|
|
|
/// <summary>
|
|
/// A multi-connection in-memory SQLite harness (shared cache) so several <see cref="TvContext" />
|
|
/// instances on DISTINCT connections hit the same database and real unique-constraint enforcement
|
|
/// applies across connections. Unlike <see cref="InMemoryTvContext" /> (a single shared connection),
|
|
/// this can reproduce a genuine cross-connection write race — needed to exercise the #308 composite-PK
|
|
/// collision through the real handler. A keep-alive connection holds the shared in-memory DB open for
|
|
/// the harness lifetime.
|
|
/// </summary>
|
|
public sealed class SharedCacheTvContext : IAsyncDisposable
|
|
{
|
|
private readonly string _connectionString;
|
|
private readonly SqliteConnection _keepAlive;
|
|
|
|
private SharedCacheTvContext(string connectionString, SqliteConnection keepAlive)
|
|
{
|
|
_connectionString = connectionString;
|
|
_keepAlive = keepAlive;
|
|
}
|
|
|
|
public static async Task<SharedCacheTvContext> CreateAsync(string name)
|
|
{
|
|
TvContext.IsSqlite = true;
|
|
TvContext.IsUniqueConstraintViolation = SqliteErrorClassifier.IsUniqueConstraintViolation;
|
|
|
|
// Foreign keys OFF (connection-string keyword, inherited by every connection) so partial object
|
|
// graphs can be seeded without satisfying every FK — matches InMemoryTvContext. The composite-PK /
|
|
// UNIQUE constraint under test is enforced regardless of this pragma.
|
|
var connectionString = $"Data Source={name};Mode=Memory;Cache=Shared;Foreign Keys=False";
|
|
var keepAlive = new SqliteConnection(connectionString);
|
|
await keepAlive.OpenAsync();
|
|
|
|
await using (TvContext context = Create(BuildOptions(connectionString, null)))
|
|
{
|
|
await context.Database.EnsureCreatedAsync();
|
|
}
|
|
|
|
return new SharedCacheTvContext(connectionString, keepAlive);
|
|
}
|
|
|
|
/// <summary>A factory whose contexts each open their own connection to the shared DB.</summary>
|
|
public IDbContextFactory<TvContext> Factory(IInterceptor? interceptor = null) =>
|
|
new PerConnectionFactory(_connectionString, interceptor);
|
|
|
|
public TvContext CreateContext() => Create(BuildOptions(_connectionString, null));
|
|
|
|
/// <summary>A freshly opened raw connection to the shared DB (used to stage a concurrent writer).</summary>
|
|
public SqliteConnection OpenConnection()
|
|
{
|
|
var connection = new SqliteConnection(_connectionString);
|
|
connection.Open();
|
|
return connection;
|
|
}
|
|
|
|
public async ValueTask DisposeAsync() => await _keepAlive.DisposeAsync();
|
|
|
|
private static DbContextOptions<TvContext> BuildOptions(string connectionString, IInterceptor? interceptor)
|
|
{
|
|
DbContextOptionsBuilder<TvContext> builder = new DbContextOptionsBuilder<TvContext>()
|
|
.UseSqlite(connectionString);
|
|
if (interceptor is not null)
|
|
{
|
|
builder.AddInterceptors(interceptor);
|
|
}
|
|
|
|
return builder.Options;
|
|
}
|
|
|
|
private static TvContext Create(DbContextOptions<TvContext> options) =>
|
|
new(
|
|
options,
|
|
NullLoggerFactory.Instance,
|
|
new SlowQueryInterceptor(NullLogger<SlowQueryInterceptor>.Instance));
|
|
|
|
private sealed class PerConnectionFactory(string connectionString, IInterceptor? interceptor)
|
|
: IDbContextFactory<TvContext>
|
|
{
|
|
public TvContext CreateDbContext() => Create(BuildOptions(connectionString, interceptor));
|
|
}
|
|
}
|