Files
ersatztv/ErsatzTV.Application/Scheduling/Commands/ReplaceDecoTemplateItemsHandler.cs
T
timothyandClaude Opus 4.8 216130b4d7 fix(#172): API hardening — null-name 500s, duplicate template items, unreachable 404
Clears the still-live findings from #172 (verified against main; #2/#4/#7 and the
auth/search/Trakt tail were already deliberate-documented or fixed since 2026-07-07).

- Null/empty Name → 500 (10 create/replace handlers). Block/Template/DecoTemplate/Deco
  Create+Replace/Update + UpdateFFmpegProfile did `request.Name.Length > 50` on a
  client-nullable string → unhandled NullReferenceException → HTTP 500 (no global
  exception filter). Now `string.IsNullOrWhiteSpace(request.Name) || .Length > 50` →
  422; also rejects empty/whitespace names, matching the group-create handlers'
  NotEmpty behavior. CreatePlaylist coalesces null→"" at the DTO so it was an
  empty-name persist, not a 500; guarded the same way.
- ReplaceTemplateItems overlap validation iterated with an `item == otherItem`
  record value-equality skip, so two exact-duplicate items were value-equal and
  bypassed the intersection check (both persisted). Now index-based (i != j) so
  duplicates register as a self-intersection and are rejected 422.
- Trimmed the unreachable 404 ProducesResponseType from POST /api/blocks/groups and
  POST /api/templates/groups (a create has no parent lookup that can 404); v1.json
  regenerated.
- Regression tests: all 10 name-guard paths + the duplicate-items path (19 cases).
- Docs: decisions.md entry + api-conventions.md §3b null-safe-validation bullet.

fixes #172

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

211 lines
9.7 KiB
C#

