Files
ersatztv/ErsatzTV/Controllers/Api/RerunCollectionController.cs
T
timothy 214fad2dcd fix(633): document the 0-based paging contract on the OpenAPI parameters
`api.paging-zero-based` says `pageNum` is 0-based across `/api/v1` and every wrapper
of it. That was true of the MCP tool catalog and the docs, and not true of the
generated OpenAPI document: all 24 paging parameters across the 12 paged operations
were emitted with no `description` at all, so a consumer reading only `v1.json` — the
intended contract, and what generated clients surface to their users — had to infer
the base from `default: 0`. That is the same inference that cost #487 a verification
pass on the MCP side, where the description was present but wrong.

Annotates each `[FromQuery]` paging parameter with `[Description]`
(`System.ComponentModel`), the mechanism `parentId` already used in ImagesController,
and regenerates `v1.json`. `pageSize` states the endpoint's OWN cap, because the caps
genuinely differ — 100 typical, 200 auto-tune members, 1000 search/all-items — and the
record forbids documenting one global number; it also states that the offset derives
from the effective (capped) size, so an over-large `pageSize` narrows the page instead
of widening the offset.

The generated TypeScript client covers DTOs only, not query parameters, so it is
unchanged; `endpoint-index.md` carries summaries, not parameter descriptions, so it is
unchanged too.

Pinned by OpenApiPagingContractTests against the in-process generated document. The
test NAMES the expected set of 12 paged operations rather than only filtering for
parameters called `pageNum`: a filter cannot see an endpoint that should page and
doesn't, which is exactly how two MCP tools escaped the equivalent check in #616. Set
equality is asserted in both directions, and the caps are pinned per endpoint so a
description naming the wrong cap fails — a wrong justification outlives a wrong line.

Mutation-verified both ways: dropping one `[Description]` reddens the description test,
and making one endpoint stop exposing `pageNum`/`pageSize` under those names reddens
the set-equality test.

Refs #633

Decisions-Edit: yes
2026-07-26 11:10:22 +02:00

