Merge remote-tracking branch 'origin/main' into feat/235-async-contract
Build ErsatzTV Image / Docs update reminder (pull_request) Successful in 8s
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 7m30s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 5m51s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
Build ErsatzTV Image / Docs update reminder (pull_request) Successful in 8s
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 7m30s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 5m51s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
# Conflicts: # docs/decisions.md
This commit is contained in:
+55
-1
@@ -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 |
|
||||
@@ -307,6 +307,60 @@ 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. 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.
|
||||
|
||||
## 8. Known API warts (don't "fix" without discussion — they're deliberate synthesized rows)
|
||||
|
||||
`GET /api/blocks` and `GET /api/templates` (via `GetAllBlocksHandler` / `GetAllTemplatesHandler` in
|
||||
|
||||
@@ -704,3 +704,35 @@ the entity locks are **in-memory singletons that die with the process**, so a dr
|
||||
lock across restarts (the F7 `finally` covers the *within-process* shutdown-break leak, which is the only way
|
||||
a lock outlives its batch while the process keeps running). Adding a bounded-channel backpressure / graceful
|
||||
drain is out of scope and would not fix a correctness bug.
|
||||
## 2026-07-11 — Optimistic-concurrency contract for replace-all PUTs (#253 PR1: infra + Block reference)
|
||||
|
||||
Replace-all aggregate PUTs had **no** optimistic concurrency — a stale second tab silently overwrote a
|
||||
fresher edit (200, no signal) across ~10 aggregate surfaces. PR1 lands the shared contract on the Block
|
||||
reference aggregate; PRs 2–4 fan it out. The full ratified design + independent-review hardening is
|
||||
[#253#issuecomment-8472](http://192.168.1.95:3000/timothy/ersatztv/issues/253#issuecomment-8472);
|
||||
the mechanics live in `api-conventions.md` §7a. Decisions frozen here:
|
||||
|
||||
- **Token = uniform plain `int Version`** on each root implementing `IVersionedAggregate`, EF-mapped
|
||||
`.IsConcurrencyToken()`, one dual-provider migration (`AddAggregateVersions`, `defaultValue: 0`). **Not**
|
||||
a reused `DateUpdated` (tick-collision, SQLite TEXT precision, couples UI cosmetics to correctness) and
|
||||
**not** a MySQL-native rowversion (portability over provider-native).
|
||||
- **412 Precondition Failed**, not 409 — 409 stays the §3a EntityLocker "build in progress" guard;
|
||||
distinct codes → distinct SPA UX. New `PreconditionFailedError : BaseError` → 412 in `ApiResults.ToErrorResult`.
|
||||
- **Pre-check AND EF token both required.** The handler pre-check (a standalone `Either` introduced AFTER
|
||||
the validation pipeline — never via `Apply`, which `Join()`-flattens the subtype to 422) gives a clean
|
||||
412; the unconditional `root.Version++` + `IsConcurrencyToken` UPDATE-guard + a `SaveChangesWithConcurrencyGuard`
|
||||
backstop closes the residual load→save TOCTOU (`DbUpdateConcurrencyException` → 412).
|
||||
- **Unconditional bump** (not "only when a child changed"): EF writes the root row only when a scalar
|
||||
differs, so a no-op PUT-back must still bump to fire the token and rotate every other client's ETag.
|
||||
- **Config-only aggregate boundary**: every mutating handler of a root's *editor-visible config state*
|
||||
bumps `Version` (incl. bulk `ExecuteUpdate/Delete` writers via `.SetProperty`); regenerated build output
|
||||
(playout items/history) is outside the token — neither bumped nor guarded.
|
||||
- **Header-only ETag**, strong tag of the decimal `Version`; parsed/emitted by `ConcurrencyHeaders`. The
|
||||
successful PUT returns the new ETag (else a same-tab second save 412s against its own write).
|
||||
- **Phasing**: Phase 1 (this arc) = a missing `If-Match` force-writes (zero breakage) while the SPA starts
|
||||
echoing; Phase 2 (a later PR) flips missing → **428** after every editor echoes and one release soaks.
|
||||
`If-Match: *` stays the scripted force-write escape hatch.
|
||||
- **Child stable-identity is OUT of #253** (the "moved fill-group item inherits the wrong slot's state"
|
||||
concern on the positional reconcile) — root-anchored versioning is orthogonal to it; split to **#259**.
|
||||
- **If-Match status semantics** (non-canonical/weak/list → 400) are fail-safe; the stricter RFC 7232
|
||||
"valid-but-non-matching → 412" refinement is deferred to #197 (**#265**).
|
||||
|
||||
@@ -71,6 +71,7 @@ Channel (1) ──< Playout (0..N per channel; ChannelPlayoutSource distinguishe
|
||||
| **Channel concepts** | `Number` (validated by `Channel.NumberValidator` regex), `Group`, `PlayoutSource` (Generated/Mirror; Mirror channels relay another channel via `MirrorSourceChannelId`+`PlayoutOffset`), `PlayoutMode` (Continuous/OnDemand), `TranscodeMode` (OnDemand only, today), `IdleBehavior` (StopOnDisconnect/KeepRunning), `StreamingMode` (TransportStream/HttpLiveStreamingDirect/HttpLiveStreamingSegmenter/TransportStreamHybrid). | `Channel` | `/app/channels`, `/app/edit-channel/{id}`, `/app/new-channel` |
|
||||
| **Guide / EPG (XMLTV)** | Per-channel programme guide generated from playout items; channels with `ShowInEpg=false` are excluded. | `GetChannelGuideHandler` | `/app/guide` (viewer); settings at `/app/settings/xmltv` |
|
||||
| **M3U** | The channel lineup playlist Jellyfin/Dispatcharr consume. | `ChannelPlaylist.ToM3U()` | — |
|
||||
| **Aggregate `Version`** | Optimistic-concurrency token (issue #253): a plain `int Version` on the 9 replace-all roots — `ProgramSchedule`, `Block`, `Template`, `DecoTemplate`, `Playlist`, `Collection`, `Playout`, `MultiCollection`, `RerunCollection` — implementing `IVersionedAggregate`, EF-mapped `.IsConcurrencyToken()`. Surfaced as a strong ETag on the aggregate's GET and checked against `If-Match` on the PUT (mismatch → 412). See `api-conventions.md` §7a. | `IVersionedAggregate` | (not user-edited) |
|
||||
|
||||
## Where things are edited (SPA routes)
|
||||
|
||||
|
||||
@@ -133,6 +133,27 @@ spec-cased vs runtime-cased key (the old `PlaybackTroubleshootingScreen` `#198`
|
||||
`data.channel.fFmpegProfileId` has been removed — read `ffmpegProfileId` straight off the typed
|
||||
response). When you mock an API response in a test, use the generated (runtime) casing.
|
||||
|
||||
## 4a. Optimistic-concurrency editors (ETag / If-Match / 412)
|
||||
|
||||
Replace-all editors (Blocks is the reference; see `api-conventions.md` §7a for the server contract,
|
||||
issue #253) must round-trip the aggregate's concurrency ETag so a stale tab can't silently overwrite a
|
||||
fresher edit:
|
||||
|
||||
- **Transport seam** (`web/src/api/client.ts`): `requestWithMeta<T>(path, options)` returns
|
||||
`{ data, etag }` (reads the `ETag` response header). `request<T>` delegates to it and drops the meta —
|
||||
keep using `request` for endpoints without a concurrency token.
|
||||
- **Domain module** (`web/src/api/blocks.ts`): expose a `…WithMeta` load
|
||||
(`getBlockItemsWithMeta` → `{ data, etag }`) and make the replace accept the last-seen ETag and return
|
||||
the new one: `replaceBlock(id, body, ifMatch?)` → `requestWithMeta(..., { headers: ifMatch ? {'If-Match': ifMatch} : undefined })`.
|
||||
- **Editor**: hold the ETag in a `useRef`; set it from the load GET, and **replace it from the PUT
|
||||
response's ETag on every successful save** (a same-tab second save otherwise 412s against its own
|
||||
write). Keyed reload: a `reloadKey` state in the load `useEffect` dep array lets the conflict flow
|
||||
re-fetch.
|
||||
- **412 UX**: catch `error instanceof ApiError && error.status === 412` on save and open a blocking
|
||||
"changed elsewhere — reload (unsaved changes discarded)" `ConfirmDialog` (Reload bumps `reloadKey`),
|
||||
distinct from a 409 ("build in progress — retry shortly"). All other errors stay the generic save-error
|
||||
path. Reference: `web/src/screens/BlocksScreen.tsx` `BlockEditor`.
|
||||
|
||||
## 5. Artwork rendering
|
||||
|
||||
Render `item.artwork` / `item.poster` (or whatever the DTO field is named) **directly as an `<img
|
||||
|
||||
Reference in New Issue
Block a user