using System.Threading.Channels;
using ErsatzTV.Application.Playouts;
using ErsatzTV.Core;
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 ReplaceDecoTemplateItemsHandler(
IDbContextFactory<TvContext> dbContextFactory,
ChannelWriter<IBackgroundServiceRequest> channel)
: IRequestHandler<ReplaceDecoTemplateItems, Either<BaseError, List<DecoTemplateItemViewModel>>>
{
public async Task<Either<BaseError, List<DecoTemplateItemViewModel>>> Handle(
ReplaceDecoTemplateItems request,
CancellationToken cancellationToken)
{
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
Validation<BaseError, DecoTemplate> validation = await Validate(dbContext, request, cancellationToken);
// Introduce the optimistic-concurrency check as a standalone Either AFTER the validation
// pipeline (never via Apply) so a PreconditionFailedError survives to a 412 and is not
// flattened to a generic 422 by Join() (issue #253 / api-conventions §7a).
Either<BaseError, DecoTemplate> validated = LanguageExtensions.ToEither(validation)
.Bind(decoTemplate => decoTemplate.CheckVersion(request.ExpectedVersions));
return await validated.Match(
Right: decoTemplate => Persist(dbContext, request, decoTemplate, cancellationToken),
Left: error => Task.FromResult<Either<BaseError, List<DecoTemplateItemViewModel>>>(error));
}
private async Task<Either<BaseError, List<DecoTemplateItemViewModel>>> Persist(
TvContext dbContext,
ReplaceDecoTemplateItems request,
DecoTemplate decoTemplate,
CancellationToken cancellationToken)
{
decoTemplate.Name = request.Name;
decoTemplate.DateUpdated = DateTime.UtcNow;
dbContext.RemoveRange(decoTemplate.Items);
decoTemplate.Items = request.Items.Map(i => BuildItem(decoTemplate, i)).ToList();
// Unconditional bump: EF emits the root UPDATE only when a scalar actually differs, so a
// same-value/no-op save would otherwise write no root row and neither fire the concurrency
// token nor rotate other clients' ETags. Bumping guarantees both on every save (issue #253).
decoTemplate.Version++;
// Save through the guard so an EF concurrency failure (a racing writer won between our load
// and save) maps to 412 rather than surfacing as a 500.
Either<BaseError, Unit> saved = await dbContext.SaveChangesWithConcurrencyGuard(cancellationToken);
return await saved.Match(
Right: async _ =>
{
// Deco/break/default-filler content is only (re)applied during a Reset build (a Continue keeps
// the frozen DecoDefault filler items), and BlockKey change-detection has no deco dimension, so
// nothing self-heals a deco-template edit — the editor returned 200 but built filler stayed
// stale until a manual Reset (#251). Enqueue a Reset for every playout that references this
// deco template. 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 the affected-playout query OR the enqueue and leave content stale. Only runs after a
// successful save (issue #253) — a 412/422 must not enqueue a Reset for content that was never
// persisted.
List<int> playoutIds = await dbContext.PlayoutTemplates
.Where(pt => pt.DecoTemplateId == decoTemplate.Id)
.Select(pt => pt.PlayoutId)
.Distinct()
.ToListAsync(CancellationToken.None);
foreach (int playoutId in playoutIds)
{
await channel.WriteAsync(
new BuildPlayout(playoutId, PlayoutBuildMode.Reset),
CancellationToken.None);
}
await dbContext.Entry(decoTemplate)
.Collection(t => t.Items)
.Query()
.Include(i => i.Deco)
.LoadAsync(cancellationToken);
return Right<BaseError, List<DecoTemplateItemViewModel>>(
decoTemplate.Items.Map(Mapper.ProjectToViewModel).ToList());
},
Left: error => Task.FromResult(Left<BaseError, List<DecoTemplateItemViewModel>>(error)));
}
private static DecoTemplateItem BuildItem(DecoTemplate decoTemplate, ReplaceDecoTemplateItem item) =>
new()
{
DecoTemplateId = decoTemplate.Id,
DecoId = item.DecoId,
StartTime = item.StartTime,
EndTime = item.EndTime
};
private static Task<Validation<BaseError, DecoTemplate>> Validate(
TvContext dbContext,
ReplaceDecoTemplateItems request,
CancellationToken cancellationToken) =>
DecoTemplateMustExist(dbContext, request.DecoTemplateId, cancellationToken)
.BindT(decoTemplate => DecoTemplateNameMustBeValid(dbContext, decoTemplate, request))
.BindT(decoTemplate => DecoTemplateItemsMustBeValid(dbContext, decoTemplate, request));
// Hardening (deliberate deviation from the original handler): rather than silently filtering out
// invalid items (unknown DecoId, StartTime >= EndTime, or overlapping ranges) - the same silent-drop
// and silent-overlap bug class fixed for ReplaceTemplateItemsHandler in #144 S2 - reject the whole
// request with a 422 so the caller knows exactly what is wrong. EndTime == TimeSpan.Zero means
// "end of day" (24:00) and is treated as such for both the ordering and overlap checks.
private static async Task<Validation<BaseError, DecoTemplate>> DecoTemplateItemsMustBeValid(
TvContext dbContext,
DecoTemplate decoTemplate,
ReplaceDecoTemplateItems request)
{
var allDecoIds = request.Items.Map(i => i.DecoId).Distinct().ToList();
Dictionary<int, Deco> allDecos = await dbContext.Decos
.AsNoTracking()
.Filter(d => allDecoIds.Contains(d.Id))
.ToListAsync()
.Map(list => list.ToDictionary(d => d.Id, d => d));
var missingDecoIds = allDecoIds.Filter(id => !allDecos.ContainsKey(id)).ToList();
if (missingDecoIds.Count > 0)
{
return BaseError.New($"[DecoId] {missingDecoIds.Head()} does not exist.");
}
var itemsWithEffectiveEnd = request.Items
.Map(i => new DecoTemplateItemRange(
i.DecoId,
i.StartTime,
i.EndTime,
i.EndTime == TimeSpan.Zero ? TimeSpan.FromHours(24) : i.EndTime))
.ToList();
foreach (DecoTemplateItemRange item in itemsWithEffectiveEnd)
{
if (item.StartTime < TimeSpan.Zero || item.StartTime >= TimeSpan.FromHours(24) ||
item.EndTime < TimeSpan.Zero || item.EndTime > TimeSpan.FromHours(24))
{
return BaseError.New(
$"Deco from {item.StartTime} to {item.EndTime} must be within a single day (00:00 to 24:00)");
}
if (item.StartTime >= item.EffectiveEndTime)
{
return BaseError.New(
$"Deco from {item.StartTime} to {item.EndTime} must start before it ends");
}
}
foreach (DecoTemplateItemRange item in itemsWithEffectiveEnd)
{
foreach (DecoTemplateItemRange otherItem in itemsWithEffectiveEnd)
{
if (item == otherItem)
{
continue;
}
if (item.StartTime < otherItem.EffectiveEndTime && otherItem.StartTime < item.EffectiveEndTime)
{
return BaseError.New(
$"Deco from {item.StartTime} to {item.EndTime} intersects deco from {otherItem.StartTime} to {otherItem.EndTime}");
}
}
}
return decoTemplate;
}
private sealed record DecoTemplateItemRange(int DecoId, TimeSpan StartTime, TimeSpan EndTime, TimeSpan EffectiveEndTime);
private static Task<Validation<BaseError, DecoTemplate>> DecoTemplateMustExist(
TvContext dbContext,
int decoTemplateId,
CancellationToken cancellationToken) =>
dbContext.DecoTemplates
.Include(b => b.Items)
.SelectOneAsync(b => b.Id, b => b.Id == decoTemplateId, cancellationToken)
.Map(o => o.ToValidation<BaseError>("[DecoTemplateId] does not exist."));
private static async Task<Validation<BaseError, DecoTemplate>> DecoTemplateNameMustBeValid(
TvContext dbContext,
DecoTemplate decoTemplate,
ReplaceDecoTemplateItems request)
{
if (string.IsNullOrWhiteSpace(request.Name) || request.Name.Length > 50)
{
return BaseError.New($"Deco template name \"{request.Name}\" is invalid");
}
Option<DecoTemplate> maybeExisting = await dbContext.DecoTemplates
.AsNoTracking()
.FirstOrDefaultAsync(d =>
d.Id != request.DecoTemplateId && d.DecoTemplateGroupId == request.DecoTemplateGroupId &&
d.Name == request.Name)
.Map(Optional);
return maybeExisting.IsSome
? BaseError.New($"A deco template named \"{request.Name}\" already exists in that deco template group")
: Success<BaseError, DecoTemplate>(decoTemplate);
}
}