feat(#253 PR2): optimistic-concurrency on schedule-items aggregate

Wire the frozen #253 ETag/If-Match/412 recipe onto ProgramSchedule /
schedule-items, keeping the PR#258 positional in-place reconcile intact.

Backend:
- ReplaceProgramScheduleItems command gains Option<int> ExpectedVersion;
  ReplaceScheduleItemsRequest.ToCommand threads it.
- Handler: standalone CheckVersion Either AFTER validation (so 412 isn't
  flattened to 422), unconditional Version++ before save, guarded save via
  SaveChangesWithConcurrencyGuard, and 412 propagated without running the
  post-save reload/enqueue.
- ProgramScheduleViewModel + Mapper carry Version.
- ScheduleController: GET /items emits ETag; PUT /items parses If-Match
  (malformed -> 400), threads ExpectedVersion, re-queries for the new ETag,
  and advertises 400/412.
- Sibling config-writers (Add/Delete item, Update schedule) bump Version.

Frontend:
- schedules.ts: getScheduleItemsWithMeta + replaceScheduleItems(ifMatch)
  returning ResponseWithMeta.
- SchedulesScreen: etagRef threaded through the #242 dirty-guard (set from
  load + every successful save); 412 opens a conflict ConfirmDialog whose
  Reload discards the draft and re-runs loadItems.

Tests: handler concurrency suite (stale->412 no mutation + fill-group state
untouched, match/absent success+bump, no-op still bumps, racing save->412);
controller ETag/If-Match/412 cases; SchedulesScreen 412-conflict-dialog test.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-11 18:36:25 +02:00
co-authored by Claude Opus 4.8
parent 2de091ea4f
commit 5c9f04fdec
16 changed files with 506 additions and 30 deletions
@@ -4,8 +4,9 @@ namespace ErsatzTV.Controllers.Api.Requests;
public record ReplaceScheduleItemsRequest(List<ScheduleItemRequest> Items)
{
public ReplaceProgramScheduleItems ToCommand(int scheduleId) =>
public ReplaceProgramScheduleItems ToCommand(int scheduleId, Option<int> expectedVersion = default) =>
new(
scheduleId,
(Items ?? []).Select((item, index) => item.ToReplaceCommand(index)).ToList());
(Items ?? []).Select((item, index) => item.ToReplaceCommand(index)).ToList(),
expectedVersion);
}
+38 -5
View File
@@ -104,7 +104,9 @@ public class ScheduleController(IMediator mediator) : ControllerBase
[EndpointDescription(
"Returns the schedule's items plus a computed, best-effort runtime estimate: each item carries a " +
"nullable durationEstimate and the envelope carries a nullable totalDurationEstimate. Estimates are " +
"derived from referenced collection/media runtimes and are null when unbounded or unknown.")]
"derived from referenced collection/media runtimes and are null when unbounded or unknown. The " +
"response also carries a strong ETag of the schedule's version; pass that ETag back as If-Match on " +
"the replace (PUT) to detect a concurrent edit (issue #253).")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(ScheduleItemsResponseModel), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
@@ -116,6 +118,9 @@ public class ScheduleController(IMediator mediator) : ControllerBase
return ApiResults.NotFoundProblem();
}
// The items GET returns children, not the root, so read the schedule's version for the ETag.
ConcurrencyHeaders.SetETag(Response, schedule.Map(s => s.Version).IfNone(0));
ProgramScheduleItemsWithDurationViewModel items =
await mediator.Send(new GetProgramScheduleItemsWithDurations(id), cancellationToken);
return new OkObjectResult(ScheduleItemResponseMapper.ProjectToResponseModel(items));
@@ -143,20 +148,48 @@ public class ScheduleController(IMediator mediator) : ControllerBase
[HttpPut("/api/schedules/{id:int}/items")]
[Tags("Schedules")]
[EndpointSummary("Replace schedule items")]
[EndpointDescription(
"Replaces the schedule's full item list; item indexes are assigned from the array order. Send the " +
"ETag from the items GET as If-Match to reject a stale overwrite with 412 (issue #253); a successful " +
"response carries the new ETag.")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(List<ScheduleItemResponseModel>), 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> ReplaceItems(
int id,
[Required] [FromBody] ReplaceScheduleItemsRequest request,
CancellationToken cancellationToken)
{
IfMatchCondition ifMatch = ConcurrencyHeaders.ParseIfMatch(Request);
if (ifMatch.Kind is IfMatchKind.Malformed)
{
return new BadRequestObjectResult(
new ProblemDetails
{
Status = StatusCodes.Status400BadRequest,
Title = "Invalid If-Match header",
Detail = "If-Match must be a strong ETag of the resource version (e.g. \"3\") or \"*\"."
});
}
Either<BaseError, IEnumerable<ProgramScheduleItemViewModel>> result =
await mediator.Send(request.ToCommand(id), cancellationToken);
return result
.Map(items => items.Select(ScheduleItemResponseMapper.ProjectToResponseModel).ToList())
.ToUpdatedResult();
await mediator.Send(request.ToCommand(id, ifMatch.ExpectedVersion), cancellationToken);
return await result.Match(
Left: error => Task.FromResult(error.ToErrorResult()),
Right: async items =>
{
// Return the new ETag so a same-tab second save doesn't 412 against its own write.
Option<ProgramScheduleViewModel> refreshed =
await mediator.Send(new GetProgramScheduleById(id), cancellationToken);
refreshed.IfSome(vm => ConcurrencyHeaders.SetETag(Response, vm.Version));
return (IActionResult)new OkObjectResult(
items.Select(ScheduleItemResponseMapper.ProjectToResponseModel).ToList());
});
}
[HttpDelete("/api/schedules/{id:int}/items/{itemId:int}")]