Files
ersatztv/ErsatzTV.Application/ProgramSchedules/Commands/ReplaceProgramScheduleItemsHandler.cs
T
timothyandClaude Opus 4.8 51ac11e5aa
Build ErsatzTV Image / Docs update reminder (pull_request) Successful in 4s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 3m55s
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 6m58s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
fix(review): close post-commit cancellation window + guard default-deco enqueue (Codex Medium/Low)
Independent Codex review of the fix diff surfaced two real findings the fork pass missed:

- Medium: the #251 affected-playout QUERIES in ReplaceDecoTemplateItemsHandler and
  UpdateDecoHandler still ran on the request `cancellationToken`, so a cancellation
  landing after SaveChanges committed but before those queries executed would throw
  before the CancellationToken.None enqueue — the edit committed but no playout Reset,
  re-opening the stale-content bug in that window. Run the entire post-commit
  invalidation (queries + enqueue) on CancellationToken.None so the side effect can't
  be half-aborted once the data has changed.
- Low: UpdateDefaultDecoHandler enqueued a Reset for request.PlayoutId even when
  ExecuteUpdateAsync matched 0 rows (nonexistent playout), creating a background build
  request for an id that isn't there. Guard the enqueue on rows-updated > 0 so the
  enqueued set equals the affected set. Added a regression test.

Also corrected the ReplaceProgramScheduleItemsHandler comments: the schedule-item
hierarchy is TPT (table-per-type), not TPH — the SetValues reconcile is safe either way
(same-runtime-type guard; no discriminator to corrupt), Codex confirmed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 15:18:38 +02:00

