Files
ersatztv/ErsatzTV.Application/Scheduling/Commands/ReplaceTemplateItemsHandler.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

181 lines
7.7 KiB
C#

using ErsatzTV.Core;
using ErsatzTV.Core.Domain.Scheduling;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Infrastructure.Extensions;
using Microsoft.EntityFrameworkCore;
namespace ErsatzTV.Application.Scheduling;
public class ReplaceTemplateItemsHandler(IDbContextFactory<TvContext> dbContextFactory)
: IRequestHandler<ReplaceTemplateItems, Either<BaseError, List<TemplateItemViewModel>>>
{
public async Task<Either<BaseError, List<TemplateItemViewModel>>> Handle(
ReplaceTemplateItems request,
CancellationToken cancellationToken)
{
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
Validation<BaseError, Template> 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, Template> validated = LanguageExtensions.ToEither(validation)
.Bind(template => template.CheckVersion(request.ExpectedVersions));
return await validated.Match(
Right: template => Persist(dbContext, request, template, cancellationToken),
Left: error => Task.FromResult<Either<BaseError, List<TemplateItemViewModel>>>(error));
}
private static async Task<Either<BaseError, List<TemplateItemViewModel>>> Persist(
TvContext dbContext,
ReplaceTemplateItems request,
Template template,
CancellationToken cancellationToken)
{
template.Name = request.Name;
template.DateUpdated = DateTime.UtcNow;
dbContext.RemoveRange(template.Items);
template.Items = request.Items.Map(i => BuildItem(template, 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).
template.Version++;
// TODO: refresh any playouts that use this schedule
// foreach (Playout playout in programSchedule.Playouts)
// {
// await _channel.WriteAsync(new BuildPlayout(playout.Id, PlayoutBuildMode.Refresh));
// }
// 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 _ =>
{
await dbContext.Entry(template)
.Collection(t => t.Items)
.Query()
.Include(i => i.Block)
.LoadAsync(cancellationToken);
return Right<BaseError, List<TemplateItemViewModel>>(
template.Items.Map(Mapper.ProjectToViewModel).ToList());
},
Left: error => Task.FromResult(Left<BaseError, List<TemplateItemViewModel>>(error)));
}
private static TemplateItem BuildItem(Template template, ReplaceTemplateItem item) =>
new()
{
TemplateId = template.Id,
BlockId = item.BlockId,
StartTime = item.StartTime
};
private static Task<Validation<BaseError, Template>> Validate(
TvContext dbContext,
ReplaceTemplateItems request,
CancellationToken cancellationToken) =>
TemplateMustExist(dbContext, request.TemplateId, cancellationToken)
.BindT(template => TemplateItemsMustBeValid(dbContext, template, request))
.BindT(template => ValidateTemplateName(dbContext, template, request));
private static async Task<Validation<BaseError, Template>> TemplateItemsMustBeValid(
TvContext dbContext,
Template template,
ReplaceTemplateItems request)
{
var allBlockIds = request.Items.Map(i => i.BlockId).Distinct().ToList();
Dictionary<int, Block> allBlocks = await dbContext.Blocks
.AsNoTracking()
.Filter(b => allBlockIds.Contains(b.Id))
.ToListAsync()
.Map(list => list.ToDictionary(b => b.Id, b => b));
var missingBlockIds = allBlockIds.Filter(id => !allBlocks.ContainsKey(id)).ToList();
if (missingBlockIds.Count > 0)
{
return BaseError.New($"[BlockId] {missingBlockIds.Head()} does not exist.");
}
var allTemplateItems = request.Items.Map(i =>
{
Block block = allBlocks[i.BlockId];
var endTime = i.StartTime + TimeSpan.FromMinutes(block.Minutes);
return new BlockTemplateItem(i.BlockId, i.StartTime, endTime);
})
.ToList();
foreach (BlockTemplateItem item in allTemplateItems)
{
if (item.EndTime > TimeSpan.FromHours(24))
{
return BaseError.New(
$"Block from {item.StartTime} to {item.EndTime} crosses midnight, which is not supported");
}
}
// Compare by index, not value: BlockTemplateItem is a record, so two identical items would be
// value-equal and skipped by an `item == otherItem` guard, letting exact duplicates persist
// unvalidated (issue #172). Index comparison compares every distinct position, so duplicates
// register as a (self-)intersection and are rejected.
for (var i = 0; i < allTemplateItems.Count; i++)
{
BlockTemplateItem item = allTemplateItems[i];
for (var j = 0; j < allTemplateItems.Count; j++)
{
if (i == j)
{
continue;
}
BlockTemplateItem otherItem = allTemplateItems[j];
if (item.StartTime < otherItem.EndTime && otherItem.StartTime < item.EndTime)
{
return BaseError.New(
$"Block from {item.StartTime} to {item.EndTime} intersects block from {otherItem.StartTime} to {otherItem.EndTime}");
}
}
}
return template;
}
private static Task<Validation<BaseError, Template>> TemplateMustExist(
TvContext dbContext,
int templateId,
CancellationToken cancellationToken) =>
dbContext.Templates
.Include(b => b.Items)
.SelectOneAsync(b => b.Id, b => b.Id == templateId, cancellationToken)
.Map(o => o.ToValidation<BaseError>("[TemplateId] does not exist."));
private static async Task<Validation<BaseError, Template>> ValidateTemplateName(
TvContext dbContext,
Template template,
ReplaceTemplateItems request)
{
if (string.IsNullOrWhiteSpace(request.Name) || request.Name.Length > 50)
{
return BaseError.New($"Template name \"{request.Name}\" is invalid");
}
Option<Template> maybeExisting = await dbContext.Templates
.AsNoTracking()
.FirstOrDefaultAsync(d =>
d.Id != request.TemplateId && d.TemplateGroupId == request.TemplateGroupId && d.Name == request.Name)
.Map(Optional);
return maybeExisting.IsSome
? BaseError.New($"A template named \"{request.Name}\" already exists in that template group")
: Success<BaseError, Template>(template);
}
private sealed record BlockTemplateItem(int BlockId, TimeSpan StartTime, TimeSpan EndTime);
}