using System.Threading.Channels; using ErsatzTV.Application.Playouts; using ErsatzTV.Core; using ErsatzTV.Core.Domain; using ErsatzTV.Core.Domain.Scheduling; using ErsatzTV.Core.Scheduling; using ErsatzTV.Infrastructure.Data; using ErsatzTV.Infrastructure.Extensions; using Microsoft.EntityFrameworkCore; namespace ErsatzTV.Application.Scheduling; public class UpdateDecoHandler( IDbContextFactory dbContextFactory, ChannelWriter channel) : IRequestHandler> { public async Task> Handle(UpdateDeco request, CancellationToken cancellationToken) { await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken); Validation validation = await Validate(dbContext, request, cancellationToken); return await validation.Match( Succ: deco => ApplyUpdateRequestTranslatingLostRace(dbContext, deco, request, cancellationToken), Fail: errors => Task.FromResult(Left(errors.Join()))); } // Mirrors UpdateChannelHandler.ApplyUpdateRequestTranslatingLostRace (#568): validation and the // write are two statements, so a concurrent delete of a validated watermark or graphics element // -- RefreshGraphicsElements deletes elements whose template file is gone -- lands the join // insert on the FK violation the validators exist to prevent, as an unhandled 500. A transaction // does not close that window either (neither provider locks the rows the validator merely READ), // so ask the existence questions again on the failure path and return the same 422; a // DbUpdateException from any other cause keeps its own exception. // // The whole of Validate is re-asked rather than a named pair of fields, for the same reason as // the channel twin: a recovery path that enumerates its own fields omits the next one the DTO // gains, while re-running the validator set covers a check added to Validate by construction. private async Task> ApplyUpdateRequestTranslatingLostRace( TvContext dbContext, Deco existing, UpdateDeco request, CancellationToken cancellationToken) { try { return await ApplyUpdateRequest(dbContext, existing, request, cancellationToken); } catch (DbUpdateException) { // a fresh context: the failed save left the original one tracking the changes that // could not be written, so the same query there could be answered out of those. await using TvContext recheckContext = await dbContextFactory.CreateDbContextAsync(cancellationToken); Validation recheck = await Validate(recheckContext, request, cancellationToken); Option maybeError = recheck.Match( Succ: _ => Option.None, Fail: errors => Some(errors.Join())); foreach (BaseError error in maybeError) { return Left(error); } throw; } } private async Task ApplyUpdateRequest( TvContext dbContext, Deco existing, UpdateDeco request, CancellationToken cancellationToken) { existing.Name = request.Name; // watermark bool hasWatermark = ConsumesWatermarkIds(request); existing.WatermarkMode = request.WatermarkMode; existing.UseWatermarkDuringFiller = hasWatermark && request.UseWatermarkDuringFiller; if (hasWatermark) { // this is different than schedule item/playout item because we have to merge watermark ids IEnumerable toAdd = request.WatermarkIds.Where(id => existing.DecoWatermarks.All(wm => wm.WatermarkId != id)); IEnumerable toRemove = existing.DecoWatermarks.Where(wm => !request.WatermarkIds.Contains(wm.WatermarkId)); existing.DecoWatermarks.RemoveAll(toRemove.Contains); foreach (int watermarkId in toAdd) { existing.DecoWatermarks.Add( new DecoWatermark { DecoId = existing.Id, WatermarkId = watermarkId }); } } else { existing.DecoWatermarks.Clear(); } // graphics elements bool hasGraphicsElements = ConsumesGraphicsElementIds(request); existing.GraphicsElementsMode = request.GraphicsElementsMode; existing.UseGraphicsElementsDuringFiller = hasGraphicsElements && request.UseGraphicsElementsDuringFiller; if (hasGraphicsElements) { // this is different than schedule item/playout item because we have to merge graphics element ids IEnumerable toAdd = request.GraphicsElementIds.Where(id => existing.DecoGraphicsElements.All(ge => ge.GraphicsElementId != id)); IEnumerable toRemove = existing.DecoGraphicsElements.Where(ge => !request.GraphicsElementIds.Contains(ge.GraphicsElementId)); existing.DecoGraphicsElements.RemoveAll(toRemove.Contains); foreach (int graphicsElementId in toAdd) { existing.DecoGraphicsElements.Add( new DecoGraphicsElement { DecoId = existing.Id, GraphicsElementId = graphicsElementId }); } } else { existing.DecoGraphicsElements.Clear(); } // break content existing.BreakContentMode = request.BreakContentMode; var breakContentToAdd = request.BreakContent.Where(bc => existing.BreakContent.All(b => b.Id != bc.Id)).ToList(); IEnumerable breakContentToRemove = existing.BreakContent.Where(bc => !request.BreakContent.Map(b => b.Id).Contains(bc.Id)); var breakContentToUpdate = request.BreakContent.Except(breakContentToAdd).ToList(); existing.BreakContent.RemoveAll(breakContentToRemove.Contains); foreach (var toUpdate in breakContentToUpdate) { foreach (var ex in Optional(existing.BreakContent.FirstOrDefault(b => b.Id == toUpdate.Id))) { ex.CollectionType = toUpdate.CollectionType; ex.CollectionId = toUpdate.CollectionId; ex.MediaItemId = toUpdate.MediaItemId; ex.MultiCollectionId = toUpdate.MultiCollectionId; ex.SmartCollectionId = toUpdate.SmartCollectionId; ex.PlaylistId = toUpdate.PlaylistId; ex.Placement = toUpdate.Placement; } } foreach (var add in breakContentToAdd) { existing.BreakContent.Add(new DecoBreakContent { DecoId = existing.Id, CollectionType = add.CollectionType, CollectionId = add.CollectionId, MediaItemId = add.MediaItemId, MultiCollectionId = add.MultiCollectionId, SmartCollectionId = add.SmartCollectionId, PlaylistId = add.PlaylistId, Placement = add.Placement }); } // default filler existing.DefaultFillerMode = request.DefaultFillerMode; existing.DefaultFillerCollectionType = request.DefaultFillerCollectionType; existing.DefaultFillerCollectionId = null; existing.DefaultFillerMediaItemId = null; existing.DefaultFillerMultiCollectionId = null; existing.DefaultFillerSmartCollectionId = null; if (request.DefaultFillerMode is DecoMode.Override) { switch (request.DefaultFillerCollectionType) { case CollectionType.Collection: existing.DefaultFillerCollectionId = request.DefaultFillerCollectionId; break; case CollectionType.MultiCollection: existing.DefaultFillerMultiCollectionId = request.DefaultFillerMultiCollectionId; break; case CollectionType.SmartCollection: existing.DefaultFillerSmartCollectionId = request.DefaultFillerSmartCollectionId; break; default: existing.DefaultFillerMediaItemId = request.DefaultFillerMediaItemId; break; } } existing.DefaultFillerTrimToFit = request.DefaultFillerTrimToFit; // dead air fallback existing.DeadAirFallbackMode = request.DeadAirFallbackMode; existing.DeadAirFallbackCollectionType = request.DeadAirFallbackCollectionType; existing.DeadAirFallbackCollectionId = null; existing.DeadAirFallbackMediaItemId = null; existing.DeadAirFallbackMultiCollectionId = null; existing.DeadAirFallbackSmartCollectionId = null; if (request.DeadAirFallbackMode is DecoMode.Override) { switch (request.DeadAirFallbackCollectionType) { case CollectionType.Collection: existing.DeadAirFallbackCollectionId = request.DeadAirFallbackCollectionId; break; case CollectionType.MultiCollection: existing.DeadAirFallbackMultiCollectionId = request.DeadAirFallbackMultiCollectionId; break; case CollectionType.SmartCollection: existing.DeadAirFallbackSmartCollectionId = request.DeadAirFallbackSmartCollectionId; break; default: existing.DeadAirFallbackMediaItemId = request.DeadAirFallbackMediaItemId; break; } } await dbContext.SaveChangesAsync(cancellationToken); // Deco content (break/default filler/etc.) is only (re)applied during a Reset build, and BlockKey // change-detection has no deco dimension, so editing a deco left already-built filler/break content // stale until a manual Reset (#251). Enqueue a Reset for every playout that references this deco — // directly (Playout.DecoId) or through a deco template that includes it. This whole post-commit // invalidation runs with CancellationToken.None (audit #22 policy): once the edit is committed, a // late request cancellation must not be able to abort either the affected-playout queries OR the // enqueue and leave content stale — the entire side effect has to complete. List directPlayoutIds = await dbContext.Playouts .Where(p => p.DecoId == request.DecoId) .Select(p => p.Id) .ToListAsync(CancellationToken.None); List decoTemplateIds = await dbContext.DecoTemplateItems .Where(i => i.DecoId == request.DecoId) .Select(i => i.DecoTemplateId) .Distinct() .ToListAsync(CancellationToken.None); List templatePlayoutIds = await dbContext.PlayoutTemplates .Where(pt => pt.DecoTemplateId.HasValue && decoTemplateIds.Contains(pt.DecoTemplateId.Value)) .Select(pt => pt.PlayoutId) .ToListAsync(CancellationToken.None); foreach (int playoutId in directPlayoutIds.Concat(templatePlayoutIds).Distinct()) { await channel.WriteAsync(new BuildPlayout(playoutId, PlayoutBuildMode.Reset), CancellationToken.None); } return Unit.Default; } private static async Task> Validate( TvContext dbContext, UpdateDeco request, CancellationToken cancellationToken) => (await DecoMustExist(dbContext, request, cancellationToken), await ValidateDecoName(dbContext, request), ValidateBreakContent(request), await WatermarkIdsMustExist(dbContext, request, cancellationToken), await GraphicsElementIdsMustExist(dbContext, request, cancellationToken)) .Apply((deco, _, _, _, _) => deco); // The mode decides whether an id list is data or dead weight: ApplyUpdateRequest reconciles the // join table only under Override/Merge and Clear()s it otherwise, ignoring the ids entirely. The // validators below read these same two predicates rather than restating the mode test, so a // validator can never reject an id the apply path was going to discard (#568). The SPA sends both // id lists regardless of the mode selector, so that shape arrives from the real editor: a draft // holding an element that has since been deleted must still be able to save the deco back to // Inherit. The predicate is handed to Validators.IdsMustExist rather than short-circuiting the // call, because only the EXISTENCE half belongs to the apply path: a discarded list was still // parsed and materialized out of the request body, so the raw-count cap has to apply under // every mode. private static bool ConsumesWatermarkIds(UpdateDeco request) => request.WatermarkMode is (DecoMode.Override or DecoMode.Merge); private static bool ConsumesGraphicsElementIds(UpdateDeco request) => request.GraphicsElementsMode is (DecoMode.Override or DecoMode.Merge); // Mirrors UpdateChannelHandler.GraphicsElementIdsMustExist (#568): the reconcile in // ApplyUpdateRequest blindly Adds a DecoWatermark/DecoGraphicsElement for every incoming id, and // an id with no matching row hits the FK constraint at SaveChangesAsync and surfaces as an // unhandled 500 (there is no global exception filter). These are top-level fields on // ReplaceDecoRequest, the same position as graphicsElementIds on UpdateChannelRequest -- not the // "deep FK ids nested inside item-list request bodies" carve-out in api-conventions.md. Both go // through Validators.IdsMustExist, the one place the count cap, the request field named in the // message and the cap on echoed ids are written. private static Task> WatermarkIdsMustExist( TvContext dbContext, UpdateDeco request, CancellationToken cancellationToken) => Validators.IdsMustExist( request, r => r.WatermarkIds, "Watermark", idsAreConsumed: ConsumesWatermarkIds(request), (ids, token) => dbContext.ChannelWatermarks .Where(w => ids.Contains(w.Id)) .Select(w => w.Id) .ToListAsync(token), cancellationToken); private static Task> GraphicsElementIdsMustExist( TvContext dbContext, UpdateDeco request, CancellationToken cancellationToken) => Validators.IdsMustExist( request, r => r.GraphicsElementIds, "Graphics element", idsAreConsumed: ConsumesGraphicsElementIds(request), (ids, token) => dbContext.GraphicsElements .Where(e => ids.Contains(e.Id)) .Select(e => e.Id) .ToListAsync(token), cancellationToken); private static Task> DecoMustExist( TvContext dbContext, UpdateDeco request, CancellationToken cancellationToken) => dbContext.Decos .Include(d => d.BreakContent) .Include(d => d.DecoWatermarks) .Include(d => d.DecoGraphicsElements) .SelectOneAsync(d => d.Id, d => d.Id == request.DecoId, cancellationToken) .Map(o => o.ToValidation("Deco does not exist")); private static async Task> ValidateDecoName( TvContext dbContext, UpdateDeco request) { if (string.IsNullOrWhiteSpace(request.Name) || request.Name.Length > 50) { return BaseError.New($"Deco name \"{request.Name}\" is invalid"); } bool duplicateName = await dbContext.Decos .AnyAsync(d => d.Id != request.DecoId && d.DecoGroupId == request.DecoGroupId && d.Name == request.Name); return duplicateName ? BaseError.New($"A deco named \"{request.Name}\" already exists in that deco group") : Success(request.Name); } private static Validation ValidateBreakContent(UpdateDeco request) { int startCount = request.BreakContent.Count(bc => bc.Placement is DecoBreakPlacement.BlockStart); if (startCount > 1) { return BaseError.New("Deco may only contain one [Block Start] break content"); } int betweenCount = request.BreakContent.Count(bc => bc.Placement is DecoBreakPlacement.BetweenBlockItems); if (betweenCount > 1) { return BaseError.New("Deco may only contain one [Between Block Items] break content"); } int chapterCount = request.BreakContent.Count(bc => bc.Placement is DecoBreakPlacement.ChapterMarkers); if (chapterCount > 1) { return BaseError.New("Deco may only contain one [At Chapter Markers] break content"); } int finishCount = request.BreakContent.Count(bc => bc.Placement is DecoBreakPlacement.BlockFinish); if (finishCount > 1) { return BaseError.New("Deco may only contain one [Block Finish] break content"); } foreach (var breakContent in request.BreakContent) { switch (breakContent.CollectionType) { case CollectionType.Collection: if (breakContent.CollectionId is null) { return BaseError.New("Break content must have valid collection"); } break; case CollectionType.MultiCollection: if (breakContent.MultiCollectionId is null) { return BaseError.New("Break content must have valid multi collection"); } break; case CollectionType.SmartCollection: if (breakContent.SmartCollectionId is null) { return BaseError.New("Break content must have valid smart collection"); } break; case CollectionType.TelevisionShow: case CollectionType.TelevisionSeason: case CollectionType.Artist: if (breakContent.MediaItemId is null) { return BaseError.New("Break content must have valid media item"); } break; case CollectionType.Playlist: if (breakContent.PlaylistId is null) { return BaseError.New("Break content must have valid playlist"); } break; } } return Unit.Default; } }