242 lines
11 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 Microsoft.EntityFrameworkCore;
using static ErsatzTV.Application.ProgramSchedules.Mapper;
namespace ErsatzTV.Application.ProgramSchedules;
public class ReplaceProgramScheduleItemsHandler(
IDbContextFactory<TvContext> dbContextFactory,
ChannelWriter<IBackgroundServiceRequest> channel) : ProgramScheduleItemCommandBase,
IRequestHandler<ReplaceProgramScheduleItems, Either<BaseError, IEnumerable<ProgramScheduleItemViewModel>>>
{
public async Task<Either<BaseError, IEnumerable<ProgramScheduleItemViewModel>>> Handle(
ReplaceProgramScheduleItems request,
CancellationToken cancellationToken)
{
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
Option<ProgramSchedule> maybeProgramSchedule =
await ProgramScheduleMustExist(dbContext, request.ProgramScheduleId, cancellationToken);
return await maybeProgramSchedule.Match(
Some: async programSchedule =>
{
Validation<BaseError, ProgramSchedule> validation = await Validate(dbContext, request, programSchedule);
return await validation.Apply(ps => PersistItems(dbContext, request, ps, cancellationToken));
},
None: () => Task.FromResult<Either<BaseError, IEnumerable<ProgramScheduleItemViewModel>>>(
new NotFoundError("[ProgramScheduleId] does not exist.")));
}
private async Task<IEnumerable<ProgramScheduleItemViewModel>> PersistItems(
TvContext dbContext,
ReplaceProgramScheduleItems request,
ProgramSchedule programSchedule,
CancellationToken cancellationToken)
{
// Positional in-place reconcile (rather than delete-and-reinsert): a schedule item owns the
// persisted fill-group/shuffle enumerator state via PlayoutScheduleItemFillGroupIndex, whose
// ProgramScheduleItemId FK is OnDelete(Cascade). Removing and re-inserting every item — as the
// original handler did on every save, including a no-op PUT-back — cascade-deleted that state for
// all playouts using the schedule (#252). Reusing the existing item row for the same-typed slot
// keeps its id, so the cascade never fires and progression survives. The request DTO carries no
// stable item id, so position is the only key available here; true content-aware stable identity
// is deferred to the shared concurrency/round-trip contract in #253.
var orderedItems = request.Items.OrderBy(i => i.Index).ToList();
List<ProgramScheduleItem> existingItems = programSchedule.Items.OrderBy(i => i.Index).ToList();
// load the watermark/graphics join rows for the existing items so they can be rebuilt in place
await dbContext.Entry(programSchedule)
.Collection(ps => ps.Items)
.Query()
.Include(i => i.ProgramScheduleItemWatermarks)
.Include(i => i.ProgramScheduleItemGraphicsElements)
.LoadAsync(cancellationToken);
int commonCount = Math.Min(existingItems.Count, orderedItems.Count);
for (var i = 0; i < commonCount; i++)
{
ProgramScheduleItem existing = existingItems[i];
ProgramScheduleItem built = BuildItem(programSchedule, i, orderedItems[i]);
if (existing.GetType() == built.GetType())
{
// same TPT subtype: copy all scalar values in place (BuildItem is the single source of
// item construction, so no field is silently dropped) and rebuild the join rows, keeping
// the item's id — and with it the fill-group index that would otherwise cascade away.
built.Id = existing.Id;
dbContext.Entry(existing).CurrentValues.SetValues(built);
RebuildChildren(existing, orderedItems[i]);
}
else
{
// EF can't change a TPT row's type in place; this slot must be replaced (its fill-group
// index resets, which is acceptable — the item fundamentally changed).
dbContext.Remove(existing);
programSchedule.Items.Add(built);
}
}
// remove surplus existing items
for (int i = commonCount; i < existingItems.Count; i++)
{
dbContext.Remove(existingItems[i]);
}
// add surplus incoming items
for (int i = commonCount; i < orderedItems.Count; i++)
{
programSchedule.Items.Add(BuildItem(programSchedule, i, orderedItems[i]));
}
await dbContext.SaveChangesAsync(cancellationToken);
// refresh any playouts that use this schedule
foreach (Playout playout in programSchedule.Playouts)
{
await channel.WriteAsync(new BuildPlayout(playout.Id, PlayoutBuildMode.Refresh), cancellationToken);
}
// reload with the full navigation graph before projecting: BuildItem creates the watermark/graphics
// join rows with only their foreign-key ids set, so the tracked entities have null Watermark /
// GraphicsElement navs that ProjectToViewModel dereferences (would 500 on PUT — see #229).
List<ProgramScheduleItem> persisted = await dbContext.ProgramScheduleItems
.Filter(psi => psi.ProgramScheduleId == programSchedule.Id)
.IncludeScheduleItemDetails()
.OrderBy(i => i.Index)
.ToListAsync(cancellationToken);
return persisted.Map(ProjectToViewModel).ToList();
}
// Rebuild the watermark/graphics join rows for an item updated in place. Clearing severs the required
// relationship so EF deletes the orphaned join rows (same net effect the delete-and-reinsert path had),
// then re-add from the request. Only the parent item row is preserved — the join rows carry no state.
private static void RebuildChildren(ProgramScheduleItem item, ReplaceProgramScheduleItem request)
{
item.ProgramScheduleItemWatermarks ??= [];
item.ProgramScheduleItemWatermarks.Clear();
foreach (int watermarkId in request.WatermarkIds)
{
item.ProgramScheduleItemWatermarks.Add(
new ProgramScheduleItemWatermark
{
ProgramScheduleItem = item,
WatermarkId = watermarkId
});
}
item.ProgramScheduleItemGraphicsElements ??= [];
item.ProgramScheduleItemGraphicsElements.Clear();
foreach (int graphicsElementId in request.GraphicsElementIds)
{
item.ProgramScheduleItemGraphicsElements.Add(
new ProgramScheduleItemGraphicsElement
{
ProgramScheduleItem = item,
GraphicsElementId = graphicsElementId
});
}
}
private static async Task<Validation<BaseError, ProgramSchedule>> Validate(
TvContext dbContext,
ReplaceProgramScheduleItems request,
ProgramSchedule programSchedule)
{
Validation<BaseError, ProgramSchedule> validation = PlayoutModesMustBeValid(request, programSchedule)
.Bind(programSchedule => CollectionTypesMustBeValid(request, programSchedule))
.Bind(programSchedule => PlaybackOrdersMustBeValid(request, programSchedule));
return await validation.ToEither().Match(
Left: error => Task.FromResult<Validation<BaseError, ProgramSchedule>>(
Fail<BaseError, ProgramSchedule>(error)),
Right: validProgramSchedule => FillerConfigurationsMustBeValid(dbContext, request, validProgramSchedule));
}
private static Validation<BaseError, ProgramSchedule> PlayoutModesMustBeValid(
ReplaceProgramScheduleItems request,
ProgramSchedule programSchedule) =>
request.Items.Map(item => PlayoutModeMustBeValid(item, programSchedule)).Sequence()
.Map(_ => programSchedule);
private static Validation<BaseError, ProgramSchedule> CollectionTypesMustBeValid(
ReplaceProgramScheduleItems request,
ProgramSchedule programSchedule) =>
request.Items.Map(item => CollectionTypeMustBeValid(item, programSchedule)).Sequence()
.Map(_ => programSchedule);
private static async Task<Validation<BaseError, ProgramSchedule>> FillerConfigurationsMustBeValid(
TvContext dbContext,
ReplaceProgramScheduleItems request,
ProgramSchedule programSchedule)
{
foreach (ReplaceProgramScheduleItem item in request.Items)
{
Either<BaseError, ProgramSchedule> result = await FillerConfigurationMustBeValid(
dbContext,
item,
programSchedule);
if (result.IsLeft)
{
return result.ToValidation();
}
}
return programSchedule;
}
private static Validation<BaseError, ProgramSchedule> PlaybackOrdersMustBeValid(
ReplaceProgramScheduleItems request,
ProgramSchedule programSchedule)
{
var keyOrders = new Dictionary<CollectionKey, System.Collections.Generic.HashSet<PlaybackOrder>>();
foreach (ReplaceProgramScheduleItem item in request.Items)
{
if (item.PlaybackOrder is PlaybackOrder.ShuffleInOrder &&
item.FillWithGroupMode is not FillWithGroupMode.None)
{
return new BaseError("Shuffle in Order cannot be used with Fill With Group Mode");
}
var key = new CollectionKey(
item.CollectionType,
item.CollectionId,
item.MediaItemId,
item.MultiCollectionId,
item.SmartCollectionId,
item.RerunCollectionId,
item.PlaylistId,
item.SearchQuery);
if (keyOrders.TryGetValue(key, out System.Collections.Generic.HashSet<PlaybackOrder> playbackOrders))
{
playbackOrders.Add(item.PlaybackOrder);
keyOrders[key] = playbackOrders;
}
else
{
keyOrders.Add(key, new System.Collections.Generic.HashSet<PlaybackOrder> { item.PlaybackOrder });
}
}
return Optional(keyOrders.Values.Count(set => set.Count != 1))
.Filter(count => count == 0)
.Map(_ => programSchedule)
.ToValidation<BaseError>("A collection must not use multiple playback orders");
}
private sealed record CollectionKey(
CollectionType CollectionType,
int? CollectionId,
int? MediaItemId,
int? MultiCollectionId,
int? SmartCollectionId,
int? RerunCollectionId,
int? PlaylistId,
string SearchQuery);
}