Two holes the review round found in the previous fix, both of the same shape: a guard that names its own fields instead of deriving them. The deco validators short-circuited the entire Validators.IdsMustExist call when the DecoMode does not consume the ids, which took the 512-item raw-count cap with it -- an arbitrarily large array under Inherit/Disable parsed and materialized with nothing bounding it. Only the EXISTENCE half is the apply path's business, so the mode predicate is now a required argument of the shared validator and gates that half alone; the cap runs under every mode. The channel recovery path rechecked GraphicsElementIdsMustExist alone, so a watermark deleted between validation and SaveChangesAsync still surfaced as the unhandled 500 the fix exists to remove -- WatermarkId, FFmpegProfileId, FallbackFillerId and MirrorSourceChannelId are all written by the same save and lose the same race. Both handlers now re-ask the whole of Validate on DbUpdateException, so a validator added later is covered without editing the recovery path. The API-site outside-folder discriminator test seeded an Image row, so the Kind conjunct rejected it whatever the path comparison did: a composite revert to Path.GetFileName(path) == filename && kind == Text passed every API test. It now carries the seeded Kind, mirroring the seeder-site twin, so only the path half can reject it. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015QqCpYFsKgnAnx6jVwrKiV
428 lines
19 KiB
C#
428 lines
19 KiB
C#
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<TvContext> dbContextFactory,
|
|
ChannelWriter<IBackgroundServiceRequest> channel)
|
|
: IRequestHandler<UpdateDeco, Either<BaseError, Unit>>
|
|
{
|
|
public async Task<Either<BaseError, Unit>> Handle(UpdateDeco request, CancellationToken cancellationToken)
|
|
{
|
|
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
|
|
Validation<BaseError, Deco> validation = await Validate(dbContext, request, cancellationToken);
|
|
return await validation.Match(
|
|
Succ: deco => ApplyUpdateRequestTranslatingLostRace(dbContext, deco, request, cancellationToken),
|
|
Fail: errors => Task.FromResult(Left<BaseError, Unit>(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<Either<BaseError, Unit>> 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<BaseError, Deco> recheck = await Validate(recheckContext, request, cancellationToken);
|
|
|
|
Option<BaseError> maybeError = recheck.Match(
|
|
Succ: _ => Option<BaseError>.None,
|
|
Fail: errors => Some(errors.Join()));
|
|
|
|
foreach (BaseError error in maybeError)
|
|
{
|
|
return Left<BaseError, Unit>(error);
|
|
}
|
|
|
|
throw;
|
|
}
|
|
}
|
|
|
|
private async Task<Unit> 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<int> toAdd =
|
|
request.WatermarkIds.Where(id => existing.DecoWatermarks.All(wm => wm.WatermarkId != id));
|
|
IEnumerable<DecoWatermark> 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<int> toAdd =
|
|
request.GraphicsElementIds.Where(id => existing.DecoGraphicsElements.All(ge => ge.GraphicsElementId != id));
|
|
IEnumerable<DecoGraphicsElement> 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<DecoBreakContent> 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<int> directPlayoutIds = await dbContext.Playouts
|
|
.Where(p => p.DecoId == request.DecoId)
|
|
.Select(p => p.Id)
|
|
.ToListAsync(CancellationToken.None);
|
|
|
|
List<int> decoTemplateIds = await dbContext.DecoTemplateItems
|
|
.Where(i => i.DecoId == request.DecoId)
|
|
.Select(i => i.DecoTemplateId)
|
|
.Distinct()
|
|
.ToListAsync(CancellationToken.None);
|
|
|
|
List<int> 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<Validation<BaseError, Deco>> 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<Validation<BaseError, Unit>> 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<Validation<BaseError, Unit>> 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<Validation<BaseError, Deco>> 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<BaseError>("Deco does not exist"));
|
|
|
|
private static async Task<Validation<BaseError, string>> 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<BaseError, string>(request.Name);
|
|
}
|
|
|
|
private static Validation<BaseError, Unit> 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;
|
|
}
|
|
}
|