175 lines
7.5 KiB
C#

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using ErsatzTV.Application.MediaCollections;
using ErsatzTV.Controllers.Api.Requests;
using ErsatzTV.Core;
using ErsatzTV.Core.Api.MediaCollections;
using ErsatzTV.Extensions;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace ErsatzTV.Controllers.Api;
[ApiController]
public class RerunCollectionController(IMediator mediator) : ControllerBase
{
private const int MaxPageSize = 100;
[HttpGet("/api/v1/rerun-collections", Name = "GetRerunCollections")]
[Tags("Rerun Collections")]
[EndpointSummary("Get all rerun collections (paged)")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(PagedRerunCollectionsResponseModel), StatusCodes.Status200OK)]
public async Task<PagedRerunCollectionsResponseModel> GetAll(
[FromQuery] string query = "",
[FromQuery]
[Description("0-based page index: the first page is 0, not 1. A negative value is clamped to 0.")]
int pageNum = 0,
[FromQuery]
[Description("Rows per page (default 100); capped at 100 for this endpoint. The page offset is derived from the effective (capped) size, so a larger value narrows the page instead of widening the offset.")]
int pageSize = 100,
CancellationToken cancellationToken = default)
{
int clampedPageNum = Math.Max(0, pageNum);
int clampedPageSize = Math.Clamp(pageSize, 1, MaxPageSize);
PagedRerunCollectionsViewModel result = await mediator.Send(
new GetPagedRerunCollections(query ?? string.Empty, clampedPageNum, clampedPageSize),
cancellationToken);
return new PagedRerunCollectionsResponseModel(
result.TotalCount,
result.Page.Map(ProjectToResponseModel).ToList());
}
[HttpGet("/api/v1/rerun-collections/{id:int}", Name = "GetRerunCollectionById")]
[Tags("Rerun Collections")]
[EndpointSummary("Get a rerun collection by id")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(RerunCollectionResponseModel), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetById(int id, CancellationToken cancellationToken)
{
Option<RerunCollectionViewModel> result =
await mediator.Send(new GetRerunCollectionById(id), cancellationToken);
// This by-id GET is the editor's load endpoint: emit the concurrency ETag (issue #253).
foreach (RerunCollectionViewModel vm in result)
{
ConcurrencyHeaders.SetETag(Response, vm.Version);
}
return result.Map(ProjectToResponseModel).ToGetResult();
}
[HttpPost("/api/v1/rerun-collections")]
[Tags("Rerun Collections")]
[EndpointSummary("Create a rerun collection")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(RerunCollectionResponseModel), StatusCodes.Status201Created)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> Create(
[Required][FromBody] CreateRerunCollectionRequest request,
CancellationToken cancellationToken)
{
if (!RerunCollectionRequestMapping.IsSupportedSelectionType(request.CollectionType))
{
return BaseError.New(
$"Unsupported collection type '{request.CollectionType}' for a rerun collection")
.ToErrorResult();
}
Either<BaseError, RerunCollectionViewModel> result =
await mediator.Send(request.ToCommand(), cancellationToken);
return result.ToCreatedResult(
vm => $"/api/v1/rerun-collections/{vm.Id}",
ProjectToResponseModel);
}
[HttpPut("/api/v1/rerun-collections/{id:int}")]
[Tags("Rerun Collections")]
[EndpointSummary("Update a rerun collection")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(RerunCollectionResponseModel), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status412PreconditionFailed)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> Update(
int id,
[Required][FromBody] UpdateRerunCollectionRequest request,
CancellationToken cancellationToken)
{
IfMatchCondition ifMatch = ConcurrencyHeaders.ParseIfMatch(Request);
if (ifMatch.Kind is IfMatchKind.Malformed)
{
return ConcurrencyHeaders.MalformedIfMatchProblem();
}
if (!RerunCollectionRequestMapping.IsSupportedSelectionType(request.CollectionType))
{
return BaseError.New(
$"Unsupported collection type '{request.CollectionType}' for a rerun collection")
.ToErrorResult();
}
Either<BaseError, Unit> result =
await mediator.Send(request.ToCommand(id, ifMatch.ExpectedVersions), cancellationToken);
return await result.Match(
Left: error => Task.FromResult(error.ToErrorResult()),
Right: async _ =>
{
Option<RerunCollectionViewModel> rerunCollection =
await mediator.Send(new GetRerunCollectionById(id), cancellationToken);
return rerunCollection.Match(
Some: vm =>
{
// Emit the new ETag so a same-tab second save doesn't 412 against its own write (#253).
ConcurrencyHeaders.SetETag(Response, vm.Version);
return (IActionResult)new OkObjectResult(ProjectToResponseModel(vm));
},
None: () => ApiResults.NotFoundProblem());
});
}
[HttpDelete("/api/v1/rerun-collections/{id:int}")]
[Tags("Rerun Collections")]
[EndpointSummary("Delete a rerun collection")]
[EndpointGroupName("general")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status422UnprocessableEntity)]
public async Task<IActionResult> Delete(int id, CancellationToken cancellationToken)
{
Either<BaseError, Unit> result = await mediator.Send(new DeleteRerunCollection(id), cancellationToken);
return result.ToDeletedResult();
}
// A rerun collection is a tagged union keyed by CollectionType; exactly one of
// Collection / MultiCollection / SmartCollection / MediaItem is populated on the VM.
// Flatten it to a single selected id + name for the SPA.
private static RerunCollectionResponseModel ProjectToResponseModel(RerunCollectionViewModel vm)
{
int? selectedId = vm.Collection?.Id
?? vm.MultiCollection?.Id
?? vm.SmartCollection?.Id
?? vm.MediaItem?.MediaItemId;
string selectedName = vm.Collection?.Name
?? vm.MultiCollection?.Name
?? vm.SmartCollection?.Name
?? vm.MediaItem?.Name;
return new RerunCollectionResponseModel(
vm.Id,
vm.Name,
vm.CollectionType,
selectedId,
selectedName,
vm.FirstRunPlaybackOrder,
vm.RerunPlaybackOrder);
}
}