Files
ersatztv/ErsatzTV.Application/Playouts/Commands/ReplacePlayoutAlternateScheduleItemsHandler.cs
T
timothyandClaude Opus 4.8 8090e10408 fix(api): #265 — If-Match evaluates per RFC 7232 (valid-but-non-matching → 412, not 400)
The shared optimistic-concurrency parser (ConcurrencyHeaders.ParseIfMatch) classified any
non-canonical/weak/list If-Match value as Malformed → 400. Per RFC 7232 §3.1 a syntactically
-valid entity-tag that simply doesn't strong-match must be 412; 400 is only for a genuine
grammar violation.

- Rewrite ParseIfMatch as a real RFC 7232 entity-tag/list parser: walks the comma-separated
  1#entity-tag list, validates each [W/]DQUOTE *etagc DQUOTE member, and collects the strong
  members whose opaque text is our canonical decimal. Weak / empty / non-canonical /
  out-of-range tags are valid but contribute no version (→ empty set → 412); genuine grammar
  violations (unquoted, SP-in-tag, unterminated, garbage) → 400.
- Reshape IfMatchCondition.ExpectedVersion : Option<int> → ExpectedVersions : Option<Seq<int>>
  and VersionedAggregateExtensions.CheckVersion → set membership (any strong match proceeds;
  empty set always 412). Threads through 10 replace/update commands + handlers + request
  mappers + 9 controllers.
- No wire-contract change (400 + 412 already declared on every PUT; the field is header-derived
  and internal — no DTO/route/response-type/OpenAPI change).
- Tests: ConcurrencyHeadersTests rewritten for the new classification (lists, weak, empty,
  non-canonical → Version/empty-set; grammar violations → Malformed) + new
  VersionedAggregateExtensionsTests for CheckVersion membership/empty-set/force-write.
- Docs: api-conventions.md §7a rewritten; decisions.md entry appended.

Refs #253 #197
fixes #265

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-12 23:09:36 +02:00

207 lines
9.7 KiB
C#

