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>
105 lines
4.7 KiB
C#
105 lines
4.7 KiB
C#
using System.Threading.Channels;
|
|
using ErsatzTV.Application.Playouts;
|
|
using ErsatzTV.Application.Search;
|
|
using ErsatzTV.Core;
|
|
using ErsatzTV.Core.Domain;
|
|
using ErsatzTV.Core.Interfaces.Repositories;
|
|
using ErsatzTV.Core.Scheduling;
|
|
using ErsatzTV.Infrastructure.Data;
|
|
using ErsatzTV.Infrastructure.Extensions;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace ErsatzTV.Application.MediaCollections;
|
|
|
|
public class AddShowToCollectionHandler :
|
|
IRequestHandler<AddShowToCollection, Either<BaseError, Unit>>
|
|
{
|
|
private readonly ChannelWriter<IBackgroundServiceRequest> _channel;
|
|
private readonly IDbContextFactory<TvContext> _dbContextFactory;
|
|
private readonly IMediaCollectionRepository _mediaCollectionRepository;
|
|
private readonly ChannelWriter<ISearchIndexBackgroundServiceRequest> _searchChannel;
|
|
|
|
public AddShowToCollectionHandler(
|
|
IDbContextFactory<TvContext> dbContextFactory,
|
|
IMediaCollectionRepository mediaCollectionRepository,
|
|
ChannelWriter<IBackgroundServiceRequest> channel,
|
|
ChannelWriter<ISearchIndexBackgroundServiceRequest> searchChannel)
|
|
{
|
|
_dbContextFactory = dbContextFactory;
|
|
_mediaCollectionRepository = mediaCollectionRepository;
|
|
_channel = channel;
|
|
_searchChannel = searchChannel;
|
|
}
|
|
|
|
public async Task<Either<BaseError, Unit>> Handle(
|
|
AddShowToCollection request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
await using TvContext dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
|
|
Validation<BaseError, Parameters> validation = await Validate(dbContext, request, cancellationToken);
|
|
return await validation.Apply(parameters => ApplyAddShowRequest(dbContext, parameters));
|
|
}
|
|
|
|
private async Task<Unit> ApplyAddShowRequest(TvContext dbContext, Parameters parameters)
|
|
{
|
|
// No-op on an idempotent re-add: don't rotate the ETag or fan out rebuilds for an item that is
|
|
// already a member (also avoids a duplicate CollectionItem row) — #269.
|
|
if (parameters.Collection.MediaItems.Any(mi => mi.Id == parameters.Show.Id))
|
|
{
|
|
return Unit.Default;
|
|
}
|
|
|
|
parameters.Collection.MediaItems.Add(parameters.Show);
|
|
|
|
// Rotate the collection ETag so an open custom-order editor's If-Match invalidates (#269);
|
|
// force-write past a concurrent replace-all Version bump — this add takes no If-Match, so a
|
|
// benign race must not 500 (#253/#269 §7a). Post-commit enqueues run on CancellationToken.None.
|
|
parameters.Collection.Version++;
|
|
if (!await dbContext.TrySaveChangesForcingVersion(CancellationToken.None))
|
|
{
|
|
// A concurrent add of this same item won the composite-PK race and already inserted the row,
|
|
// rotated the collection ETag, and fanned out the rebuild — so this is now an idempotent
|
|
// no-op. Skip our reindex/rebuild fan-out (the winner already did it). #308
|
|
return Unit.Default;
|
|
}
|
|
|
|
await _searchChannel.WriteAsync(new ReindexMediaItems([parameters.Show.Id]), CancellationToken.None);
|
|
|
|
// refresh all playouts that use this collection
|
|
foreach (int playoutId in await _mediaCollectionRepository
|
|
.PlayoutIdsUsingCollection(parameters.Collection.Id))
|
|
{
|
|
await _channel.WriteAsync(new BuildPlayout(playoutId, PlayoutBuildMode.Refresh), CancellationToken.None);
|
|
}
|
|
|
|
return Unit.Default;
|
|
}
|
|
|
|
private static async Task<Validation<BaseError, Parameters>> Validate(
|
|
TvContext dbContext,
|
|
AddShowToCollection request,
|
|
CancellationToken cancellationToken) =>
|
|
(await CollectionMustExist(dbContext, request, cancellationToken),
|
|
await ValidateShow(dbContext, request, cancellationToken))
|
|
.Apply((collection, episode) => new Parameters(collection, episode));
|
|
|
|
private static Task<Validation<BaseError, Collection>> CollectionMustExist(
|
|
TvContext dbContext,
|
|
AddShowToCollection request,
|
|
CancellationToken cancellationToken) =>
|
|
dbContext.Collections
|
|
.Include(c => c.MediaItems)
|
|
.SelectOneAsync(c => c.Id, c => c.Id == request.CollectionId, cancellationToken)
|
|
.Map(o => o.ToValidation<BaseError>("Collection does not exist."));
|
|
|
|
private static Task<Validation<BaseError, Show>> ValidateShow(
|
|
TvContext dbContext,
|
|
AddShowToCollection request,
|
|
CancellationToken cancellationToken) =>
|
|
dbContext.Shows
|
|
.SelectOneAsync(m => m.Id, e => e.Id == request.ShowId, cancellationToken)
|
|
.Map(o => o.ToValidation<BaseError>("Show does not exist"));
|
|
|
|
private sealed record Parameters(Collection Collection, Show Show);
|
|
}
|