feat(#253 PR3): optimistic-concurrency fan-out — Diff + Scalar aggregates #270

Merged
timothy merged 4 commits from feat/253-pr3-diff-scalar into main 2026-07-11 20:56:31 +02:00
59 changed files with 1458 additions and 136 deletions
@@ -1,11 +1,67 @@
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
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 adopt the stored token as both original (the retry's WHERE then
/// matches) and current (so we don't revert the concurrent bump) and retry — a client-wins merge
/// scoped to the token; 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));
object currentVersion = databaseValues[nameof(IVersionedAggregate.Version)]!;
version.OriginalValue = currentVersion;
version.CurrentValue = currentVersion;
resolvedAny = true;
}
if (!resolvedAny)
{
throw;
}
}
}
}
/// <summary>
/// Persist pending changes, mapping the EF optimistic-concurrency failure to
/// <see cref="PreconditionFailedError" /> (→ 412). When a versioned root carries an
@@ -4,6 +4,7 @@ namespace ErsatzTV.Application.MediaCollections;
public record UpdateCollectionCustomOrder(
int CollectionId,
List<MediaItemCustomOrder> MediaItemCustomOrders) : IRequest<Either<BaseError, Unit>>;
List<MediaItemCustomOrder> MediaItemCustomOrders,
Option<int> ExpectedVersion = default) : IRequest<Either<BaseError, Unit>>;
public record MediaItemCustomOrder(int MediaItemId, int CustomIndex);
@@ -32,13 +32,22 @@ public class UpdateCollectionCustomOrderHandler : IRequestHandler<UpdateCollecti
{
await using TvContext dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
Validation<BaseError, Collection> validation = await Validate(dbContext, request, cancellationToken);
return await validation.Apply(c => ApplyUpdateRequest(dbContext, c, request));
// Optimistic-concurrency check as a standalone Either AFTER validation, never via Apply (which
// Join()s the error Seq and would flatten PreconditionFailedError to a 422) — issue #253 §7a.
Either<BaseError, Collection> validated = LanguageExtensions.ToEither(validation)
.Bind(c => c.CheckVersion(request.ExpectedVersion));
return await validated.Match(
Right: c => ApplyUpdateRequest(dbContext, c, request, cancellationToken),
Left: error => Task.FromResult<Either<BaseError, Unit>>(error));
}
private async Task<Unit> ApplyUpdateRequest(
private async Task<Either<BaseError, Unit>> ApplyUpdateRequest(
TvContext dbContext,
Collection c,
UpdateCollectionCustomOrder request)
UpdateCollectionCustomOrder request,
CancellationToken cancellationToken)
{
foreach (MediaItemCustomOrder updateItem in request.MediaItemCustomOrders)
{
@@ -51,14 +60,24 @@ public class UpdateCollectionCustomOrderHandler : IRequestHandler<UpdateCollecti
}
}
if (await dbContext.SaveChangesAsync() > 0)
// Unconditional bump (issue #253 §7a / M1) then guarded save (→ 412 on a lost race).
c.Version++;
Either<BaseError, Unit> saveResult = await dbContext.SaveChangesWithConcurrencyGuard(cancellationToken);
if (saveResult.IsLeft)
{
// refresh all playouts that use this collection
foreach (int playoutId in await _mediaCollectionRepository
.PlayoutIdsUsingCollection(request.CollectionId))
{
await _channel.WriteAsync(new BuildPlayout(playoutId, PlayoutBuildMode.Refresh));
}
return saveResult;
}
// Refresh all playouts that use this collection. The old `SaveChangesAsync() > 0` gate is always
// true once the version bumps unconditionally (M2), so run the refresh on any successful save.
// Post-commit enqueue on CancellationToken.None so a late cancellation can't drop the rebuild
// after the commit landed (#254 / §7b).
foreach (int playoutId in await _mediaCollectionRepository
.PlayoutIdsUsingCollection(request.CollectionId))
{
await _channel.WriteAsync(
new BuildPlayout(playoutId, PlayoutBuildMode.Refresh),
CancellationToken.None);
}
return Unit.Default;
@@ -59,7 +59,9 @@ public class UpdateCollectionHandler : IRequestHandler<UpdateCollection, Either<
c.UseCustomPlaybackOrder = useCustomPlaybackOrder;
}
if (await dbContext.SaveChangesAsync(cancellationToken) > 0 && request.UseCustomPlaybackOrder.IsSome)
// Force-write past a concurrent Version bump from the custom-order editor (this name/flag writer
// doesn't participate in If-Match, so the active token must not 500 a benign race) — #253/#269.
if (await dbContext.SaveChangesForcingVersion(cancellationToken) > 0 && request.UseCustomPlaybackOrder.IsSome)
{
// post-commit side effect runs on CancellationToken.None so a late request cancellation
// can't abort it after the commit landed (#254)
@@ -12,4 +12,5 @@ public record UpdateMultiCollectionItem(
public record UpdateMultiCollection(
int MultiCollectionId,
string Name,
List<UpdateMultiCollectionItem> Items) : IRequest<Either<BaseError, Unit>>;
List<UpdateMultiCollectionItem> Items,
Option<int> ExpectedVersion = default) : IRequest<Either<BaseError, Unit>>;
@@ -36,10 +36,18 @@ public class UpdateMultiCollectionHandler : IRequestHandler<UpdateMultiCollectio
{
await using TvContext dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
Validation<BaseError, MultiCollection> validation = await Validate(dbContext, request, cancellationToken);
return await validation.Apply(c => ApplyUpdateRequest(dbContext, c, request, cancellationToken));
// Optimistic-concurrency check as a standalone Either AFTER validation, never via Apply (which
// Join()s the error Seq and would flatten PreconditionFailedError to a 422) — issue #253 §7a.
Either<BaseError, MultiCollection> validated = LanguageExtensions.ToEither(validation)
.Bind(c => c.CheckVersion(request.ExpectedVersion));
return await validated.Match(
Right: c => ApplyUpdateRequest(dbContext, c, request, cancellationToken),
Left: error => Task.FromResult<Either<BaseError, Unit>>(error));
}
private async Task<Unit> ApplyUpdateRequest(
private async Task<Either<BaseError, Unit>> ApplyUpdateRequest(
TvContext dbContext,
MultiCollection c,
UpdateMultiCollection request,
@@ -47,8 +55,16 @@ public class UpdateMultiCollectionHandler : IRequestHandler<UpdateMultiCollectio
{
c.Name = request.Name;
// save name first so playouts don't get rebuilt for a name change
await dbContext.SaveChangesAsync(cancellationToken);
// Bump the version on this first save (issue #253 §7a): it rotates other clients' ETags and,
// via IsConcurrencyToken, closes the load→save race — a stale writer's WHERE Version=@orig hits
// 0 rows → PreconditionFailedError (412). Saving the name first also keeps a name-only change
// from triggering a playout rebuild (the item save below stays gated on real item changes).
c.Version++;
Either<BaseError, Unit> nameSave = await dbContext.SaveChangesWithConcurrencyGuard(cancellationToken);
if (nameSave.IsLeft)
{
return nameSave;
}
var toAdd = request.Items
.Filter(i => i.CollectionId.HasValue)
@@ -13,5 +13,6 @@ public record UpdateRerunCollection(
SmartCollectionViewModel SmartCollection,
NamedMediaItemViewModel MediaItem,
PlaybackOrder FirstRunPlaybackOrder,
PlaybackOrder RerunPlaybackOrder)
PlaybackOrder RerunPlaybackOrder,
Option<int> ExpectedVersion = default)
: IRequest<Either<BaseError, Unit>>;
@@ -22,10 +22,18 @@ public class UpdateRerunCollectionHandler(
{
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
Validation<BaseError, RerunCollection> validation = await Validate(dbContext, request, cancellationToken);
return await validation.Apply(c => ApplyUpdateRequest(dbContext, c, request, cancellationToken));
// Optimistic-concurrency check as a standalone Either AFTER validation, never via Apply (which
// Join()s the error Seq and would flatten PreconditionFailedError to a 422) — issue #253 §7a.
Either<BaseError, RerunCollection> validated = LanguageExtensions.ToEither(validation)
.Bind(c => c.CheckVersion(request.ExpectedVersion));
return await validated.Match(
Right: c => ApplyUpdateRequest(dbContext, c, request, cancellationToken),
Left: error => Task.FromResult<Either<BaseError, Unit>>(error));
}
private async Task<Unit> ApplyUpdateRequest(
private async Task<Either<BaseError, Unit>> ApplyUpdateRequest(
TvContext dbContext,
RerunCollection c,
UpdateRerunCollection request,
@@ -40,17 +48,23 @@ public class UpdateRerunCollectionHandler(
c.FirstRunPlaybackOrder = request.FirstRunPlaybackOrder;
c.RerunPlaybackOrder = request.RerunPlaybackOrder;
// rebuild playouts
if (await dbContext.SaveChangesAsync(cancellationToken) > 0)
// Unconditional bump (issue #253 §7a / M1) then guarded save, which maps a racing
// DbUpdateConcurrencyException to PreconditionFailedError (→ 412).
c.Version++;
Either<BaseError, Unit> saveResult = await dbContext.SaveChangesWithConcurrencyGuard(cancellationToken);
if (saveResult.IsLeft)
{
// post-commit side effect runs on CancellationToken.None so a late request cancellation
// can't abort it after the commit landed (#254)
// refresh all playouts that use this rerun collection
foreach (int playoutId in await mediaCollectionRepository.PlayoutIdsUsingRerunCollection(
request.RerunCollectionId))
{
await channel.WriteAsync(new BuildPlayout(playoutId, PlayoutBuildMode.Refresh), CancellationToken.None);
}
return saveResult;
}
// Refresh all playouts that use this rerun collection. The old `SaveChangesAsync() > 0` gate is
// always true once the version bumps unconditionally (M2), so run the refresh on any successful
// save. Post-commit enqueue on CancellationToken.None so a late cancellation can't drop the
// rebuild after the commit landed (#254).
foreach (int playoutId in await mediaCollectionRepository.PlayoutIdsUsingRerunCollection(
request.RerunCollectionId))
{
await channel.WriteAsync(new BuildPlayout(playoutId, PlayoutBuildMode.Refresh), CancellationToken.None);
}
return Unit.Default;
@@ -12,14 +12,16 @@ internal static class Mapper
collection.Id,
collection.Name,
collection.UseCustomPlaybackOrder,
MediaItemState.Normal);
MediaItemState.Normal,
collection.Version);
internal static MultiCollectionViewModel ProjectToViewModel(MultiCollection multiCollection) =>
new(
multiCollection.Id,
multiCollection.Name,
Optional(multiCollection.MultiCollectionItems).Flatten().Map(ProjectToViewModel).ToList(),
Optional(multiCollection.MultiCollectionSmartItems).Flatten().Map(ProjectToViewModel).ToList());
Optional(multiCollection.MultiCollectionSmartItems).Flatten().Map(ProjectToViewModel).ToList(),
multiCollection.Version);
internal static SmartCollectionViewModel ProjectToViewModel(SmartCollection collection) =>
new(collection.Id, collection.Name, collection.Query);
@@ -49,7 +51,8 @@ internal static class Mapper
_ => null
},
collection.FirstRunPlaybackOrder,
collection.RerunPlaybackOrder);
collection.RerunPlaybackOrder,
collection.Version);
internal static TraktListViewModel ProjectToViewModel(TraktList traktList) =>
new(
@@ -8,7 +8,10 @@ public record MediaCollectionViewModel(
int Id,
string Name,
bool UseCustomPlaybackOrder,
MediaItemState State) : MediaCardViewModel(
MediaItemState State,
// Optimistic-concurrency token (issue #253), header-only via ETag; 0 for the selection/placeholder
// constructions that don't read a real collection. Set from the entity by the Mapper projection.
int Version = 0) : MediaCardViewModel(
Id,
Name,
string.Empty,
@@ -4,4 +4,6 @@ public record MultiCollectionViewModel(
int Id,
string Name,
List<MultiCollectionItemViewModel> Items,
List<MultiCollectionSmartItemViewModel> SmartItems);
List<MultiCollectionSmartItemViewModel> SmartItems,
// Optimistic-concurrency token (issue #253), header-only via ETag; 0 for selection placeholders.
int Version = 0);
@@ -12,4 +12,6 @@ public record RerunCollectionViewModel(
SmartCollectionViewModel SmartCollection,
NamedMediaItemViewModel MediaItem,
PlaybackOrder FirstRunPlaybackOrder,
PlaybackOrder RerunPlaybackOrder);
PlaybackOrder RerunPlaybackOrder,
// Optimistic-concurrency token (issue #253), header-only via ETag.
int Version = 0);
@@ -2,5 +2,8 @@ using ErsatzTV.Core;
namespace ErsatzTV.Application.Playouts;
public record ReplacePlayoutAlternateScheduleItems(int PlayoutId, List<ReplacePlayoutAlternateSchedule> Items)
public record ReplacePlayoutAlternateScheduleItems(
int PlayoutId,
List<ReplacePlayoutAlternateSchedule> Items,
Option<int> ExpectedVersion = default)
: IRequest<Either<BaseError, Unit>>;
@@ -40,6 +40,18 @@ public class ReplacePlayoutAlternateScheduleItemsHandler(
foreach (Playout playout in maybePlayout)
{
// Optimistic-concurrency pre-check (issue #253 §7a): reject a stale If-Match with a
// PreconditionFailedError (→ 412) before any mutation. Introduced as a standalone Either,
// and returned directly (a value, not a throw) so it escapes the catch(Exception) below
// rather than being reshaped into a bare 422 (§9/H1).
Either<BaseError, Playout> versionCheck = playout.CheckVersion(request.ExpectedVersion);
if (versionCheck.IsLeft)
{
return versionCheck.Match<Either<BaseError, Unit>>(
Left: error => error,
Right: _ => Unit.Default);
}
var existingScheduleMap = new Dictionary<DateTimeOffset, ProgramSchedule>();
var daysToCheck = new List<DateTimeOffset>();
@@ -127,7 +139,20 @@ public class ReplacePlayoutAlternateScheduleItemsHandler(
playout.ProgramScheduleId = highest.ProgramScheduleId;
}
await dbContext.SaveChangesAsync(cancellationToken);
// Unconditional bump (issue #253 §7a / M1): EF emits the root UPDATE only when a scalar
// actually differs, so a no-op PUT-back would otherwise neither fire the concurrency token
// nor rotate other clients' ETags.
playout.Version++;
// Guarded save maps a racing DbUpdateConcurrencyException to PreconditionFailedError (→ 412)
// as a return value, so a lost race short-circuits here before the post-commit refresh block
// and escapes the catch(Exception) below as a 412, not a 422 (§9/H1).
Either<BaseError, Unit> saveResult =
await dbContext.SaveChangesWithConcurrencyGuard(cancellationToken);
if (saveResult.IsLeft)
{
return saveResult;
}
if (hasDefaultScheduleChange)
{
@@ -40,7 +40,9 @@ public class
{
playout.ScheduleFile = request.ScheduleFile;
if (await dbContext.SaveChangesAsync(cancellationToken) > 0)
// Force-write past a concurrent Version bump from a replace-all editor (schedule-file writer
// doesn't participate in If-Match, so an active token must not 500 a benign race) — #253/#269.
if (await dbContext.SaveChangesForcingVersion(cancellationToken) > 0)
{
// post-commit side effect runs on CancellationToken.None so a late request cancellation
// can't abort it after the commit landed (#254)
@@ -58,7 +60,8 @@ public class
playout.DailyRebuildTime,
playout.BuildStatus,
playout.DecoId,
playout.Deco?.Name);
playout.Deco?.Name,
playout.Version);
}
private static Task<Validation<BaseError, Playout>> Validate(
@@ -61,7 +61,10 @@ public class UpdateOnDemandCheckpointHandler(
playout.Channel.Name,
playout.OnDemandCheckpoint);
await dbContext.SaveChangesAsync(cancellationToken);
// Force-write past a concurrent Version bump from a replace-all editor: the on-demand
// checkpoint writer touches the Playout root but doesn't participate in If-Match, so the
// active concurrency token must not turn a benign race into a 500 (#253/#269).
await dbContext.SaveChangesForcingVersion(cancellationToken);
}
}
}
@@ -35,7 +35,9 @@ public class UpdatePlayoutHandler : IRequestHandler<UpdatePlayout, Either<BaseEr
playout.DailyRebuildTime = dailyRebuildTime;
}
await dbContext.SaveChangesAsync(cancellationToken);
// Force-write past a concurrent Version bump from a replace-all editor (this settings writer
// doesn't participate in If-Match, so a missing token = force-write, not a 500) — #253/#269.
await dbContext.SaveChangesForcingVersion(cancellationToken);
return new PlayoutNameViewModel(
playout.Id,
@@ -48,7 +50,8 @@ public class UpdatePlayoutHandler : IRequestHandler<UpdatePlayout, Either<BaseEr
playout.DailyRebuildTime,
playout.BuildStatus,
playout.DecoId,
playout.Deco?.Name);
playout.Deco?.Name,
playout.Version);
}
private static Task<Validation<BaseError, Playout>> Validate(
@@ -35,7 +35,9 @@ public class
{
playout.ScheduleFile = request.ScheduleFile;
if (await dbContext.SaveChangesAsync(cancellationToken) > 0)
// Force-write past a concurrent Version bump from a replace-all editor (schedule-file writer
// doesn't participate in If-Match, so an active token must not 500 a benign race) — #253/#269.
if (await dbContext.SaveChangesForcingVersion(cancellationToken) > 0)
{
// post-commit side effect runs on CancellationToken.None so a late request cancellation
// can't abort it after the commit landed (#254)
@@ -53,7 +55,8 @@ public class
playout.DailyRebuildTime,
playout.BuildStatus,
playout.DecoId,
playout.Deco?.Name);
playout.Deco?.Name,
playout.Version);
}
private async Task<Validation<BaseError, Playout>> Validate(
@@ -40,7 +40,9 @@ public class
{
playout.ScheduleFile = request.ScheduleFile;
if (await dbContext.SaveChangesAsync(cancellationToken) > 0)
// Force-write past a concurrent Version bump from a replace-all editor (schedule-file writer
// doesn't participate in If-Match, so an active token must not 500 a benign race) — #253/#269.
if (await dbContext.SaveChangesForcingVersion(cancellationToken) > 0)
{
// post-commit side effect runs on CancellationToken.None so a late request cancellation
// can't abort it after the commit landed (#254)
@@ -58,7 +60,8 @@ public class
playout.DailyRebuildTime,
playout.BuildStatus,
playout.DecoId,
playout.Deco?.Name);
playout.Deco?.Name,
playout.Version);
}
private static Task<Validation<BaseError, Playout>> Validate(
+2 -1
View File
@@ -19,7 +19,8 @@ internal static class Mapper
playout.DecoId,
// the paged-playouts query does not eager-load Deco (the list response does not surface
// the default deco); GetPlayoutById includes it for the detail response
playout.Deco?.Name);
playout.Deco?.Name,
playout.Version);
internal static PlayoutItemViewModel ProjectToViewModel(PlayoutItem playoutItem) =>
new(
@@ -13,7 +13,8 @@ public record PlayoutNameViewModel(
TimeSpan? DbDailyRebuildTime,
PlayoutBuildStatus BuildStatus,
int? DecoId,
string DecoName)
string DecoName,
int Version)
{
public Option<TimeSpan> DailyRebuildTime => Optional(DbDailyRebuildTime);
@@ -30,6 +30,7 @@ public class GetPlayoutByIdHandler(IDbContextFactory<TvContext> dbContextFactory
p.DailyRebuildTime,
p.BuildStatus,
p.DecoId,
p.DecoId == null ? null : p.Deco.Name));
p.DecoId == null ? null : p.Deco.Name,
p.Version));
}
}
@@ -2,5 +2,8 @@ using ErsatzTV.Core;
namespace ErsatzTV.Application.Scheduling;
public record ReplacePlayoutTemplateItems(int PlayoutId, List<ReplacePlayoutTemplate> Items)
public record ReplacePlayoutTemplateItems(
int PlayoutId,
List<ReplacePlayoutTemplate> Items,
Option<int> ExpectedVersion = default)
: IRequest<Option<BaseError>>;
@@ -29,6 +29,17 @@ public class ReplacePlayoutTemplateItemsHandler(
foreach (Playout playout in maybePlayout)
{
// Optimistic-concurrency pre-check (issue #253 §7a): reject a stale If-Match with a
// PreconditionFailedError (→ 412) before any mutation. Returned directly so it escapes the
// catch(Exception) below as a 412 rather than being reshaped into a bare 422 (§9/H1).
Either<BaseError, Playout> versionCheck = playout.CheckVersion(request.ExpectedVersion);
if (versionCheck.IsLeft)
{
return versionCheck.Match<Option<BaseError>>(
Left: error => error,
Right: _ => Option<BaseError>.None);
}
PlayoutTemplate[] existing = playout.Templates.ToArray();
List<ReplacePlayoutTemplate> incoming = request.Items;
@@ -88,7 +99,20 @@ public class ReplacePlayoutTemplateItemsHandler(
}
}
await dbContext.SaveChangesAsync(cancellationToken);
// Unconditional bump (issue #253 §7a / M1): #8 writes no root scalar at all (only the
// Templates child collection), so without this the root UPDATE never fires and the token
// never rotates. Bump then save through the guard, which maps a racing
// DbUpdateConcurrencyException to PreconditionFailedError (→ 412) as a return value.
playout.Version++;
Either<BaseError, Unit> saveResult =
await dbContext.SaveChangesWithConcurrencyGuard(cancellationToken);
if (saveResult.IsLeft)
{
return saveResult.Match<Option<BaseError>>(
Left: error => error,
Right: _ => Option<BaseError>.None);
}
}
return Option<BaseError>.None;
@@ -20,7 +20,14 @@ public class UpdateDefaultDecoHandler(
int updated = await dbContext.Playouts
.Where(p => p.Id == request.PlayoutId)
.ExecuteUpdateAsync(u => u.SetProperty(p => p.DecoId, p => request.DecoId), cancellationToken);
.ExecuteUpdateAsync(
u => u
.SetProperty(p => p.DecoId, p => request.DecoId)
// Bump the shared Playout.Version so any open alternate-schedule/template editor tab
// (which round-trips this same token) detects the deco change and reloads (#253 §7a).
// Bulk ExecuteUpdate bypasses change-tracking, so bump via SetProperty, not Version++.
.SetProperty(p => p.Version, p => p.Version + 1),
cancellationToken);
// Changing a playout's default deco only takes effect on a Reset build (deco content is applied
// during Reset, and BlockKey has no deco dimension to self-heal) — same stale-until-Reset class
@@ -0,0 +1,82 @@
using System.Threading.Channels;
using ErsatzTV.Application;
using ErsatzTV.Application.MediaCollections;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using ErsatzTV.Core.Interfaces.Repositories;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Tests.Support;
using LanguageExt;
using Microsoft.EntityFrameworkCore;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
using Unit = LanguageExt.Unit;
using static LanguageExt.Prelude;
namespace ErsatzTV.Tests.Application.MediaCollections;
/// <summary>
/// #253 optimistic-concurrency contract on the Collection custom-order handler (#6): the pre-check
/// 412 (standalone Either after validation, not flattened to 422) and the unconditional Version bump.
/// </summary>
[TestFixture]
public class CollectionCustomOrderConcurrencyTests : MediaCollectionHandlerTestBase
{
private async Task SeedCollectionWithVersion(int id, int version, string name = "Collection")
{
await using TvContext context = Db.CreateContext();
context.Collections.Add(new Collection
{
Id = id,
Name = name,
Version = version,
MediaItems = [],
CollectionItems = []
});
await context.SaveChangesAsync();
}
private async Task<int> ReadVersion(int id)
{
await using TvContext context = Db.CreateContext();
return await context.Collections.Where(c => c.Id == id).Select(c => c.Version).SingleAsync();
}
private UpdateCollectionCustomOrderHandler MakeHandler()
{
IMediaCollectionRepository repo = Substitute.For<IMediaCollectionRepository>();
repo.PlayoutIdsUsingCollection(Arg.Any<int>()).Returns([]);
return new UpdateCollectionCustomOrderHandler(Db.Factory, repo, Worker);
}
private static BaseError LeftOf(Either<BaseError, Unit> either) =>
either.Match(Left: e => e, Right: _ => throw new AssertionException("Expected a Left result"));
[Test]
public async Task Stale_If_Match_Should_Fail_Precondition_And_Not_Mutate()
{
await SeedCollectionWithVersion(1, version: 2);
Either<BaseError, Unit> result = await MakeHandler().Handle(
new UpdateCollectionCustomOrder(1, [], Some(1)),
CancellationToken.None);
LeftOf(result).ShouldBeOfType<PreconditionFailedError>();
(await ReadVersion(1)).ShouldBe(2);
}
[Test]
public async Task Matching_If_Match_Should_Succeed_And_Bump()
{
await SeedCollectionWithVersion(1, version: 2);
Either<BaseError, Unit> result = await MakeHandler().Handle(
new UpdateCollectionCustomOrder(1, [], Some(2)),
CancellationToken.None);
result.IsRight.ShouldBeTrue();
(await ReadVersion(1)).ShouldBe(3);
}
}
@@ -0,0 +1,107 @@
using System.Threading.Channels;
using ErsatzTV.Application;
using ErsatzTV.Application.MediaCollections;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using ErsatzTV.Core.Interfaces.Repositories;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Tests.Support;
using LanguageExt;
using Microsoft.EntityFrameworkCore;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
using Unit = LanguageExt.Unit;
using static LanguageExt.Prelude;
namespace ErsatzTV.Tests.Application.MediaCollections;
/// <summary>
/// #253 optimistic-concurrency contract on the MultiCollection replace handler (#9): pre-check 412
/// (standalone Either, not flattened to 422), the unconditional Version bump, and the M2 rework of
/// the old <c>SaveChangesAsync() &gt; 0</c> gate — a name-only change still saves (and bumps) but must
/// NOT rebuild playouts, since the version bump rides the first (name) save while the item save stays
/// gated on real item changes.
/// </summary>
[TestFixture]
public class MultiCollectionConcurrencyTests : MediaCollectionHandlerTestBase
{
private static UpdateMultiCollection Update(int id, string name, Option<int> expectedVersion) =>
new(id, name, [], expectedVersion);
private async Task SeedMultiCollection(int id, int version, string name = "Multi")
{
await using TvContext context = Db.CreateContext();
context.MultiCollections.Add(new MultiCollection
{
Id = id,
Name = name,
Version = version,
MultiCollectionItems = [],
MultiCollectionSmartItems = []
});
await context.SaveChangesAsync();
}
private async Task<int> ReadVersion(int id)
{
await using TvContext context = Db.CreateContext();
return await context.MultiCollections.Where(c => c.Id == id).Select(c => c.Version).SingleAsync();
}
private UpdateMultiCollectionHandler MakeHandler(IMediaCollectionRepository repo) =>
new(Db.Factory, repo, Worker, SearchTargets);
private static IMediaCollectionRepository EmptyRepo()
{
IMediaCollectionRepository repo = Substitute.For<IMediaCollectionRepository>();
repo.PlayoutIdsUsingMultiCollection(Arg.Any<int>()).Returns([]);
return repo;
}
private static BaseError LeftOf(Either<BaseError, Unit> either) =>
either.Match(Left: e => e, Right: _ => throw new AssertionException("Expected a Left result"));
[Test]
public async Task Update_Stale_If_Match_Should_Fail_Precondition_And_Not_Mutate()
{
await SeedMultiCollection(1, version: 2);
Either<BaseError, Unit> result =
await MakeHandler(EmptyRepo()).Handle(Update(1, "Renamed", Some(1)), CancellationToken.None);
LeftOf(result).ShouldBeOfType<PreconditionFailedError>();
(await ReadVersion(1)).ShouldBe(2);
}
[Test]
public async Task Update_Matching_If_Match_Should_Succeed_And_Bump()
{
await SeedMultiCollection(1, version: 2);
Either<BaseError, Unit> result =
await MakeHandler(EmptyRepo()).Handle(Update(1, "Renamed", Some(2)), CancellationToken.None);
result.IsRight.ShouldBeTrue();
(await ReadVersion(1)).ShouldBe(3);
}
[Test]
public async Task Name_Only_Change_Should_Bump_But_Not_Rebuild_Playouts()
{
await SeedMultiCollection(1, version: 1, name: "Before");
IMediaCollectionRepository repo = EmptyRepo();
Either<BaseError, Unit> result =
await MakeHandler(repo).Handle(Update(1, "After", None), CancellationToken.None);
result.IsRight.ShouldBeTrue();
(await ReadVersion(1)).ShouldBe(2);
// M2: the version bump rides the first (name) save, so the second (items) save writes nothing →
// no rebuild is enqueued and the search index is not signalled for a name-only edit.
SearchTargets.DidNotReceive().SearchTargetsChanged();
await repo.DidNotReceive().PlayoutIdsUsingMultiCollection(Arg.Any<int>());
}
}
@@ -8,10 +8,12 @@ using ErsatzTV.Core.Interfaces.Repositories;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Tests.Support;
using LanguageExt;
using Microsoft.EntityFrameworkCore;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
using Unit = LanguageExt.Unit;
using static LanguageExt.Prelude;
namespace ErsatzTV.Tests.Application.MediaCollections;
@@ -150,7 +152,49 @@ public class RerunCollectionHandlerTests : MediaCollectionHandlerTestBase
await context.SaveChangesAsync();
}
private async Task SeedRerunCollection(int id, CollectionType collectionType, string name = "Rerun")
[Test]
public async Task Update_Stale_If_Match_Should_Fail_Precondition()
{
await SeedRerunCollection(1, CollectionType.SmartCollection, version: 2);
await SeedSmartCollection(2);
IMediaCollectionRepository repo = Substitute.For<IMediaCollectionRepository>();
repo.PlayoutIdsUsingRerunCollection(Arg.Any<int>()).Returns([]);
var handler = new UpdateRerunCollectionHandler(Db.Factory, repo, Worker);
Either<BaseError, Unit> result = await handler.Handle(
MakeUpdate(1, CollectionType.SmartCollection, smartCollection: new SmartCollectionViewModel(2, "", ""))
with { ExpectedVersion = Some(1) },
CancellationToken.None);
LeftOf(result).ShouldBeOfType<PreconditionFailedError>();
(await ReadVersion(1)).ShouldBe(2);
}
[Test]
public async Task Update_Matching_If_Match_Should_Succeed_And_Bump()
{
await SeedRerunCollection(1, CollectionType.SmartCollection, version: 2);
await SeedSmartCollection(2);
IMediaCollectionRepository repo = Substitute.For<IMediaCollectionRepository>();
repo.PlayoutIdsUsingRerunCollection(Arg.Any<int>()).Returns([]);
var handler = new UpdateRerunCollectionHandler(Db.Factory, repo, Worker);
Either<BaseError, Unit> result = await handler.Handle(
MakeUpdate(1, CollectionType.SmartCollection, smartCollection: new SmartCollectionViewModel(2, "", ""))
with { ExpectedVersion = Some(2) },
CancellationToken.None);
RightOf(result);
(await ReadVersion(1)).ShouldBe(3);
}
private async Task<int> ReadVersion(int id)
{
await using TvContext context = Db.CreateContext();
return await context.RerunCollections.Where(c => c.Id == id).Select(c => c.Version).SingleAsync();
}
private async Task SeedRerunCollection(int id, CollectionType collectionType, string name = "Rerun", int version = 0)
{
await using TvContext context = Db.CreateContext();
context.RerunCollections.Add(new RerunCollection
@@ -158,6 +202,7 @@ public class RerunCollectionHandlerTests : MediaCollectionHandlerTestBase
Id = id,
Name = name,
CollectionType = collectionType,
Version = version,
FirstRunPlaybackOrder = PlaybackOrder.Chronological,
RerunPlaybackOrder = PlaybackOrder.Chronological
});
@@ -1,6 +1,7 @@
using System.Threading.Channels;
using ErsatzTV.Application;
using ErsatzTV.Application.Playouts;
using ErsatzTV.Application.Scheduling;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
@@ -9,6 +10,7 @@ using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Tests.Support;
using LanguageExt;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using NUnit.Framework;
@@ -16,6 +18,7 @@ using Shouldly;
using Testably.Abstractions.Testing;
using Unit = LanguageExt.Unit;
using Channel = System.Threading.Channels.Channel;
using static LanguageExt.Prelude;
namespace ErsatzTV.Tests.Application.Playouts;
@@ -118,6 +121,176 @@ public class PlayoutHandlerTests
LeftOf(result).Value.ShouldContain("must not be empty");
}
// ---- #253 optimistic concurrency (alternate schedules #7 + templates #8, shared Playout.Version) ----
private static ReplacePlayoutAlternateSchedule AltItem(int programScheduleId = 10) =>
new(0, 0, programScheduleId, [], [], [], false, 1, 1, null, 12, 31, null);
private static ReplacePlayoutTemplate TemplateItem(int templateId = 20) =>
new(0, 0, templateId, null, [], [], [], false, 1, 1, null, 12, 31, null);
private async Task SeedPlayout(int id, int version, int? programScheduleId = 10)
{
await using TvContext context = _db.CreateContext();
context.Playouts.Add(
new Playout
{
Id = id,
ChannelId = 1,
ProgramScheduleId = programScheduleId,
Version = version,
Items = [],
ProgramScheduleAlternates = [],
Templates = []
});
await context.SaveChangesAsync();
}
private async Task<int> ReadPlayoutVersion(int id)
{
await using TvContext context = _db.CreateContext();
return await context.Playouts.Where(p => p.Id == id).Select(p => p.Version).SingleAsync();
}
[Test]
public async Task ReplaceAlternateSchedules_Stale_If_Match_Should_Fail_Precondition_And_Not_Mutate()
{
await SeedPlayout(1, version: 2);
var handler = new ReplacePlayoutAlternateScheduleItemsHandler(
_db.Factory,
_worker,
NullLogger<ReplacePlayoutAlternateScheduleItemsHandler>.Instance);
Either<BaseError, Unit> result = await handler.Handle(
new ReplacePlayoutAlternateScheduleItems(1, [AltItem()], Some(1)),
CancellationToken.None);
// Standalone-Either pre-check (not via Apply) preserves the subtype → 412 rather than a flattened 422.
LeftOf(result).ShouldBeOfType<PreconditionFailedError>();
(await ReadPlayoutVersion(1)).ShouldBe(2);
}
[Test]
public async Task ReplaceAlternateSchedules_Matching_If_Match_Should_Succeed_And_Bump()
{
await SeedPlayout(1, version: 2);
var handler = new ReplacePlayoutAlternateScheduleItemsHandler(
_db.Factory,
_worker,
NullLogger<ReplacePlayoutAlternateScheduleItemsHandler>.Instance);
Either<BaseError, Unit> result = await handler.Handle(
new ReplacePlayoutAlternateScheduleItems(1, [AltItem()], Some(2)),
CancellationToken.None);
result.IsRight.ShouldBeTrue();
(await ReadPlayoutVersion(1)).ShouldBe(3);
}
[Test]
public async Task ReplaceAlternateSchedules_Absent_If_Match_Should_Force_Write_And_Bump()
{
await SeedPlayout(1, version: 2);
var handler = new ReplacePlayoutAlternateScheduleItemsHandler(
_db.Factory,
_worker,
NullLogger<ReplacePlayoutAlternateScheduleItemsHandler>.Instance);
Either<BaseError, Unit> result = await handler.Handle(
new ReplacePlayoutAlternateScheduleItems(1, [AltItem()], None),
CancellationToken.None);
result.IsRight.ShouldBeTrue();
(await ReadPlayoutVersion(1)).ShouldBe(3);
}
[Test]
public async Task ReplaceTemplates_Stale_If_Match_Should_Fail_Precondition_And_Not_Mutate()
{
await SeedPlayout(1, version: 2);
var handler = new ReplacePlayoutTemplateItemsHandler(
_db.Factory,
NullLogger<ReplacePlayoutTemplateItemsHandler>.Instance);
Option<BaseError> result = await handler.Handle(
new ReplacePlayoutTemplateItems(1, [TemplateItem()], Some(1)),
CancellationToken.None);
// Some(PreconditionFailedError): the pre-check escapes the handler's catch(Exception) as a 412
// rather than being reshaped into a bare BaseError → 422 (§9/H1).
result.IfNone(() => throw new AssertionException("Expected a Some(error)"))
.ShouldBeOfType<PreconditionFailedError>();
(await ReadPlayoutVersion(1)).ShouldBe(2);
}
[Test]
public async Task ReplaceTemplates_Matching_If_Match_Should_Succeed_And_Bump()
{
await SeedPlayout(1, version: 2);
var handler = new ReplacePlayoutTemplateItemsHandler(
_db.Factory,
NullLogger<ReplacePlayoutTemplateItemsHandler>.Instance);
Option<BaseError> result = await handler.Handle(
new ReplacePlayoutTemplateItems(1, [TemplateItem()], Some(2)),
CancellationToken.None);
result.IsNone.ShouldBeTrue();
(await ReadPlayoutVersion(1)).ShouldBe(3);
}
[Test]
public async Task Racing_Playout_Save_Should_Map_Concurrency_Failure_To_412()
{
await SeedPlayout(1, version: 1);
// Backstop mechanic on the Playout token: two writers load the same version and both bump-and-save;
// IsConcurrencyToken on Playout keys the loser's UPDATE on the original version → 0 rows →
// DbUpdateConcurrencyException → PreconditionFailedError. Non-vacuous: drop .IsConcurrencyToken()
// on Playout and the loser silently overwrites the winner instead.
await using TvContext ctxWinner = _db.CreateContext();
await using TvContext ctxLoser = _db.CreateContext();
Playout winner = await ctxWinner.Playouts.SingleAsync(p => p.Id == 1);
Playout loser = await ctxLoser.Playouts.SingleAsync(p => p.Id == 1);
winner.Version++;
(await ctxWinner.SaveChangesWithConcurrencyGuard(CancellationToken.None)).IsRight.ShouldBeTrue();
loser.Version++;
Either<BaseError, Unit> loserResult = await ctxLoser.SaveChangesWithConcurrencyGuard(CancellationToken.None);
loserResult.Match<BaseError?>(Right: _ => null, Left: e => e).ShouldBeOfType<PreconditionFailedError>();
(await ReadPlayoutVersion(1)).ShouldBe(2);
}
[Test]
public async Task SaveChangesForcingVersion_Should_Force_Write_Past_A_Concurrent_Bump_Without_Reverting_It()
{
await SeedPlayout(1, version: 1);
await using TvContext ctxSettings = _db.CreateContext();
await using TvContext ctxBumper = _db.CreateContext();
Playout settings = await ctxSettings.Playouts.SingleAsync(p => p.Id == 1);
Playout bumper = await ctxBumper.Playouts.SingleAsync(p => p.Id == 1);
// A replace-all editor bumps the version in another context after the settings writer loaded.
bumper.Version++;
await ctxBumper.SaveChangesAsync();
// The non-participating settings writer changes a root scalar against the now-stale version. Plain
// SaveChangesAsync would throw DbUpdateConcurrencyException (proven by the racing test above); the
// forcing helper must land the write instead (Phase-1 force-write) and NOT revert the bump.
settings.DailyRebuildTime = TimeSpan.FromHours(3);
await ctxSettings.SaveChangesForcingVersion(CancellationToken.None);
await using TvContext verify = _db.CreateContext();
Playout result = await verify.Playouts.SingleAsync(p => p.Id == 1);
result.DailyRebuildTime.ShouldBe(TimeSpan.FromHours(3));
result.Version.ShouldBe(2);
}
private static BaseError LeftOf<TR>(Either<BaseError, TR> either) =>
either.Match(Left: e => e, Right: _ => throw new AssertionException("Expected a Left result"));
@@ -454,7 +454,8 @@ public class ChannelControllerTests
null,
null,
null,
null);
null,
0);
private static ChannelViewModel MakeVm(int id) =>
new(
@@ -8,6 +8,7 @@ using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using LanguageExt;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
using NSubstitute;
@@ -28,7 +29,11 @@ public class CollectionControllerTests
public void SetUp()
{
_mediator = Substitute.For<IMediator>();
_controller = new CollectionController(_mediator);
_controller = new CollectionController(_mediator)
{
// Real HttpContext so the #253 ETag/If-Match concurrency headers can be read/written.
ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }
};
}
[Test]
@@ -7,6 +7,7 @@ using ErsatzTV.Core.Api.MediaCollections;
using ErsatzTV.Core.Domain;
using LanguageExt;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
using NSubstitute;
@@ -24,7 +25,11 @@ public class MultiCollectionControllerTests
public void SetUp()
{
_mediator = Substitute.For<IMediator>();
_controller = new MultiCollectionController(_mediator);
_controller = new MultiCollectionController(_mediator)
{
// Real HttpContext so the #253 ETag/If-Match concurrency headers can be read/written.
ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }
};
}
private MultiCollectionController _controller = null!;
@@ -17,6 +17,7 @@ using ErsatzTV.Core.Interfaces.Locking;
using ErsatzTV.Core.Scheduling;
using LanguageExt;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
using NSubstitute;
@@ -39,7 +40,11 @@ public class PlayoutControllerTests
{
_mediator = Substitute.For<IMediator>();
_entityLocker = Substitute.For<IEntityLocker>();
_controller = new PlayoutController(_mediator, _entityLocker);
_controller = new PlayoutController(_mediator, _entityLocker)
{
// Real HttpContext so the #253 ETag/If-Match concurrency headers can be read/written.
ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }
};
}
[Test]
@@ -1307,7 +1312,8 @@ public class PlayoutControllerTests
null,
new PlayoutBuildStatus(),
null,
null);
null,
0);
private static PlayoutResponseModel ToResponse(PlayoutNameViewModel vm, bool isLocked = false) =>
PlayoutResponseModel.From(
@@ -7,6 +7,7 @@ using ErsatzTV.Core.Api.MediaCollections;
using ErsatzTV.Core.Domain;
using LanguageExt;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
using NSubstitute;
@@ -24,7 +25,11 @@ public class RerunCollectionControllerTests
public void SetUp()
{
_mediator = Substitute.For<IMediator>();
_controller = new RerunCollectionController(_mediator);
_controller = new RerunCollectionController(_mediator)
{
// Real HttpContext so the #253 ETag/If-Match concurrency headers can be read/written.
ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }
};
}
private RerunCollectionController _controller = null!;
@@ -49,6 +49,15 @@ public class CollectionController(IMediator mediator) : ControllerBase
int clampedPageNum = Math.Max(0, pageNum);
int clampedPageSize = Math.Clamp(pageSize, 1, 100);
// The items GET is the reorder editor's load endpoint: emit the collection's version as the
// concurrency ETag (issue #253). The response carries children, so read the root separately.
Option<MediaCollectionViewModel> maybeCollection =
await mediator.Send(new GetCollectionById(id), cancellationToken);
foreach (MediaCollectionViewModel collection in maybeCollection)
{
ConcurrencyHeaders.SetETag(Response, collection.Version);
}
Either<BaseError, PagedLibraryBrowseItemsResponseModel> result = await mediator.Send(
new GetCollectionItems(id, clampedPageNum, clampedPageSize),
cancellationToken);
@@ -105,13 +114,21 @@ public class CollectionController(IMediator mediator) : ControllerBase
"UseCustomPlaybackOrder on the collection for this order to take effect.")]
[EndpointGroupName("general")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status412PreconditionFailed)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> UpdateCustomOrder(
int id,
[Required] [FromBody] UpdateCollectionCustomOrderRequest request,
CancellationToken cancellationToken)
{
IfMatchCondition ifMatch = ConcurrencyHeaders.ParseIfMatch(Request);
if (ifMatch.Kind is IfMatchKind.Malformed)
{
return ConcurrencyHeaders.MalformedIfMatchProblem();
}
Option<MediaCollectionViewModel> maybeCollection =
await mediator.Send(new GetCollectionById(id), cancellationToken);
if (maybeCollection.IsNone)
@@ -119,8 +136,18 @@ public class CollectionController(IMediator mediator) : ControllerBase
return ApiResults.NotFoundProblem();
}
Either<BaseError, Unit> result = await mediator.Send(request.ToCommand(id), cancellationToken);
return result.ToDeletedResult();
Either<BaseError, Unit> result =
await mediator.Send(request.ToCommand(id, ifMatch.ExpectedVersion), cancellationToken);
return await result.Match(
Left: error => Task.FromResult(error.ToErrorResult()),
Right: async _ =>
{
// Emit the new ETag on the bodyless 204 so a same-tab second save doesn't 412 (#253).
Option<MediaCollectionViewModel> refreshed =
await mediator.Send(new GetCollectionById(id), cancellationToken);
ConcurrencyHeaders.SetETag(Response, refreshed.Map(c => c.Version).IfNone(0));
return (IActionResult)new NoContentResult();
});
}
[HttpDelete("/api/collections/{id:int}")]
@@ -48,6 +48,13 @@ public class MultiCollectionController(IMediator mediator) : ControllerBase
{
Option<MultiCollectionViewModel> result =
await mediator.Send(new GetMultiCollectionById(id), cancellationToken);
// This by-id GET is the editor's load endpoint: emit the concurrency ETag (issue #253).
foreach (MultiCollectionViewModel vm in result)
{
ConcurrencyHeaders.SetETag(Response, vm.Version);
}
return result.Map(ProjectToResponseModel).ToGetResult();
}
@@ -74,14 +81,23 @@ public class MultiCollectionController(IMediator mediator) : ControllerBase
[EndpointSummary("Update a multi collection")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(MultiCollectionResponseModel), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status412PreconditionFailed)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> Update(
int id,
[Required] [FromBody] UpdateMultiCollectionRequest request,
CancellationToken cancellationToken)
{
Either<BaseError, Unit> result = await mediator.Send(request.ToCommand(id), cancellationToken);
IfMatchCondition ifMatch = ConcurrencyHeaders.ParseIfMatch(Request);
if (ifMatch.Kind is IfMatchKind.Malformed)
{
return ConcurrencyHeaders.MalformedIfMatchProblem();
}
Either<BaseError, Unit> result =
await mediator.Send(request.ToCommand(id, ifMatch.ExpectedVersion), cancellationToken);
return await result.Match(
Left: error => Task.FromResult(error.ToErrorResult()),
Right: async _ =>
@@ -89,7 +105,12 @@ public class MultiCollectionController(IMediator mediator) : ControllerBase
Option<MultiCollectionViewModel> multiCollection =
await mediator.Send(new GetMultiCollectionById(id), cancellationToken);
return multiCollection.Match(
Some: vm => (IActionResult)new OkObjectResult(ProjectToResponseModel(vm)),
Some: vm =>
{
// Emit the new ETag so a same-tab second save doesn't 412 against its own write (#253).
ConcurrencyHeaders.SetETag(Response, vm.Version);
return (IActionResult)new OkObjectResult(ProjectToResponseModel(vm));
},
None: () => ApiResults.NotFoundProblem());
});
}
+35 -2
View File
@@ -295,6 +295,9 @@ public class PlayoutController(IMediator mediator, IEntityLocker entityLocker) :
}
}
// The GET returns children, so read the playout's version for the concurrency ETag (issue #253).
ConcurrencyHeaders.SetETag(Response, maybePlayout.Map(p => p.Version).IfNone(0));
List<PlayoutAlternateScheduleViewModel> items =
await mediator.Send(new GetPlayoutAlternateSchedules(id), cancellationToken);
return new OkObjectResult(items.OrderBy(i => i.Index).Select(ToResponse).ToList());
@@ -310,14 +313,22 @@ public class PlayoutController(IMediator mediator, IEntityLocker entityLocker) :
"at least one item, and every ProgramScheduleId must exist. Only valid for Classic playouts.")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(List<PlayoutAlternateScheduleResponseModel>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status409Conflict)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status412PreconditionFailed)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> ReplaceAlternateSchedules(
int id,
[Required] [FromBody] ReplacePlayoutAlternateSchedulesRequest request,
CancellationToken cancellationToken)
{
IfMatchCondition ifMatch = ConcurrencyHeaders.ParseIfMatch(Request);
if (ifMatch.Kind is IfMatchKind.Malformed)
{
return ConcurrencyHeaders.MalformedIfMatchProblem();
}
if (entityLocker.IsPlayoutLocked(id))
{
return PlayoutLockedProblem();
@@ -358,11 +369,17 @@ public class PlayoutController(IMediator mediator, IEntityLocker entityLocker) :
return BaseError.New($"[ProgramScheduleId] {missingScheduleIds[0]} does not exist").ToErrorResult();
}
Either<BaseError, Unit> result = await mediator.Send(request.ToCommand(id), cancellationToken);
Either<BaseError, Unit> result =
await mediator.Send(request.ToCommand(id, ifMatch.ExpectedVersion), cancellationToken);
return await result.Match(
Left: error => Task.FromResult(error.ToErrorResult()),
Right: async _ =>
{
// Emit the new ETag (post-bump) so a same-tab second save doesn't 412 against its own write (#253).
Option<PlayoutNameViewModel> refreshedPlayout =
await mediator.Send(new GetPlayoutById(id), cancellationToken);
ConcurrencyHeaders.SetETag(Response, refreshedPlayout.Map(p => p.Version).IfNone(0));
List<PlayoutAlternateScheduleViewModel> refreshed =
await mediator.Send(new GetPlayoutAlternateSchedules(id), cancellationToken);
return (IActionResult)new OkObjectResult(refreshed.OrderBy(i => i.Index).Select(ToResponse).ToList());
@@ -395,6 +412,9 @@ public class PlayoutController(IMediator mediator, IEntityLocker entityLocker) :
}
}
// The GET returns children, so read the playout's version for the concurrency ETag (issue #253).
ConcurrencyHeaders.SetETag(Response, maybePlayout.Map(p => p.Version).IfNone(0));
List<PlayoutTemplateViewModel> items = await mediator.Send(new GetPlayoutTemplates(id), cancellationToken);
return new OkObjectResult(items.OrderBy(i => i.Index).Select(ToResponse).ToList());
}
@@ -408,14 +428,22 @@ public class PlayoutController(IMediator mediator, IEntityLocker entityLocker) :
"supplied DecoTemplateId must exist. An empty list clears all templates. Only valid for Block playouts.")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(List<PlayoutTemplateResponseModel>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status409Conflict)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status412PreconditionFailed)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> ReplaceTemplates(
int id,
[Required] [FromBody] ReplacePlayoutTemplatesRequest request,
CancellationToken cancellationToken)
{
IfMatchCondition ifMatch = ConcurrencyHeaders.ParseIfMatch(Request);
if (ifMatch.Kind is IfMatchKind.Malformed)
{
return ConcurrencyHeaders.MalformedIfMatchProblem();
}
if (entityLocker.IsPlayoutLocked(id))
{
return PlayoutLockedProblem();
@@ -463,12 +491,17 @@ public class PlayoutController(IMediator mediator, IEntityLocker entityLocker) :
}
}
Option<BaseError> result = await mediator.Send(request.ToCommand(id), cancellationToken);
Option<BaseError> result =
await mediator.Send(request.ToCommand(id, ifMatch.ExpectedVersion), cancellationToken);
foreach (BaseError error in result)
{
return error.ToErrorResult();
}
// Emit the new ETag (post-bump) so a same-tab second save doesn't 412 against its own write (#253).
Option<PlayoutNameViewModel> refreshedPlayout = await mediator.Send(new GetPlayoutById(id), cancellationToken);
ConcurrencyHeaders.SetETag(Response, refreshedPlayout.Map(p => p.Version).IfNone(0));
List<PlayoutTemplateViewModel> refreshed = await mediator.Send(new GetPlayoutTemplates(id), cancellationToken);
return new OkObjectResult(refreshed.OrderBy(i => i.Index).Select(ToResponse).ToList());
}
@@ -8,10 +8,11 @@ public record ReplacePlayoutAlternateSchedulesRequest(List<PlayoutAlternateSched
// is the lowest priority (the catch-all default whose schedule becomes the playout's default
// schedule). This mirrors the Blazor editor, which lists items top-to-bottom in priority order
// and writes the highest-Index item's schedule as the playout default.
public ReplacePlayoutAlternateScheduleItems ToCommand(int playoutId) =>
public ReplacePlayoutAlternateScheduleItems ToCommand(int playoutId, Option<int> expectedVersion = default) =>
new(
playoutId,
(Items ?? [])
.Select((item, index) => item.ToReplaceItem(index))
.ToList());
.ToList(),
expectedVersion);
}
@@ -5,10 +5,11 @@ namespace ErsatzTV.Controllers.Api.Requests;
public record ReplacePlayoutTemplatesRequest(List<PlayoutTemplateItemRequest> Items)
{
// Index is assigned from array order (top-to-bottom priority), mirroring the Blazor editor.
public ReplacePlayoutTemplateItems ToCommand(int playoutId) =>
public ReplacePlayoutTemplateItems ToCommand(int playoutId, Option<int> expectedVersion = default) =>
new(
playoutId,
(Items ?? [])
.Select((item, index) => item.ToReplaceItem(index))
.ToList());
.ToList(),
expectedVersion);
}
@@ -4,10 +4,11 @@ namespace ErsatzTV.Controllers.Api.Requests;
public record UpdateCollectionCustomOrderRequest(List<int> MediaItemIds)
{
public UpdateCollectionCustomOrder ToCommand(int collectionId) =>
public UpdateCollectionCustomOrder ToCommand(int collectionId, Option<int> expectedVersion = default) =>
new(
collectionId,
(MediaItemIds ?? [])
.Select((mediaItemId, index) => new MediaItemCustomOrder(mediaItemId, index))
.ToList());
.ToList(),
expectedVersion);
}
@@ -6,7 +6,7 @@ namespace ErsatzTV.Controllers.Api.Requests;
public record UpdateMultiCollectionRequest(string Name, List<MultiCollectionItemRequest> Items)
{
public UpdateMultiCollection ToCommand(int id) =>
public UpdateMultiCollection ToCommand(int id, Option<int> expectedVersion = default) =>
new(
id,
Name,
@@ -16,5 +16,6 @@ public record UpdateMultiCollectionRequest(string Name, List<MultiCollectionItem
i.SmartCollectionId,
i.ScheduleAsGroup,
i.PlaybackOrder))
.ToList());
.ToList(),
expectedVersion);
}
@@ -11,7 +11,7 @@ public record UpdateRerunCollectionRequest(
PlaybackOrder FirstRunPlaybackOrder,
PlaybackOrder RerunPlaybackOrder)
{
public UpdateRerunCollection ToCommand(int id)
public UpdateRerunCollection ToCommand(int id, Option<int> expectedVersion = default)
{
(MediaCollectionViewModel collection,
MultiCollectionViewModel multiCollection,
@@ -28,6 +28,7 @@ public record UpdateRerunCollectionRequest(
smartCollection,
mediaItem,
FirstRunPlaybackOrder,
RerunPlaybackOrder);
RerunPlaybackOrder,
expectedVersion);
}
}
@@ -48,6 +48,13 @@ public class RerunCollectionController(IMediator mediator) : ControllerBase
{
Option<RerunCollectionViewModel> result =
await mediator.Send(new GetRerunCollectionById(id), cancellationToken);
// This by-id GET is the editor's load endpoint: emit the concurrency ETag (issue #253).
foreach (RerunCollectionViewModel vm in result)
{
ConcurrencyHeaders.SetETag(Response, vm.Version);
}
return result.Map(ProjectToResponseModel).ToGetResult();
}
@@ -81,13 +88,21 @@ public class RerunCollectionController(IMediator mediator) : ControllerBase
[EndpointSummary("Update a rerun collection")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(RerunCollectionResponseModel), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status412PreconditionFailed)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> Update(
int id,
[Required] [FromBody] UpdateRerunCollectionRequest request,
CancellationToken cancellationToken)
{
IfMatchCondition ifMatch = ConcurrencyHeaders.ParseIfMatch(Request);
if (ifMatch.Kind is IfMatchKind.Malformed)
{
return ConcurrencyHeaders.MalformedIfMatchProblem();
}
if (!RerunCollectionRequestMapping.IsSupportedSelectionType(request.CollectionType))
{
return BaseError.New(
@@ -95,7 +110,8 @@ public class RerunCollectionController(IMediator mediator) : ControllerBase
.ToErrorResult();
}
Either<BaseError, Unit> result = await mediator.Send(request.ToCommand(id), cancellationToken);
Either<BaseError, Unit> result =
await mediator.Send(request.ToCommand(id, ifMatch.ExpectedVersion), cancellationToken);
return await result.Match(
Left: error => Task.FromResult(error.ToErrorResult()),
Right: async _ =>
@@ -103,7 +119,12 @@ public class RerunCollectionController(IMediator mediator) : ControllerBase
Option<RerunCollectionViewModel> rerunCollection =
await mediator.Send(new GetRerunCollectionById(id), cancellationToken);
return rerunCollection.Match(
Some: vm => (IActionResult)new OkObjectResult(ProjectToResponseModel(vm)),
Some: vm =>
{
// Emit the new ETag so a same-tab second save doesn't 412 against its own write (#253).
ConcurrencyHeaders.SetETag(Response, vm.Version);
return (IActionResult)new OkObjectResult(ProjectToResponseModel(vm));
},
None: () => ApiResults.NotFoundProblem());
});
}
+15
View File
@@ -1,6 +1,7 @@
using System.Globalization;
using LanguageExt;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
namespace ErsatzTV.Extensions;
@@ -74,4 +75,18 @@ public static class ConcurrencyHeaders
public static void SetETag(HttpResponse response, int version) =>
response.Headers.ETag = $"\"{version}\"";
/// <summary>
/// The 400 response for a syntactically-invalid <c>If-Match</c> header
/// (<see cref="IfMatchKind.Malformed" />). Shared by the replace-all PUT endpoints so the
/// fail-safe rejection wording stays consistent (issue #253 §7a).
/// </summary>
public static IActionResult MalformedIfMatchProblem() =>
new BadRequestObjectResult(
new ProblemDetails
{
Status = StatusCodes.Status400BadRequest,
Title = "Invalid If-Match header",
Detail = "If-Match must be a strong ETag of the resource version (e.g. \"3\") or \"*\"."
});
}
+205
View File
@@ -2981,6 +2981,26 @@
"204": {
"description": "No Content"
},
"400": {
"description": "Bad Request",
"content": {
"text/plain": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"text/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
}
},
"404": {
"description": "Not Found",
"content": {
@@ -3001,6 +3021,26 @@
}
}
},
"412": {
"description": "Precondition Failed",
"content": {
"text/plain": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"text/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
}
},
"422": {
"description": "Unprocessable Entity",
"content": {
@@ -8362,6 +8402,26 @@
}
}
},
"400": {
"description": "Bad Request",
"content": {
"text/plain": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"text/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
}
},
"404": {
"description": "Not Found",
"content": {
@@ -8382,6 +8442,26 @@
}
}
},
"412": {
"description": "Precondition Failed",
"content": {
"text/plain": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"text/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
}
},
"422": {
"description": "Unprocessable Entity",
"content": {
@@ -10236,6 +10316,26 @@
}
}
},
"400": {
"description": "Bad Request",
"content": {
"text/plain": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"text/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
}
},
"404": {
"description": "Not Found",
"content": {
@@ -10276,6 +10376,26 @@
}
}
},
"412": {
"description": "Precondition Failed",
"content": {
"text/plain": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"text/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
}
},
"422": {
"description": "Unprocessable Entity",
"content": {
@@ -10462,6 +10582,26 @@
}
}
},
"400": {
"description": "Bad Request",
"content": {
"text/plain": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"text/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
}
},
"404": {
"description": "Not Found",
"content": {
@@ -10502,6 +10642,26 @@
}
}
},
"412": {
"description": "Precondition Failed",
"content": {
"text/plain": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"text/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
}
},
"422": {
"description": "Unprocessable Entity",
"content": {
@@ -11962,6 +12122,26 @@
}
}
},
"400": {
"description": "Bad Request",
"content": {
"text/plain": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"text/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
}
},
"404": {
"description": "Not Found",
"content": {
@@ -11982,6 +12162,26 @@
}
}
},
"412": {
"description": "Precondition Failed",
"content": {
"text/plain": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
},
"text/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
}
},
"422": {
"description": "Unprocessable Entity",
"content": {
@@ -21588,6 +21788,11 @@
"useCustomPlaybackOrder": {
"type": "boolean"
},
"version": {
"type": "integer",
"format": "int32",
"default": 0
},
"mediaItemId": {
"type": "integer",
"format": "int32"
+18
View File
@@ -374,6 +374,24 @@ save → 412 (prove it non-vacuous by dropping `.IsConcurrencyToken()` and watch
Phase 2 (a later PR) flips a missing `If-Match` from force-write to **428 Precondition Required** once
every editor echoes and one release soaks.
**Fan-out status.** Block (#2) is the reference. **PR2** wired the RR + Reconcile aggregates
(Template #3, DecoTemplate #4, Playlist #5, schedule-items #1). **PR3** wired the Diff + Scalar aggregates:
Collection custom-order #6, Playout alternate-schedules #7 and templates #8 (both share `Playout.Version`;
their `catch(Exception)`→422 handlers were restructured so the guard's `PreconditionFailedError` Left
returns before the catch — §9/H1), MultiCollection #9, and RerunCollection #10. Two M2 gate notes for the
`SaveChangesAsync() > 0` handlers: the RerunCollection/Collection-custom-order refresh now runs on any
successful save (the bump makes the gate always-true); MultiCollection keeps its "name-only change → no
playout rebuild" optimization by bumping on the **first** (name) save so the **second** (items) save's
`> 0` still means "items changed". The one bulk writer in scope, `UpdateDefaultDecoHandler`, bumps via
`.SetProperty(x => x.Version, x => x.Version + 1)` (bulk `ExecuteUpdate` can't throw the concurrency
exception, so it needs no guard). **Deferred (tracked follow-up):** the *other* same-root config
writers — non-bulk siblings like `UpdateCollectionHandler`/`RemoveItemsFromCollectionHandler`,
`UpdatePlayoutHandler` and the `ScheduleFile` handlers, and the repository-mediated `Add*ToCollection`
family — do **not** yet rotate their aggregate's ETag. The primary endpoints' own bump+guard fully cover
the two-tab lost-update this contract targets; the deferred writers only affect cross-editor ETag rotation,
and adding an unconditional bump to a handler that uses plain `SaveChangesAsync` (not the guard) would open
a new `DbUpdateConcurrencyException`→500 path — so they need a uniform guard+bump pass of their own.
## 7b. Post-commit side effects run on `CancellationToken.None`
Once a command handler's `await dbContext.SaveChangesAsync(cancellationToken)` (or repository upsert)
+42
View File
@@ -778,6 +778,48 @@ the versioned aggregates — several of which this sweep also touched (post-comm
region). Low git-conflict risk, but merge `main` in and expect to see the `CancellationToken.None`
convention already present on the post-commit enqueues.
## 2026-07-11 — #253 PR3: Diff + Scalar concurrency fan-out (Collection / Playout×2 / MultiCollection / RerunCollection)
**Context.** PR3 of the #253 optimistic-concurrency arc fans the frozen Block recipe (api-conventions §7a)
across the five Diff/Scalar aggregates. Three judgment calls beyond the mechanical copy:
**H1 — Playout `catch(Exception)`→422.** The two Playout replace handlers wrap `SaveChangesAsync` in a
`catch(Exception)` that maps any exception to a bare `BaseError` (→ 422). Rather than let the guard's
concurrency failure be reshaped into a 422, the guarded save (`SaveChangesWithConcurrencyGuard`) returns a
`PreconditionFailedError` **Left as a value** and the handler returns it before the post-commit block —
so it never reaches the catch. Proven by the pre-check-subtype tests (a `.Apply` flatten would fail
`ShouldBeOfType<PreconditionFailedError>`) plus a non-vacuous Playout racing-save test.
**M2 — the `SaveChangesAsync() > 0` gates.** RerunCollection and Collection-custom-order run their
playout-refresh **unconditionally** on a successful save (the unconditional `Version++` makes the old gate
always-true; the "nothing changed" branch is dead). MultiCollection is the exception: it saved the name
first specifically so a name-only change wouldn't rebuild playouts, so we bump `Version` on that **first**
save and leave the **second** (items) save's `> 0` gate intact — a name-only edit still bumps + rotates the
ETag but does not rebuild. Enumerating every behavior the gate provided before reworking it (the #232 lesson).
**Sibling-writer scope (deferred).** §7a's config-only boundary says every writer of an aggregate's
editor-visible config bumps `Version`. PR3 ships the five primary endpoints' full contract + the one
design-named bulk writer (`UpdateDefaultDecoHandler`, safe via `.SetProperty`). It **defers** the other
same-root non-bulk config writers (`UpdateCollectionHandler`, `RemoveItemsFromCollectionHandler`,
`UpdatePlayoutHandler`, the `ScheduleFile` handlers) and the repository-mediated `Add*ToCollection` family.
Rationale: the primary endpoints' own bump+guard fully cover the two-tab lost-update the issue targets;
the deferred writers only affect cross-editor ETag *rotation*, and adding an unconditional bump to a handler
that uses plain `SaveChangesAsync` (not the guard) converts a latent lost-update into a **new 500**
(`DbUpdateConcurrencyException`) — doing it safely needs a uniform guard+bump+412 pass of its own, better
done with the #197 contract work. Tracked as a follow-up issue.
**VMs.** `Playout.Version` surfaces via `PlayoutNameViewModel` (required arg); the three collection VMs
(`MediaCollectionViewModel`, `MultiCollectionViewModel`, `RerunCollectionViewModel`) carry `int Version = 0`
(defaulted — 0 for the selection-placeholder constructions, real value from the Mapper projection).
Header-only via ETag, never echoed in a response body (the Block precedent).
**Post-merge addendum (PR3 review, #269).** Activating the `Version` token means EF guards *every* root
UPDATE, so non-participating root-scalar writers that use plain `SaveChangesAsync` (playout settings /
schedule-file / on-demand-checkpoint, collection name) would 500 on a concurrent bump. The realistic
UPDATE writers were fixed in-PR with `ConcurrencyExtensions.SaveChangesForcingVersion` (Phase-1
force-write on conflict: adopt the stored token, retry, never revert the concurrent bump). The deferral
above is re-scoped to the DELETE handlers + repository `Add*` writers only (→ #269).
## 2026-07-11 — External Collections in the SPA derives from `getMediaSources()`; collections scans are optimistically bounded (#91b Libraries.razor parity)
**Context.** The last SPA pre-work before deleting Blazor `Libraries.razor` was wiring the shipped
+6
View File
@@ -153,6 +153,12 @@ fresher edit:
"changed elsewhere — reload (unsaved changes discarded)" `ConfirmDialog` (Reload bumps `reloadKey`),
distinct from a 409 ("build in progress — retry shortly"). All other errors stay the generic save-error
path. Reference: `web/src/screens/BlocksScreen.tsx` `BlockEditor`.
- **List-derived editors** (Multi/Rerun collections open the editor from a paged-list row, not a per-record
GET): fetch the single record via the `…WithMeta` by-id helper (`getMultiCollectionWithMeta` /
`getRerunCollectionWithMeta`) when the editor mounts, and build the draft from **that** response — so the
ETag and the draft data come from one read and stay consistent (the fail-safe ordering; don't pair a
list-row draft with a separately-fetched ETag). Editors that navigate back to the list on save (Playout,
Multi/Rerun, Collection reorder) need only the 412 branch — no post-save ETag rotation.
## 5. Artwork rendering
+27 -3
View File
@@ -1,4 +1,4 @@
import { ApiError, request } from './client';
import { ApiError, request, requestWithMeta, type ResponseWithMeta } from './client';
import type { components } from './generated/v1';
import type { LibraryBrowseItem, PagedLibraryBrowseItems } from './libraryBrowse';
@@ -57,12 +57,36 @@ export function getCollectionItems(
return request<PagedLibraryBrowseItems>(`/api/collections/${id}/items?${params.toString()}`);
}
/** Load a page of collection items together with the collection's concurrency ETag (issue #253). */
export function getCollectionItemsWithMeta(
id: number,
pageNum = 0,
pageSize = 100
): Promise<ResponseWithMeta<PagedLibraryBrowseItems>> {
const params = new URLSearchParams({
pageNum: String(pageNum),
pageSize: String(pageSize)
});
return requestWithMeta<PagedLibraryBrowseItems>(`/api/collections/${id}/items?${params.toString()}`);
}
// Replaces a manual collection's custom order wholesale: the CustomIndex of each media item is
// derived from its position in `mediaItemIds`, so a partial array silently drops the items left
// out of it (#211). Callers must submit the full ordered id list.
export function updateCollectionCustomOrder(id: number, mediaItemIds: number[]): Promise<void> {
//
// Pass the last-seen ETag as `If-Match` to reject a stale overwrite with 412; the resolved
// value carries the new ETag for a subsequent save (issue #253).
export function updateCollectionCustomOrder(
id: number,
mediaItemIds: number[],
ifMatch?: string | null
): Promise<ResponseWithMeta<void>> {
const body: UpdateCollectionCustomOrderRequest = { mediaItemIds };
return request<void>(`/api/collections/${id}/custom-order`, { body, method: 'PUT' });
return requestWithMeta<void>(`/api/collections/${id}/custom-order`, {
body,
method: 'PUT',
headers: ifMatch ? { 'If-Match': ifMatch } : undefined
});
}
/* ---------- smart collections ---------- */
+1
View File
@@ -801,6 +801,7 @@ export interface components {
"id": number;
"name": null | string;
"useCustomPlaybackOrder": boolean;
"version"?: number;
"mediaItemId"?: number;
"title"?: null | string;
"subtitle"?: null | string;
+20 -3
View File
@@ -1,4 +1,4 @@
import { ApiError, request } from './client';
import { ApiError, request, requestWithMeta, type ResponseWithMeta } from './client';
import type { components } from './generated/v1';
export type MultiCollection = components['schemas']['MultiCollectionResponseModel'];
@@ -38,12 +38,29 @@ export function getMultiCollection(id: number): Promise<MultiCollection> {
return request<MultiCollection>(`/api/multi-collections/${id}`);
}
/** Load a single multi-collection together with its concurrency ETag (issue #253). */
export function getMultiCollectionWithMeta(id: number): Promise<ResponseWithMeta<MultiCollection>> {
return requestWithMeta<MultiCollection>(`/api/multi-collections/${id}`);
}
export function createMultiCollection(body: CreateMultiCollectionRequest): Promise<MultiCollection> {
return request<MultiCollection>('/api/multi-collections', { body, method: 'POST' });
}
export function updateMultiCollection(id: number, body: UpdateMultiCollectionRequest): Promise<MultiCollection> {
return request<MultiCollection>(`/api/multi-collections/${id}`, { body, method: 'PUT' });
/**
* Update a multi-collection. Pass the last-seen ETag as `If-Match` to reject a stale overwrite
* with 412; the resolved value carries the new ETag for a subsequent save (issue #253).
*/
export function updateMultiCollection(
id: number,
body: UpdateMultiCollectionRequest,
ifMatch?: string | null
): Promise<ResponseWithMeta<MultiCollection>> {
return requestWithMeta<MultiCollection>(`/api/multi-collections/${id}`, {
body,
method: 'PUT',
headers: ifMatch ? { 'If-Match': ifMatch } : undefined
});
}
export function deleteMultiCollection(id: number): Promise<void> {
+33 -9
View File
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { ApiError, request } from './client';
import { ApiError, request, requestWithMeta, type ResponseWithMeta } from './client';
import type { components } from './generated/v1';
export type PlayoutSummary = components['schemas']['PlayoutListItemResponseModel'];
@@ -164,13 +164,26 @@ export function getAlternateSchedules(playoutId: number): Promise<PlayoutAlterna
return request<PlayoutAlternateSchedule[]>(`/api/playouts/${playoutId}/alternate-schedules`);
}
/** Load alternate schedules together with the playout's concurrency ETag (issue #253). */
export function getAlternateSchedulesWithMeta(
playoutId: number
): Promise<ResponseWithMeta<PlayoutAlternateSchedule[]>> {
return requestWithMeta<PlayoutAlternateSchedule[]>(`/api/playouts/${playoutId}/alternate-schedules`);
}
/**
* Replace a playout's alternate schedules. Pass the last-seen ETag as `If-Match` to reject a stale
* overwrite with 412; the resolved value carries the new ETag for a subsequent save (issue #253).
*/
export function replaceAlternateSchedules(
playoutId: number,
body: ReplacePlayoutAlternateSchedulesRequest
): Promise<PlayoutAlternateSchedule[]> {
return request<PlayoutAlternateSchedule[]>(`/api/playouts/${playoutId}/alternate-schedules`, {
body: ReplacePlayoutAlternateSchedulesRequest,
ifMatch?: string | null
): Promise<ResponseWithMeta<PlayoutAlternateSchedule[]>> {
return requestWithMeta<PlayoutAlternateSchedule[]>(`/api/playouts/${playoutId}/alternate-schedules`, {
body,
method: 'PUT'
method: 'PUT',
headers: ifMatch ? { 'If-Match': ifMatch } : undefined
});
}
@@ -178,13 +191,24 @@ export function getPlayoutTemplates(playoutId: number): Promise<PlayoutTemplate[
return request<PlayoutTemplate[]>(`/api/playouts/${playoutId}/templates`);
}
/** Load playout templates together with the playout's concurrency ETag (issue #253). */
export function getPlayoutTemplatesWithMeta(playoutId: number): Promise<ResponseWithMeta<PlayoutTemplate[]>> {
return requestWithMeta<PlayoutTemplate[]>(`/api/playouts/${playoutId}/templates`);
}
/**
* Replace a playout's templates. Pass the last-seen ETag as `If-Match` to reject a stale overwrite
* with 412; the resolved value carries the new ETag for a subsequent save (issue #253).
*/
export function replacePlayoutTemplates(
playoutId: number,
body: ReplacePlayoutTemplatesRequest
): Promise<PlayoutTemplate[]> {
return request<PlayoutTemplate[]>(`/api/playouts/${playoutId}/templates`, {
body: ReplacePlayoutTemplatesRequest,
ifMatch?: string | null
): Promise<ResponseWithMeta<PlayoutTemplate[]>> {
return requestWithMeta<PlayoutTemplate[]>(`/api/playouts/${playoutId}/templates`, {
body,
method: 'PUT'
method: 'PUT',
headers: ifMatch ? { 'If-Match': ifMatch } : undefined
});
}
+20 -3
View File
@@ -1,4 +1,4 @@
import { ApiError, request } from './client';
import { ApiError, request, requestWithMeta, type ResponseWithMeta } from './client';
import type { components } from './generated/v1';
export type RerunCollection = components['schemas']['RerunCollectionResponseModel'];
@@ -36,12 +36,29 @@ export function getRerunCollection(id: number): Promise<RerunCollection> {
return request<RerunCollection>(`/api/rerun-collections/${id}`);
}
/** Load a single rerun collection together with its concurrency ETag (issue #253). */
export function getRerunCollectionWithMeta(id: number): Promise<ResponseWithMeta<RerunCollection>> {
return requestWithMeta<RerunCollection>(`/api/rerun-collections/${id}`);
}
export function createRerunCollection(body: CreateRerunCollectionRequest): Promise<RerunCollection> {
return request<RerunCollection>('/api/rerun-collections', { body, method: 'POST' });
}
export function updateRerunCollection(id: number, body: UpdateRerunCollectionRequest): Promise<RerunCollection> {
return request<RerunCollection>(`/api/rerun-collections/${id}`, { body, method: 'PUT' });
/**
* Update a rerun collection. Pass the last-seen ETag as `If-Match` to reject a stale overwrite
* with 412; the resolved value carries the new ETag for a subsequent save (issue #253).
*/
export function updateRerunCollection(
id: number,
body: UpdateRerunCollectionRequest,
ifMatch?: string | null
): Promise<ResponseWithMeta<RerunCollection>> {
return requestWithMeta<RerunCollection>(`/api/rerun-collections/${id}`, {
body,
method: 'PUT',
headers: ifMatch ? { 'If-Match': ifMatch } : undefined
});
}
export function deleteRerunCollection(id: number): Promise<void> {
+37 -5
View File
@@ -27,11 +27,13 @@ import {
} from '../components';
import {
addItemsToCollection,
ApiError,
createCollection,
createSmartCollection,
deleteCollection,
deleteSmartCollection,
getCollectionItems,
getCollectionItemsWithMeta,
getCollections,
getLibraryBrowseItems,
getSmartCollections,
@@ -513,7 +515,11 @@ function ManualItemsView({
const [reorderItems, setReorderItems] = useState<LibraryBrowseItem[] | null>(null);
const [reorderLoading, setReorderLoading] = useState(false);
const [reorderSaving, setReorderSaving] = useState(false);
const [conflictOpen, setConflictOpen] = useState(false);
const activeRef = useRef(true);
// Concurrency ETag (issue #253): captured from the first page of the reorder-mode items GET,
// sent as If-Match on the custom-order save.
const etagRef = useRef<string | null>(null);
// No synchronous setState here: `loading` starts true and flips false in `finally`, so
// this is safe to call from an effect. Reloads (after add/remove) reset to the first page.
@@ -586,9 +592,9 @@ function ManualItemsView({
setError(null);
try {
const first = await getCollectionItems(collection.id, 0, PAGE_SIZE);
let all = first.page ?? [];
const totalCount = first.totalCount ?? all.length;
const first = await getCollectionItemsWithMeta(collection.id, 0, PAGE_SIZE);
let all = first.data.page ?? [];
const totalCount = first.data.totalCount ?? all.length;
let pageNum = 1;
while (all.length < totalCount) {
@@ -604,6 +610,7 @@ function ManualItemsView({
}
if (activeRef.current) {
etagRef.current = first.etag;
setReorderItems(all);
setReordering(true);
}
@@ -651,7 +658,7 @@ function ManualItemsView({
try {
const mediaItemIds = reorderItems.map((item) => item.mediaItemId ?? item.id);
await updateCollectionCustomOrder(collection.id, mediaItemIds);
await updateCollectionCustomOrder(collection.id, mediaItemIds, etagRef.current);
if (activeRef.current) {
setReordering(false);
@@ -660,7 +667,13 @@ function ManualItemsView({
}
} catch (saveError) {
if (activeRef.current) {
setError(messageFromCollectionError(saveError, 'Unable to save order'));
if (saveError instanceof ApiError && saveError.status === 412) {
// Another edit landed since we loaded the reorder view — force a reload rather than
// overwriting it (#253).
setConflictOpen(true);
} else {
setError(messageFromCollectionError(saveError, 'Unable to save order'));
}
}
} finally {
if (activeRef.current) {
@@ -669,6 +682,14 @@ function ManualItemsView({
}
};
const reloadAfterConflict = () => {
setConflictOpen(false);
setError(null);
setReordering(false);
setReorderItems(null);
void enterReorder();
};
return (
<div className="ctv-collections">
<div className="ctv-channels-actionbar">
@@ -808,6 +829,17 @@ function ManualItemsView({
onClose={() => setPickerOpen(false)}
open={pickerOpen}
/>
<ConfirmDialog
cancelLabel="Keep editing"
confirmLabel="Reload"
message="This collection's order was changed elsewhere since you opened it. Reload to get the latest — your unsaved changes will be discarded."
onCancel={() => setConflictOpen(false)}
onConfirm={reloadAfterConflict}
open={conflictOpen}
title="Order changed elsewhere"
tone="danger"
/>
</div>
);
}
@@ -47,6 +47,14 @@ function mockApi(options: MockOptions = {}) {
}
}
// Single-record GET (the editor loads it on open for the #253 concurrency ETag) — must be
// matched before the list handler, which would otherwise swallow it with the paged shape.
const multiById = url.match(/^\/api\/multi-collections\/(\d+)$/);
if (multiById && method === 'GET') {
const found = (multi as Array<{ id: number }>).find((m) => String(m.id) === multiById[1]) ?? multi[0];
return Promise.resolve(jsonResponse(found));
}
if (url.startsWith('/api/multi-collections') && method === 'GET') {
return Promise.resolve(jsonResponse({ page: multi, totalCount: multi.length }));
}
+44 -5
View File
@@ -2,9 +2,11 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import { ArrowLeft, Check, Layers, Plus, Trash2, TriangleAlert } from 'lucide-react';
import { Badge, Button, Card, ConfirmDialog, IconButton, Input, Select, Spinner, Switch } from '../components';
import {
ApiError,
createMultiCollection,
deleteMultiCollection,
getCollections,
getMultiCollectionWithMeta,
getMultiCollections,
getSmartCollections,
messageFromMultiCollectionError,
@@ -111,15 +113,30 @@ function MultiCollectionEditor({
const [loadError, setLoadError] = useState<string | null>(null);
const [saveError, setSaveError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const [conflictOpen, setConflictOpen] = useState(false);
const [reloadKey, setReloadKey] = useState(0);
const activeRef = useRef(true);
// Concurrency ETag (issue #253): captured from the single-record GET when editing an existing
// multi-collection, sent as If-Match on save. There's no rotation-on-save because the editor
// always returns to the list after a successful save (see onSaved below).
const etagRef = useRef<string | null>(null);
useEffect(() => {
activeRef.current = true;
Promise.all([getCollections(), getSmartCollections()])
.then(([manual, smart]) => {
Promise.all([
getCollections(),
getSmartCollections(),
initial ? getMultiCollectionWithMeta(initial.id) : Promise.resolve(null)
])
.then(([manual, smart, mcMeta]) => {
if (activeRef.current) {
setCollections(manual);
setSmartCollections(smart);
if (mcMeta) {
etagRef.current = mcMeta.etag;
setName(mcMeta.data.name ?? '');
setItems(itemsFromMultiCollection(mcMeta.data));
}
setLoadError(null);
}
})
@@ -132,7 +149,7 @@ function MultiCollectionEditor({
return () => {
activeRef.current = false;
};
}, []);
}, [initial, reloadKey]);
const hasManual = (id: number) => items.some((item) => item.kind === 'manual' && item.id === id);
const hasSmart = (id: number) => items.some((item) => item.kind === 'smart' && item.id === id);
@@ -182,19 +199,30 @@ function MultiCollectionEditor({
try {
const body = { items: items.map(toItemRequest), name: trimmedName };
if (initial) {
await updateMultiCollection(initial.id, body);
await updateMultiCollection(initial.id, body, etagRef.current);
} else {
await createMultiCollection(body);
}
onSaved();
} catch (error) {
setSaveError(messageFromMultiCollectionError(error, 'Unable to save multi-collection'));
if (error instanceof ApiError && error.status === 412) {
// Another edit landed since we loaded — force a reload rather than overwriting it (#253).
setConflictOpen(true);
} else {
setSaveError(messageFromMultiCollectionError(error, 'Unable to save multi-collection'));
}
} finally {
setSaving(false);
}
};
const reloadAfterConflict = () => {
setConflictOpen(false);
setSaveError(null);
setReloadKey((key) => key + 1);
};
const collectionOptions = [
{ label: 'Select a collection…', value: '' },
...collections
@@ -316,6 +344,17 @@ function MultiCollectionEditor({
))
)}
</Card>
<ConfirmDialog
cancelLabel="Keep editing"
confirmLabel="Reload"
message="This was changed elsewhere since you opened it. Reload to get the latest — your unsaved changes will be discarded."
onCancel={() => setConflictOpen(false)}
onConfirm={reloadAfterConflict}
open={conflictOpen}
title="Multi-collection changed elsewhere"
tone="danger"
/>
</div>
);
}
+101 -28
View File
@@ -1,14 +1,15 @@
import { useEffect, useRef, useState } from 'react';
import { ArrowDown, ArrowLeft, ArrowRight, ArrowUp, CalendarDays, Check, Plus, Trash2, TriangleAlert } from 'lucide-react';
import { navigateToPath } from '../routing';
import { Badge, Button, Card, Checkbox, IconButton, Select, Spinner } from '../components';
import { Badge, Button, Card, Checkbox, ConfirmDialog, IconButton, Select, Spinner } from '../components';
import { daysInMonth, firstMatchingIndex } from './playoutTemplateCalendar';
import {
ApiError,
DAYS_OF_WEEK,
getAlternateSchedules,
getAlternateSchedulesWithMeta,
getDecoTemplates,
getPlayout,
getPlayoutTemplates,
getPlayoutTemplatesWithMeta,
getSchedules,
getTemplates,
messageFromPlayoutClientError,
@@ -428,18 +429,24 @@ export function PlayoutAlternateSchedulesScreen({ playoutId }: { playoutId: numb
const [loadError, setLoadError] = useState<null | string>(null);
const [saveError, setSaveError] = useState<null | string>(null);
const [saving, setSaving] = useState(false);
const [conflictOpen, setConflictOpen] = useState(false);
const [reloadKey, setReloadKey] = useState(0);
const activeRef = useRef(true);
// Concurrency ETag (issue #253): captured from the alternate-schedules GET, sent as If-Match on
// save. Both screens navigate away on a successful save, so there's no response ETag to rotate in.
const etagRef = useRef<string | null>(null);
useEffect(() => {
activeRef.current = true;
Promise.all([getPlayout(playoutId), getAlternateSchedules(playoutId), getSchedules()])
.then(([playout, alternates, allSchedules]) => {
Promise.all([getPlayout(playoutId), getAlternateSchedulesWithMeta(playoutId), getSchedules()])
.then(([playout, alternatesMeta, allSchedules]) => {
if (!activeRef.current) {
return;
}
etagRef.current = alternatesMeta.etag;
setChannelName(playout.channelName);
setSchedules(allSchedules);
const drafts = alternates.map((alternate) => altToDraft(alternate, allSchedules));
const drafts = alternatesMeta.data.map((alternate) => altToDraft(alternate, allSchedules));
setItems(drafts);
setSelectedKey(drafts.length === 1 ? drafts[0].key : null);
})
@@ -451,7 +458,7 @@ export function PlayoutAlternateSchedulesScreen({ playoutId }: { playoutId: numb
return () => {
activeRef.current = false;
};
}, [playoutId]);
}, [playoutId, reloadKey]);
if (loadError) {
return <LoadErrorState error={loadError} />;
@@ -516,24 +523,43 @@ export function PlayoutAlternateSchedulesScreen({ playoutId }: { playoutId: numb
}
setSaving(true);
setSaveError(null);
replaceAlternateSchedules(playoutId, {
items: items.map((item) => ({
id: item.id,
programScheduleId: item.programScheduleId,
...toRequestRecurrence(item)
}))
})
replaceAlternateSchedules(
playoutId,
{
items: items.map((item) => ({
id: item.id,
programScheduleId: item.programScheduleId,
...toRequestRecurrence(item)
}))
},
etagRef.current
)
.then(() => {
navigateToPath(PLAYOUTS_PATH);
})
.catch((error: unknown) => {
if (activeRef.current) {
if (!activeRef.current) {
return;
}
if (error instanceof ApiError && error.status === 412) {
// Another edit landed since we loaded — force a reload rather than overwriting it (#253).
setConflictOpen(true);
setSaving(false);
} else {
setSaveError(messageFromPlayoutClientError(error, 'Unable to save alternate schedules'));
setSaving(false);
}
});
};
const reloadAfterConflict = () => {
setConflictOpen(false);
setSaveError(null);
setItems(null);
setSelectedKey(null);
setReloadKey((key) => key + 1);
};
const scheduleNameOf = (id: number) => schedules.find((schedule) => schedule.id === id)?.name ?? '(none)';
// note: '(none)' also covers a schedule whose name is null
@@ -643,6 +669,17 @@ export function PlayoutAlternateSchedulesScreen({ playoutId }: { playoutId: numb
/>
</Card>
)}
<ConfirmDialog
cancelLabel="Keep editing"
confirmLabel="Reload"
message="This playout was changed elsewhere since you opened it. Reload to get the latest — your unsaved changes will be discarded."
onCancel={() => setConflictOpen(false)}
onConfirm={reloadAfterConflict}
open={conflictOpen}
title="Playout changed elsewhere"
tone="danger"
/>
</EditorChrome>
);
}
@@ -684,19 +721,25 @@ export function PlayoutTemplatesEditorScreen({ playoutId }: { playoutId: number
const [saveError, setSaveError] = useState<null | string>(null);
const [saving, setSaving] = useState(false);
const [showPreview, setShowPreview] = useState(false);
const [conflictOpen, setConflictOpen] = useState(false);
const [reloadKey, setReloadKey] = useState(0);
const activeRef = useRef(true);
// Concurrency ETag (issue #253): captured from the templates GET, sent as If-Match on save. Both
// screens navigate away on a successful save, so there's no response ETag to rotate in.
const etagRef = useRef<string | null>(null);
useEffect(() => {
activeRef.current = true;
Promise.all([getPlayout(playoutId), getPlayoutTemplates(playoutId), getTemplates(), getDecoTemplates()])
.then(([playout, playoutTemplates, allTemplates, allDecoTemplates]) => {
Promise.all([getPlayout(playoutId), getPlayoutTemplatesWithMeta(playoutId), getTemplates(), getDecoTemplates()])
.then(([playout, templatesMeta, allTemplates, allDecoTemplates]) => {
if (!activeRef.current) {
return;
}
etagRef.current = templatesMeta.etag;
setChannelName(playout.channelName);
setTemplates(allTemplates);
setDecoTemplates(allDecoTemplates);
const drafts = playoutTemplates.map(templateToDraft);
const drafts = templatesMeta.data.map(templateToDraft);
setItems(drafts);
setSelectedKey(drafts.length === 1 ? drafts[0].key : null);
})
@@ -708,7 +751,7 @@ export function PlayoutTemplatesEditorScreen({ playoutId }: { playoutId: number
return () => {
activeRef.current = false;
};
}, [playoutId]);
}, [playoutId, reloadKey]);
if (loadError) {
return <LoadErrorState error={loadError} />;
@@ -784,25 +827,44 @@ export function PlayoutTemplatesEditorScreen({ playoutId }: { playoutId: number
}
setSaving(true);
setSaveError(null);
replacePlayoutTemplates(playoutId, {
items: items.map((item) => ({
id: item.id,
templateId: item.templateId,
decoTemplateId: item.decoTemplateId,
...toRequestRecurrence(item)
}))
})
replacePlayoutTemplates(
playoutId,
{
items: items.map((item) => ({
id: item.id,
templateId: item.templateId,
decoTemplateId: item.decoTemplateId,
...toRequestRecurrence(item)
}))
},
etagRef.current
)
.then(() => {
navigateToPath(PLAYOUTS_PATH);
})
.catch((error: unknown) => {
if (activeRef.current) {
if (!activeRef.current) {
return;
}
if (error instanceof ApiError && error.status === 412) {
// Another edit landed since we loaded — force a reload rather than overwriting it (#253).
setConflictOpen(true);
setSaving(false);
} else {
setSaveError(messageFromPlayoutClientError(error, 'Unable to save playout templates'));
setSaving(false);
}
});
};
const reloadAfterConflict = () => {
setConflictOpen(false);
setSaveError(null);
setItems(null);
setSelectedKey(null);
setReloadKey((key) => key + 1);
};
const templateNameOf = (id: number) => templates.find((template) => template.id === id)?.name ?? '(none)';
return (
@@ -916,6 +978,17 @@ export function PlayoutTemplatesEditorScreen({ playoutId }: { playoutId: number
<RecurrenceFields draft={selected} onChange={patchSelected} />
</Card>
)}
<ConfirmDialog
cancelLabel="Keep editing"
confirmLabel="Reload"
message="This playout was changed elsewhere since you opened it. Reload to get the latest — your unsaved changes will be discarded."
onCancel={() => setConflictOpen(false)}
onConfirm={reloadAfterConflict}
open={conflictOpen}
title="Playout changed elsewhere"
tone="danger"
/>
</EditorChrome>
);
}
@@ -47,6 +47,14 @@ function mockApi(options: MockOptions = {}) {
}
}
// Single-record GET (the editor loads it on open for the #253 concurrency ETag) — must be
// matched before the list handler, which would otherwise swallow it with the paged shape.
const rerunById = url.match(/^\/api\/rerun-collections\/(\d+)$/);
if (rerunById && method === 'GET') {
const found = (list as Array<{ id: number }>).find((r) => String(r.id) === rerunById[1]) ?? list[0];
return Promise.resolve(jsonResponse(found));
}
if (url.startsWith('/api/rerun-collections') && method === 'GET') {
return Promise.resolve(jsonResponse({ page: list, totalCount: list.length }));
}
+59 -2
View File
@@ -3,11 +3,13 @@ import { ArrowLeft, Check, Plus, Repeat, Trash2, TriangleAlert } from 'lucide-re
import { Badge, Button, Card, ConfirmDialog, IconButton, Input, Select, Spinner } from '../components';
import type { SelectOption } from '../components';
import {
ApiError,
createRerunCollection,
deleteRerunCollection,
getCollections,
getLibraryBrowseItems,
getMultiCollections,
getRerunCollectionWithMeta,
getRerunCollections,
getSmartCollections,
messageFromRerunCollectionError,
@@ -208,9 +210,42 @@ function RerunCollectionEditor({
const [pickerError, setPickerError] = useState<string | null>(null);
const [saveError, setSaveError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const [conflictOpen, setConflictOpen] = useState(false);
const [reloadKey, setReloadKey] = useState(0);
// Concurrency ETag (issue #253): captured from the single-record GET when editing an existing
// rerun collection, sent as If-Match on save. There's no rotation-on-save because the editor
// always returns to the list after a successful save (see onSaved below).
const etagRef = useRef<string | null>(null);
const { collectionType } = draft;
// Re-fetch the record's ETag (and current data, on a conflict reload) when editing an existing
// rerun collection. Runs once on mount and again after reloadAfterConflict bumps reloadKey.
useEffect(() => {
if (!initial) {
return;
}
let active = true;
getRerunCollectionWithMeta(initial.id)
.then((meta) => {
if (active) {
etagRef.current = meta.etag;
setDraft(draftFromRerun(meta.data));
}
})
.catch((error: unknown) => {
if (active) {
setSaveError(messageFromRerunCollectionError(error, 'Unable to load rerun collection'));
}
});
return () => {
active = false;
};
}, [initial, reloadKey]);
// Load the picker list for the active type. Resets only in the async callbacks (never
// synchronously in the effect body) per spa-conventions §3.
useEffect(() => {
@@ -275,19 +310,30 @@ function RerunCollectionEditor({
};
if (initial) {
await updateRerunCollection(initial.id, body);
await updateRerunCollection(initial.id, body, etagRef.current);
} else {
await createRerunCollection(body);
}
onSaved();
} catch (error) {
setSaveError(messageFromRerunCollectionError(error, 'Unable to save rerun collection'));
if (error instanceof ApiError && error.status === 412) {
// Another edit landed since we loaded — force a reload rather than overwriting it (#253).
setConflictOpen(true);
} else {
setSaveError(messageFromRerunCollectionError(error, 'Unable to save rerun collection'));
}
} finally {
setSaving(false);
}
};
const reloadAfterConflict = () => {
setConflictOpen(false);
setSaveError(null);
setReloadKey((key) => key + 1);
};
// Ensure the currently-selected item is always an option even if it isn't in the fetched
// page (e.g. a large library where browse returned a different slice).
const selectedInList = draft.selectedId != null && pickerItems.some((item) => item.id === draft.selectedId);
@@ -378,6 +424,17 @@ function RerunCollectionEditor({
/>
</div>
</Card>
<ConfirmDialog
cancelLabel="Keep editing"
confirmLabel="Reload"
message="This was changed elsewhere since you opened it. Reload to get the latest — your unsaved changes will be discarded."
onCancel={() => setConflictOpen(false)}
onConfirm={reloadAfterConflict}
open={conflictOpen}
title="Rerun collection changed elsewhere"
tone="danger"
/>
</div>
);
}