using System.Threading.Channels;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Scheduling;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Infrastructure.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace ErsatzTV.Application.Playouts;
public class ReplacePlayoutAlternateScheduleItemsHandler(
IDbContextFactory<TvContext> dbContextFactory,
ChannelWriter<IBackgroundServiceRequest> channel,
ILogger<ReplacePlayoutAlternateScheduleItemsHandler> logger)
:
IRequestHandler<ReplacePlayoutAlternateScheduleItems, Either<BaseError, Unit>>
{
public async Task<Either<BaseError, Unit>> Handle(
ReplacePlayoutAlternateScheduleItems request,
CancellationToken cancellationToken)
{
// The handler reads the highest-index item as the default schedule (Max() below), so an empty
// list is invalid — reject it here rather than letting Max() throw. The controller pre-guards
// too, but a direct handler caller (MCP, test, reuse) must get a clean 422, not a raw crash (#254).
if (request.Items.Count == 0)
{
return BaseError.New("Playout alternate schedule items must not be empty");
}
try
{
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
Option<Playout> maybePlayout = await dbContext.Playouts
.Include(p => p.ProgramSchedule)
.Include(p => p.ProgramScheduleAlternates)
.ThenInclude(p => p.ProgramSchedule)
.SelectOneAsync(p => p.Id, p => p.Id == request.PlayoutId, cancellationToken);
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.ExpectedVersions);
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>();
Option<PlayoutItem> maybeLastPlayoutItem = await dbContext.PlayoutItems
.Filter(pi => pi.PlayoutId == request.PlayoutId)
.OrderByDescending(pi => pi.Start)
.FirstOrDefaultAsync(cancellationToken)
.Map(Optional);
foreach (PlayoutItem lastPlayoutItem in maybeLastPlayoutItem)
{
DateTimeOffset start = DateTimeOffset.Now;
daysToCheck = Enumerable.Range(0, (lastPlayoutItem.StartOffset - start).Days + 1)
.Select(d => start.AddDays(d))
.ToList();
foreach (DateTimeOffset dayToCheck in daysToCheck)
{
ProgramSchedule schedule = AlternateScheduleSelector
.GetScheduleForDate(playout.ProgramScheduleAlternates, dayToCheck)
.Match(s => s.ProgramSchedule, playout.ProgramSchedule);
existingScheduleMap.Add(dayToCheck, schedule);
}
}
// exclude highest index
int maxIndex = request.Items.Map(x => x.Index).Max();
ReplacePlayoutAlternateSchedule highest = request.Items.First(x => x.Index == maxIndex);
ProgramScheduleAlternate[] existing = playout.ProgramScheduleAlternates.ToArray();
var incoming = request.Items.Except([highest]).ToList();
var toAdd = incoming.Filter(x => existing.All(e => e.Id != x.Id)).ToList();
var toRemove = existing.Filter(e => incoming.All(m => m.Id != e.Id)).ToList();
var toUpdate = incoming.Except(toAdd).ToList();
playout.ProgramScheduleAlternates.RemoveAll(toRemove.Contains);
foreach (ReplacePlayoutAlternateSchedule add in toAdd)
{
playout.ProgramScheduleAlternates.Add(
new ProgramScheduleAlternate
{
PlayoutId = playout.Id,
Index = add.Index,
ProgramScheduleId = add.ProgramScheduleId,
DaysOfWeek = add.DaysOfWeek,
DaysOfMonth = add.DaysOfMonth,
MonthsOfYear = add.MonthsOfYear,
LimitToDateRange = add.LimitToDateRange,
StartMonth = add.StartMonth,
StartDay = add.StartDay,
StartYear = add.StartYear,
EndMonth = add.EndMonth,
EndDay = add.EndDay,
EndYear = add.EndYear
});
}
foreach (ReplacePlayoutAlternateSchedule update in toUpdate)
{
foreach (ProgramScheduleAlternate ex in existing.Filter(x => x.Id == update.Id))
{
ex.Index = update.Index;
ex.ProgramScheduleId = update.ProgramScheduleId;
ex.DaysOfWeek = update.DaysOfWeek;
ex.DaysOfMonth = update.DaysOfMonth;
ex.MonthsOfYear = update.MonthsOfYear;
ex.LimitToDateRange = update.LimitToDateRange;
ex.StartMonth = update.StartMonth;
ex.StartDay = update.StartDay;
ex.StartYear = update.StartYear;
ex.EndMonth = update.EndMonth;
ex.EndDay = update.EndDay;
ex.EndYear = update.EndYear;
}
}
// save highest index directly to playout
bool hasDefaultScheduleChange = playout.ProgramScheduleId != highest.ProgramScheduleId;
if (hasDefaultScheduleChange)
{
playout.ProgramScheduleId = highest.ProgramScheduleId;
}
// 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)
{
await dbContext.Entry(playout).Reference(p => p.ProgramSchedule).LoadAsync(cancellationToken);
}
// load newly-added schedules
foreach (ProgramScheduleAlternate alternate in playout.ProgramScheduleAlternates
.Where(alternate => alternate.ProgramSchedule is null))
{
await dbContext.Entry(alternate).Reference(a => a.ProgramSchedule).LoadAsync(cancellationToken);
}
foreach (PlayoutItem _ in maybeLastPlayoutItem)
{
foreach (DateTimeOffset dayToCheck in daysToCheck)
{
ProgramSchedule schedule = AlternateScheduleSelector
.GetScheduleForDate(playout.ProgramScheduleAlternates, dayToCheck)
.Match(s => s.ProgramSchedule, playout.ProgramSchedule);
if (existingScheduleMap.TryGetValue(dayToCheck, out ProgramSchedule existingValue) &&
existingValue.Id != schedule.Id)
{
logger.LogInformation(
"Alternate schedule change detected for day {Day}, schedule {One} => {Two}; will refresh playout",
dayToCheck,
existingValue.Name,
schedule.Name);
// post-commit enqueue runs on CancellationToken.None: the schedule change is
// already committed, so a late cancellation must not drop the rebuild (#254)
await channel.WriteAsync(
new BuildPlayout(request.PlayoutId, PlayoutBuildMode.Refresh),
CancellationToken.None);
break;
}
}
}
}
return Unit.Default;
}
catch (Exception ex)
{
logger.LogError(ex, "Error saving alternate schedule items");
return BaseError.New(ex.Message);
}
}
}