Build ErsatzTV Image / Docs update reminder (pull_request) Successful in 5s
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 8m11s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 9m51s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
Fans the frozen Block recipe (api-conventions §7a) across the five Diff/Scalar replace-all endpoints, completing the #253 PR2→PR4 arc's implementable core: - #6 Collection custom-order, #7 Playout alternate-schedules, #8 Playout templates (shared Playout.Version), #9 MultiCollection, #10 RerunCollection — each: pre-check 412 as a standalone Either after validation (H2, subtype survives the Join flatten), unconditional Version++ (M1), guarded save, controller If-Match/ETag/400/412, SPA editor ETag round-trip + 412 conflict dialog. - H1: the two Playout handlers' catch(Exception)→422 restructured so the guard's PreconditionFailedError returns before the catch (412, not 422). - M2: RerunCollection/Collection refresh runs unconditionally on save; MultiCollection keeps its name-only→no-rebuild optimization by bumping on the first (name) save. - H3: UpdateDefaultDecoHandler bulk-bumps Playout.Version via .SetProperty. - Shared ConcurrencyHeaders.MalformedIfMatchProblem() for the 400 guard. - Deferred (→ #269): same-root non-bulk sibling config writers' ETag rotation. Tests: per-handler pre-check/bump concurrency tests (Playout ×2 incl. non-vacuous racing-save backstop, Rerun, Multi incl. name-only-no-rebuild M2, Collection); controller tests get a DefaultHttpContext for the header read/write. Docs: api-conventions §7a fan-out status, spa-conventions §4a list-editor note, decisions. Refs #253 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
207 lines
9.7 KiB
C#
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.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>();
|
|
|
|
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);
|
|
}
|
|
}
|
|
}
|