Merge remote-tracking branch 'origin/main' into feat/254-mutation-hardening
Build ErsatzTV Image / Docs update reminder (pull_request) Successful in 6s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 4m23s
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 5m49s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
Build ErsatzTV Image / Docs update reminder (push) Has been skipped
Build ErsatzTV Image / Build & test (.NET) (push) Successful in 6m31s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (push) Successful in 9m21s
Build ErsatzTV Image / Build & push image (amd64) (push) Successful in 6m10s
Build ErsatzTV Image / Docs update reminder (pull_request) Successful in 6s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 4m23s
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 5m49s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
Build ErsatzTV Image / Docs update reminder (push) Has been skipped
Build ErsatzTV Image / Build & test (.NET) (push) Successful in 6m31s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (push) Successful in 9m21s
Build ErsatzTV Image / Build & push image (amd64) (push) Successful in 6m10s
# Conflicts: # docs/api-conventions.md # docs/decisions.md
This commit was merged in pull request #266.
This commit is contained in:
+87
-2
@@ -84,7 +84,7 @@ hand-rolling `IActionResult` status codes:
|
||||
|
||||
| Method | Input | Output |
|
||||
|---|---|---|
|
||||
| `ToErrorResult()` | `BaseError` | 404 if `NotFoundError`, else 422 (`ProblemDetails`) |
|
||||
| `ToErrorResult()` | `BaseError` | 404 if `NotFoundError`, **412 if `PreconditionFailedError`** (optimistic-concurrency mismatch, §7a), else 422 (`ProblemDetails`) |
|
||||
| `ToCreatedResult(location, body)` | `Either<BaseError, T>` | `Left` → `ToErrorResult()`; `Right` → 201 + `Location` header |
|
||||
| `ToUpdatedResult()` | `Either<BaseError, T>` | `Left` → `ToErrorResult()`; `Right` → 200 + body |
|
||||
| `ToDeletedResult()` | `Either<BaseError, Unit>` | `Left` → `ToErrorResult()`; `Right` → 204 |
|
||||
@@ -152,6 +152,37 @@ handler's validation when a lookup fails, so the controller-side mapping falls o
|
||||
precedent from the schedules endpoints (see issue #172) and intentional to avoid N+1 validation
|
||||
queries; don't "fix" this without discussing it first.
|
||||
|
||||
### 3c. A durable-save PUT that also triggers a background sync as a side effect
|
||||
|
||||
Some PUT-replace endpoints (issue #202: `PUT /api/media-sources/{plex|jellyfin|emby}/{id}/libraries`)
|
||||
have a synchronous durable write as their primary purpose — the response must reflect that write —
|
||||
but Blazor's editor also fired off a background sync per newly-enabled library after the save. This
|
||||
is a **different shape from §3b**: §3b is for an endpoint whose entire job *is* starting a
|
||||
background operation (so the outcome enum drives the status code); here the enqueue is a fire-and-
|
||||
forget side effect of an otherwise-ordinary write, and the response must still be **200 with the
|
||||
durably-saved data**, not 202.
|
||||
|
||||
Pattern (see `PlexMediaSourcesController.ReplaceLibraryPreferences` / `EnqueuePostSaveSync`):
|
||||
1. Dispatch the write command; on `Left`, return the error — nothing is enqueued.
|
||||
2. **Reload** the saved rows through the same query the GET uses (per §7) — needed both for the
|
||||
response and because ids can change as a result of the save (e.g. a disable-then-re-add).
|
||||
3. Iterate the reloaded rows and, per row that needs a sync, `LockLibrary(id)` — **skip rows whose
|
||||
lock is already held** (mirrors Blazor's `if (Locker.LockLibrary(id))` loop; no 409 for the save
|
||||
itself, only a silent skip for that one row's sync).
|
||||
4. Enqueue the background message(s) for that row; if a multi-message enqueue can throw partway
|
||||
through, wrap it in `try/catch` and release the lock in the `catch` (compensating unlock) before
|
||||
rethrowing — the standard `EnqueueWithTraktLock` one-lock-⇄-one-release discipline (§3b), just
|
||||
invoked from inside a write endpoint instead of a dedicated "start background job" endpoint.
|
||||
5. Return the reloaded data with `200 OK` — never 202 — since the durable save already happened;
|
||||
the enqueue is best-effort and its failure (after a caught/compensated exception) surfaces as a
|
||||
500 on this same request rather than silently dropping the sync.
|
||||
|
||||
This is server-side (not SPA-orchestrated) because the SPA has no access to the scanner channel,
|
||||
and having the SPA fire a second request after the save would open a crash window between "saved"
|
||||
and "synced". See `docs/decisions.md` 2026-07-11 (#202) for the fuller rationale and the specific
|
||||
bug this pattern corrected (Blazor's Plex `Unlock` ordering released the library lock before a
|
||||
dependent second message ran).
|
||||
|
||||
## 4. Artwork contract
|
||||
|
||||
API response DTOs return **rooted, directly-usable artwork URLs** — e.g. `/artwork/posters/...`,
|
||||
@@ -258,7 +289,61 @@ via `ProgramScheduleItemQueryExtensions.IncludeScheduleItemDetails()` (the one i
|
||||
the NRE; the controller's `.ToList()`/serialization does (regression: `ScheduleItemWriteProjectionTests`).
|
||||
GET handlers that feed an ordered list must also `.OrderBy(i => i.Index)` — id order is not index order.
|
||||
|
||||
### 7a. Post-commit side effects run on `CancellationToken.None`
|
||||
## 7a. PUT-replace concurrency (ETag / If-Match / 412)
|
||||
|
||||
The replace-all aggregate PUTs (blocks, templates, schedules items, playlists, collections, playouts,
|
||||
etc.) carry an **optimistic-concurrency contract** so a stale second tab can't silently overwrite a
|
||||
fresher edit (issue #253). The Block endpoints are the reference implementation; PRs 2–4 fan the same
|
||||
recipe across the other aggregates.
|
||||
|
||||
**Token.** Each versioned root implements `IVersionedAggregate` (`int Version`, EF-mapped with
|
||||
`.IsConcurrencyToken()` in its `IEntityTypeConfiguration`). A single dual-provider migration
|
||||
(`AddAggregateVersions`) adds the column (`nullable: false, defaultValue: 0`). Do **not** overload the
|
||||
existing `DateUpdated` — a plain `int` is portable across SQLite/MySQL and decoupled from UI cosmetics.
|
||||
|
||||
**Transport.** The aggregate's GET (the one the editor loads from — e.g. `GET /api/blocks/{id}/items`)
|
||||
emits a strong `ETag: "3"` of `Version`; the PUT sends it back as `If-Match: "3"`. Mismatch → **412
|
||||
Precondition Failed** (distinct from the §3a **409** "build in progress" lock guard). A successful PUT
|
||||
returns the **new** ETag (post-increment) so a same-tab second save doesn't 412 against its own write.
|
||||
`If-Match: *` and (Phase 1) a missing header force-write; a non-canonical/weak/list/malformed header
|
||||
→ 400 (fail-safe; the stricter RFC 7232 "valid-but-non-matching tag → 412" refinement is deferred to
|
||||
#197 — see #265). Parse/emit with `ErsatzTV.Extensions.ConcurrencyHeaders` (`ParseIfMatch` → `IfMatchCondition.ExpectedVersion : Option<int>`,
|
||||
`SetETag`). The items GET returns *children*, so the controller reads `root.Version` separately for the
|
||||
header (here `BlockViewModel` carries `Version`, projected but **not** echoed in the response body —
|
||||
header-only).
|
||||
|
||||
**Handler recipe (the error-prone part).** Introduce the concurrency check as a **standalone `Either`
|
||||
AFTER** the validation pipeline, never via `Apply` — `LanguageExtensions.Apply`/`ToEither` `Join()` a
|
||||
`Seq<BaseError>` down to a base `BaseError`, which would flatten `PreconditionFailedError` to a 422. The
|
||||
reference shape (`ReplaceBlockItemsHandler`):
|
||||
|
||||
```csharp
|
||||
Either<BaseError, Block> validated = LanguageExtensions.ToEither(validation) // explicit: the native
|
||||
.Bind(block => block.CheckVersion(request.ExpectedVersion)); // Validation.ToEither() shadows ours
|
||||
return await validated.Match(
|
||||
Right: block => Persist(dbContext, request, block, cancellationToken),
|
||||
Left: error => Task.FromResult<Either<BaseError, Unit>>(error));
|
||||
```
|
||||
|
||||
In `Persist`, bump **unconditionally** before saving — `root.Version++` — because EF emits the root
|
||||
UPDATE only when a scalar actually differs, so a same-value/no-op PUT-back would otherwise neither fire
|
||||
the token nor rotate other clients' ETags. Then save through
|
||||
`dbContext.SaveChangesWithConcurrencyGuard(ct)` (maps `DbUpdateConcurrencyException` → 412), which is the
|
||||
backstop that closes the load→save TOCTOU the pre-check can't. `CheckVersion` (pure, on
|
||||
`IVersionedAggregate`) and `SaveChangesWithConcurrencyGuard` live in `ErsatzTV.Core` /
|
||||
`ErsatzTV.Application` respectively.
|
||||
|
||||
Add `[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]` and `…412…` to the
|
||||
PUT action. **Config-only boundary**: every mutating handler of an aggregate's *editor-visible config
|
||||
state* bumps `Version` (incl. bulk `ExecuteUpdate/Delete` writers, which add
|
||||
`.SetProperty(x => x.Version, x => x.Version + 1)`); regenerated build output (playout items/history) is
|
||||
outside the token — its handlers neither bump nor are guarded. Test the reference with: stale-If-Match →
|
||||
412 (no mutation), matching/absent → success + bump, no-op save still bumps, and a two-context racing
|
||||
save → 412 (prove it non-vacuous by dropping `.IsConcurrencyToken()` and watching the race test fail).
|
||||
Phase 2 (a later PR) flips a missing `If-Match` from force-write to **428 Precondition Required** once
|
||||
every editor echoes and one release soaks.
|
||||
|
||||
## 7b. Post-commit side effects run on `CancellationToken.None`
|
||||
|
||||
Once a command handler's `await dbContext.SaveChangesAsync(cancellationToken)` (or repository upsert)
|
||||
has **committed**, everything that runs afterwards to complete that mutation's side effect —
|
||||
|
||||
Reference in New Issue
Block a user