Files
ersatztv/ErsatzTV.Application/MediaCollections/Commands/UpdateCollectionCustomOrderHandler.cs
T
timothy 50cd29d841
Build ErsatzTV Image / Docs update reminder (pull_request) Successful in 6s
Build ErsatzTV Image / decisions.md append-only (pull_request) Successful in 7s
Build ErsatzTV Image / Formatting (changed .cs conform to .editorconfig) (pull_request) Failing after 2m30s
Build ErsatzTV Image / API docs in sync (OpenAPI + endpoint index) (pull_request) Successful in 4m23s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 4m44s
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 5m47s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
fix(api): #265 review — quote-aware If-Match scanner, RFC OWS trim, de-BOM
Independent review fix commit (cold fork MERGEABLE-WITH-NITS + Codex BLOCKED, 2 Highs):

- Codex H1: a comma (0x2C) is a valid etagc and can appear INSIDE a quoted opaque-tag
  ("3,5" is ONE tag). The old Split(',') broke it into two malformed tokens → 400. Replaced
  with a quote-aware position scanner that treats a comma as a separator only outside the
  quotes; "3,5" is now one valid non-canonical tag → 412.
- Codex H2: RFC 7230 OWS is SP/HTAB only. string.Trim() also strips NBSP and other Unicode
  whitespace, letting " * " masquerade as the "*" force-write escape. Trim only
  (' ', '\t'); such input is now Malformed → 400.
- Fork nit: corrected the canonical-guard comment (interior-whitespace tags are rejected by
  IsEtagc, not NumberStyles.None).
- CI Formatting gate: de-BOM the 8 touched legacy Application .cs (charset=utf-8, #311/#310).
- Tests: added comma-in-tag ("3,5", "x,y","3"), empty-element tolerance, NBSP-not-OWS,
  trailing-junk, lowercase-weak, wildcard-in-list cases. Full ErsatzTV.Tests green (1556).

Refs #253 #197
2026-07-12 23:09:36 +02:00

101 lines
4.3 KiB
C#

using System.Threading.Channels;
using ErsatzTV.Application.Playouts;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Interfaces.Repositories;
using ErsatzTV.Core.Scheduling;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Infrastructure.Extensions;
using Microsoft.EntityFrameworkCore;
namespace ErsatzTV.Application.MediaCollections;
public class UpdateCollectionCustomOrderHandler : IRequestHandler<UpdateCollectionCustomOrder, Either<BaseError, Unit>>
{
private readonly ChannelWriter<IBackgroundServiceRequest> _channel;
private readonly IDbContextFactory<TvContext> _dbContextFactory;
private readonly IMediaCollectionRepository _mediaCollectionRepository;
public UpdateCollectionCustomOrderHandler(
IDbContextFactory<TvContext> dbContextFactory,
IMediaCollectionRepository mediaCollectionRepository,
ChannelWriter<IBackgroundServiceRequest> channel)
{
_dbContextFactory = dbContextFactory;
_mediaCollectionRepository = mediaCollectionRepository;
_channel = channel;
}
public async Task<Either<BaseError, Unit>> Handle(
UpdateCollectionCustomOrder request,
CancellationToken cancellationToken)
{
await using TvContext dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
Validation<BaseError, Collection> validation = await Validate(dbContext, request, cancellationToken);
// Optimistic-concurrency check as a standalone Either AFTER validation, never via Apply (which
// Join()s the error Seq and would flatten PreconditionFailedError to a 422) — issue #253 §7a.
Either<BaseError, Collection> validated = LanguageExtensions.ToEither(validation)
.Bind(c => c.CheckVersion(request.ExpectedVersions));
return await validated.Match(
Right: c => ApplyUpdateRequest(dbContext, c, request, cancellationToken),
Left: error => Task.FromResult<Either<BaseError, Unit>>(error));
}
private async Task<Either<BaseError, Unit>> ApplyUpdateRequest(
TvContext dbContext,
Collection c,
UpdateCollectionCustomOrder request,
CancellationToken cancellationToken)
{
foreach (MediaItemCustomOrder updateItem in request.MediaItemCustomOrders)
{
Option<CollectionItem> maybeCollectionItem = c.CollectionItems
.FirstOrDefault(ci => ci.MediaItemId == updateItem.MediaItemId);
foreach (CollectionItem collectionItem in maybeCollectionItem)
{
collectionItem.CustomIndex = updateItem.CustomIndex;
}
}
// Unconditional bump (issue #253 §7a / M1) then guarded save (→ 412 on a lost race).
c.Version++;
Either<BaseError, Unit> saveResult = await dbContext.SaveChangesWithConcurrencyGuard(cancellationToken);
if (saveResult.IsLeft)
{
return saveResult;
}
// Refresh all playouts that use this collection. The old `SaveChangesAsync() > 0` gate is always
// true once the version bumps unconditionally (M2), so run the refresh on any successful save.
// Post-commit enqueue on CancellationToken.None so a late cancellation can't drop the rebuild
// after the commit landed (#254 / §7b).
foreach (int playoutId in await _mediaCollectionRepository
.PlayoutIdsUsingCollection(request.CollectionId))
{
await _channel.WriteAsync(
new BuildPlayout(playoutId, PlayoutBuildMode.Refresh),
CancellationToken.None);
}
return Unit.Default;
}
private static Task<Validation<BaseError, Collection>> Validate(
TvContext dbContext,
UpdateCollectionCustomOrder request,
CancellationToken cancellationToken) =>
CollectionMustExist(dbContext, request, cancellationToken);
private static Task<Validation<BaseError, Collection>> CollectionMustExist(
TvContext dbContext,
UpdateCollectionCustomOrder request,
CancellationToken cancellationToken) =>
dbContext.Collections
.Include(c => c.CollectionItems)
.SelectOneAsync(c => c.Id, c => c.Id == request.CollectionId, cancellationToken)
.Map(o => o.ToValidation<BaseError>("Collection does not exist."));
}