Files
ersatztv/ErsatzTV.Application/ProgramSchedules/Commands/UpdateProgramScheduleHandler.cs
T
timothyandClaude Opus 4.8 d80bf886b2
Build ErsatzTV Image / Docs update reminder (pull_request) Successful in 5s
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 8m6s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 9m49s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
fix(api): #269 force-write non-If-Match root writers past a concurrent Version bump
Activating #253's `Version` as an `IsConcurrencyToken` made EF guard every
UPDATE *and DELETE* of a versioned root with `WHERE Version=@orig`, so any
writer outside the If-Match contract that saves via plain `SaveChangesAsync`
throws an unhandled `DbUpdateConcurrencyException`->500 when a replace-all
editor bumps the row in its narrow load->save window (ordinary two-tab UI).

A completeness sweep (grep every `Version` bumper + every root delete, not
just the handlers PR3's close note named) found 17 exposed writers, all now
routed through `ConcurrencyExtensions.SaveChangesForcingVersion` (Phase-1
force-write: adopt the stored token and retry; rethrow only on genuine
row-deletion):
  - 9 versioned-root delete handlers (a delete has no ETag to rotate -> force
    only, no bump)
  - UpdateProgramScheduleHandler (bumps then saved plainly - the ProgramSchedule
    case PR3 only suspected; its post-commit query/enqueue also moved to
    CancellationToken.None per section 7b)
  - 7 item add/remove bumpers PR2 left on plain save:
    Add/DeleteProgramScheduleItem + Add{Items,Movie,Show,Season,Episode}ToPlaylist

Force-write (not 412) is correct: these endpoints take no If-Match, so an
unconditional delete/edit should win. No API contract change (no new response
codes) -> no OpenAPI regen.

Still deferred to #197 (cross-editor ETag rotation only, not a 500): the
non-bumping config siblings + the scanner-shared Add*ToCollection family.

Tests: RootWriterForceVersionTests races a bump *through the handler* via a
pre-tracked context (non-vacuous - reverting a handler to plain save fails the
test, verified) for the Option-delete / Either-delete / bump+update shapes,
plus the genuine-conflict rethrow branch and an explicit negative control
proving the plain-save path throws. Full ErsatzTV.Tests green (1482).

Also strips a pre-existing UTF-8 BOM from the touched handlers to satisfy the
.editorconfig `charset=utf-8` rule the pre-commit format hook enforces.

Docs: api-conventions section 7a (fan-out completeness) + decisions.md entry.

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

116 lines
5.4 KiB
C#

using System.Threading.Channels;
using ErsatzTV.Application.Playouts;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using ErsatzTV.Core.Scheduling;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Infrastructure.Extensions;
using Microsoft.EntityFrameworkCore;
namespace ErsatzTV.Application.ProgramSchedules;
public class UpdateProgramScheduleHandler(
IDbContextFactory<TvContext> dbContextFactory,
ChannelWriter<IBackgroundServiceRequest> channel)
:
IRequestHandler<UpdateProgramSchedule, Either<BaseError, UpdateProgramScheduleResult>>
{
public async Task<Either<BaseError, UpdateProgramScheduleResult>> Handle(
UpdateProgramSchedule request,
CancellationToken cancellationToken)
{
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
Option<ProgramSchedule> maybeProgramSchedule =
await ProgramScheduleMustExist(dbContext, request, cancellationToken);
return await maybeProgramSchedule.Match(
Some: async programSchedule =>
{
Validation<BaseError, ProgramSchedule> validation = await Validate(dbContext, request, programSchedule, cancellationToken);
return await validation.Apply(ps => ApplyUpdateRequest(dbContext, ps, request, cancellationToken));
},
None: () => Task.FromResult<Either<BaseError, UpdateProgramScheduleResult>>(
new NotFoundError("Schedule does not exist")));
}
private async Task<UpdateProgramScheduleResult> ApplyUpdateRequest(
TvContext dbContext,
ProgramSchedule programSchedule,
UpdateProgramSchedule request,
CancellationToken cancellationToken)
{
// we need to refresh playouts if the playback order or keep multi-episodes has been modified
bool needToRefreshPlayout =
programSchedule.KeepMultiPartEpisodesTogether != request.KeepMultiPartEpisodesTogether ||
programSchedule.TreatCollectionsAsShows != request.TreatCollectionsAsShows ||
programSchedule.ShuffleScheduleItems != request.ShuffleScheduleItems ||
programSchedule.RandomStartPoint != request.RandomStartPoint ||
programSchedule.FixedStartTimeBehavior != request.FixedStartTimeBehavior;
programSchedule.Name = request.Name;
programSchedule.KeepMultiPartEpisodesTogether = request.KeepMultiPartEpisodesTogether;
programSchedule.TreatCollectionsAsShows = programSchedule.KeepMultiPartEpisodesTogether &&
request.TreatCollectionsAsShows;
programSchedule.ShuffleScheduleItems = request.ShuffleScheduleItems;
programSchedule.RandomStartPoint = request.RandomStartPoint;
programSchedule.FixedStartTimeBehavior = request.FixedStartTimeBehavior;
// bump the optimistic-concurrency token so this config edit rotates other clients' ETags (#253).
// Force-write past a concurrent Version bump (e.g. a parallel schedule-items replace) instead of
// surfacing the IsConcurrencyToken guard as an unhandled DbUpdateConcurrencyException → 500 (#269).
programSchedule.Version++;
await dbContext.SaveChangesForcingVersion(cancellationToken);
if (needToRefreshPlayout)
{
// post-commit side effect: run the affected-playout query + enqueue on CancellationToken.None
// so a late request cancellation can't abort the rebuild after the edit already committed (#254)
List<int> playoutIds = await dbContext.Playouts
.Filter(p => p.ProgramScheduleId == programSchedule.Id)
.Map(p => p.Id)
.ToListAsync(CancellationToken.None);
foreach (int playoutId in playoutIds)
{
await channel.WriteAsync(new BuildPlayout(playoutId, PlayoutBuildMode.Refresh), CancellationToken.None);
}
}
return new UpdateProgramScheduleResult(programSchedule.Id);
}
private static async Task<Validation<BaseError, ProgramSchedule>> Validate(
TvContext dbContext,
UpdateProgramSchedule request,
ProgramSchedule programSchedule,
CancellationToken cancellationToken) =>
(await ValidateName(dbContext, request, cancellationToken)).Map(_ => programSchedule);
private static Task<Option<ProgramSchedule>> ProgramScheduleMustExist(
TvContext dbContext,
UpdateProgramSchedule request,
CancellationToken cancellationToken) =>
dbContext.ProgramSchedules
.SelectOneAsync(ps => ps.Id, ps => ps.Id == request.ProgramScheduleId, cancellationToken)
.Map(identity);
private static async Task<Validation<BaseError, string>> ValidateName(
TvContext dbContext,
UpdateProgramSchedule request,
CancellationToken cancellationToken)
{
Validation<BaseError, string> result1 = request.NotEmpty(c => c.Name)
.Bind(_ => request.NotLongerThan(50)(c => c.Name));
bool duplicateName = await dbContext.ProgramSchedules
.AnyAsync(c => c.Id != request.ProgramScheduleId && c.Name == request.Name, cancellationToken);
Validation<BaseError, Unit> result2 = duplicateName
? Fail<BaseError, Unit>("Schedule name must be unique")
: Success<BaseError, Unit>(Unit.Default);
return (result1, result2).Apply((_, _) => request.Name);
}
}