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

# Conflicts:
#	docs/api-conventions.md
#	docs/decisions.md
This commit was merged in pull request #266.
This commit is contained in:
2026-07-11 18:10:30 +02:00
133 changed files with 28151 additions and 913 deletions
+87 -2
View File
@@ -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 —
+48 -21
View File
@@ -122,17 +122,35 @@ target query and harmlessly ignored). The incoming query string is merged into `
> | Media browse/detail (read paths + image browser) | PARITY-OK | — |
> | Media browse/detail (mutations, per-show scan, episode info/troubleshoot) | PARITY-OK (shared Add-to layer + scan/info/troubleshoot wired, 2026-07-10; mutation controls gated on kind/query/page refetch — #221) | — |
> | Schedules editors | PARITY-OK (full item + schedule CRUD rebuild, draft/explicit-Save, all Blazor fields/gates/resets; 2026-07-11) | **#207 DONE** |
> | Media sources | **disproven — moved to Section 3** | **#202** |
> | Media sources | **PARITY-OK** (#202 DONE 2026-07-11 — moved back from Section 3; new SPA screens under `/app/libraries/*` over a new REST write API) | — |
>
> Bold issues + #202 are MUST-FIX gates for #91 phase (b); #212 DONE 2026-07-11; #213 closed 2026-07-11.
> Bold issues are MUST-FIX gates for #91 phase (b); #212 DONE 2026-07-11; #213 closed 2026-07-11; #202 DONE 2026-07-11.
**As of ersatztv#204, this section is empty** — every route the mutation-depth sweep marked
PARITY-OK now has a redirect entry (exact `Map` or a `PatternRule`) and has moved to **Section 1**.
The SPA screens were verified against `web/src/App.tsx`'s route table and `web/src/screens/` when
each was built (scheduling parity #144/#162; troubleshooting/YAML #145; media detail + image browser
#141/#183); #204 only added the redirects. The one route still deliberately un-redirected is
`/media/sources/*` — disproven and tracked in **Section 3** (#202) — plus the `/system/health`
escape hatch in **Section 4**.
As of ersatztv#204, every route the mutation-depth sweep marked PARITY-OK received a redirect entry
(an exact `Map` entry or a Tier-2 `PatternRule`) and moved to **Section 1** — EXCEPT the 14
`/media/sources/*` routes. Those became **SPA-READY as of #202 (DONE 2026-07-11)**: new screens under
`/app/libraries/*` (`LibrariesScreen` hub + `LocalLibraryEditScreen`, `PlexSourceScreen`,
`RemoteSourceScreen`, `RemoteConnectionEditScreen`, `RemoteLibrariesEditScreen`,
`PathReplacementsEditScreen`) over a new REST write API. They are listed below; their redirect entries
are **deferred to the #91b removal PR** (matching the pre-removal spot-check convention). Once those
redirects land, this section is empty.
| Blazor route | Blazor file | SPA route | Notes |
|---|---|---|---|
| `/media/sources/local` | `LocalLibraries.razor` | `/app/libraries` | local-library rows on the hub (list, scan, gear → editor); **#202** |
| `/media/sources/local/add` | `LocalLibraryEditor.razor` (add mode) | `/app/libraries/local/new` | `LocalLibraryEditScreen` create mode: name/media-kind/paths (`path-exists` pre-check); **#202** |
| `/media/sources/local/{Id:int}/edit` | `LocalLibraryEditor.razor` (edit mode) | `/app/libraries/local/{id}` | `LocalLibraryEditScreen` edit mode: name + path add/delete (count-confirm)/move (incl. "(New Library)"), media-kind immutable; **#202** |
| `/media/sources/plex` | `PlexMediaSources.razor` | `/app/libraries/plex` | `PlexSourceScreen`: OAuth pin-flow sign-in/fix-credentials/sign-out, server table, per-server Refresh; **#202** |
| `/media/sources/plex/{Id:int}/libraries` | `PlexLibrariesEditor.razor` | `/app/libraries/plex/{id}/sync` | `RemoteLibrariesEditScreen` (family=plex): sortable Name/MediaKind, per-library sync toggle + Save; **#202** |
| `/media/sources/plex/{Id:int}/paths` | `PlexPathReplacementsEditor.razor` | `/app/libraries/plex/{id}/path-replacements` | `PathReplacementsEditScreen` (family=plex); **#202** |
| `/media/sources/jellyfin` | `JellyfinMediaSources.razor` | `/app/libraries/jellyfin` | `RemoteSourceScreen` (family=jellyfin): connect/edit-connection/disconnect + server table; **#202** |
| `/media/sources/jellyfin/edit` | `JellyfinMediaSourceEditor.razor` | `/app/libraries/jellyfin/connection` | `RemoteConnectionEditScreen` (family=jellyfin): address prefilled, api-key set-affordance (never displayed once set); **#202** |
| `/media/sources/jellyfin/{Id:int}/libraries` | `JellyfinLibrariesEditor.razor` | `/app/libraries/jellyfin/{id}/sync` | `RemoteLibrariesEditScreen` (family=jellyfin); **#202** |
| `/media/sources/jellyfin/{Id:int}/paths` | `JellyfinPathReplacementsEditor.razor` | `/app/libraries/jellyfin/{id}/path-replacements` | `PathReplacementsEditScreen` (family=jellyfin); **#202** |
| `/media/sources/emby` | `EmbyMediaSources.razor` | `/app/libraries/emby` | `RemoteSourceScreen` (family=emby); **#202** |
| `/media/sources/emby/edit` | `EmbyMediaSourceEditor.razor` | `/app/libraries/emby/connection` | `RemoteConnectionEditScreen` (family=emby); **#202** |
| `/media/sources/emby/{Id:int}/libraries` | `EmbyLibrariesEditor.razor` | `/app/libraries/emby/{id}/sync` | `RemoteLibrariesEditScreen` (family=emby); **#202** |
| `/media/sources/emby/{Id:int}/paths` | `EmbyPathReplacementsEditor.razor` | `/app/libraries/emby/{id}/path-replacements` | `PathReplacementsEditScreen` (family=emby); **#202** |
## Section 3 — BLAZOR-ONLY (blocking issues)
@@ -164,17 +182,26 @@ search preview. The `POST /api/collections/{id}/items` bogus-id case already ret
Nothing remains here. The playback troubleshooting screen (`/app/troubleshooting/playback`,
`PlaybackTroubleshootingScreen.tsx`) is built and now lives in Section 2.
### Media sources — #202 (found by the #91 cold review, 2026-07-09)
### Media sources — #202 DONE (2026-07-11)
| Blazor route | Blazor file | Blocking issue |
|---|---|---|
| `/media/sources/{local,plex,jellyfin,emby}/...` | `LocalLibraries.razor`, `PlexMediaSources.razor`, `JellyfinMediaSources.razor`, `EmbyMediaSources.razor` + editors | **#202** |
Nothing remains here. Found by the #91 cold review (2026-07-09): the SPA `/app/libraries` screen
listed sources/libraries and could trigger scans, but source add/edit, connection parameters,
path replacements, and library enable/disable had **no SPA UI and no write REST API**
(`MediaSourcesController` was GET-only; "Add Source" was a hardcoded disabled stub) — a fresh
install could not connect any library without Blazor.
Previously (wrongly) listed in Section 2 as "merged into libraries screen": the SPA
`/app/libraries` screen lists sources/libraries and can trigger scans, but source add/edit,
connection parameters, path replacements, and library enable/disable have **no SPA UI and no
write REST API** (`MediaSourcesController` is GET-only; the "Add Source" button is a hardcoded
disabled stub). A fresh install could not connect any library without Blazor.
**Resolved by #202**: new write controllers (`LocalLibrariesController` under
`/api/libraries/local/*`; `PlexMediaSourcesController`/`JellyfinMediaSourcesController`/
`EmbyMediaSourcesController` under `/api/media-sources/{plex|jellyfin|emby}/*`) wrap the existing
MediatR commands (no new commands, no DB migration), plus new SPA screens
(`LocalLibraryEditScreen`, `PlexSourceScreen`, `RemoteSourceScreen`, `RemoteConnectionEditScreen`,
`RemoteLibrariesEditScreen`, `PathReplacementsEditScreen`) under the now-`allowSubPaths`
`/app/libraries/*` route. All 14 Blazor routes now have SPA equivalents — see the per-route table
in Section 2 (moved there from this section). Fixed along the way (pre-existing bugs #202 chose to
own, not just parity-copy): the Plex pin-flow lock leak on an abandoned OAuth flow, cross-source
overwrite in the path-replacement repo SQL, non-`finally` lock release in sign-out/disconnect
handlers, and the secure `apiKey` contract (never served over GET). Full design rationale in
`docs/decisions.md` (2026-07-11 entries) and the capability matrix posted on issue #202.
### Schedule editors — #207 DONE (2026-07-11)
@@ -242,9 +269,9 @@ intentional exit ramp until phase (b) removes Blazor entirely.
## Section 5 — Removal execution runbook (#91 phase b, Step 2/3)
The removal PR is **gated** — it starts only after these clear: #202 (media-source write API + SPA),
#235 F9 (deep-scan + external-collections-scan API — no API today, so `Libraries.razor` can't be deleted
yet), and the **mandatory cold adversarial pass** (#91 comment 2026-07-09). (#204's id-carrying pattern
The removal PR is **gated** — it starts only after these clear: ~~#202 (media-source write API + SPA)~~
**DONE 2026-07-11**, #235 F9 (deep-scan + external-collections-scan API — no API today, so `Libraries.razor`
can't be deleted yet), and the **mandatory cold adversarial pass** (#91 comment 2026-07-09). (#204's id-carrying pattern
redirects landed 2026-07-11; its catch-all fallback that replaces `MapFallbackToPage("/_Host")` is folded
into Step 2 below, since it can only ship when `_Host` is deleted.) When those close, the removal-PR routine
executes, in order:
+120 -1
View File
@@ -460,6 +460,92 @@ into the moved `progressFromChannelState` (behavior-identical — `ChannelState.
dispatch is #238's owned bug and out of scope for a behavior-preserving extraction; the shell/action redesign
is deferred to #247 (epic phase 4).
## 2026-07-11 — Media-source management REST write API + SPA (#202)
Replaced the Blazor `/media/sources/{local,plex,jellyfin,emby}/...` pages (14 routes) with SPA
screens under `/app/libraries/*` over new write controllers (`LocalLibrariesController`,
`Plex|Jellyfin|EmbyMediaSourcesController`), wrapping existing MediatR commands 1:1 (no new
commands, no DB migration). Full design + adversarial-review reconciliation:
`docs/handoffs/` session record and issue #202. The design surfaced and fixed several pre-existing
Application/Infrastructure bugs newly reachable from a programmatic client; each is recorded here
because it changes documented behavior, not just adds a route.
**Secure `apiKey` contract (Jellyfin/Emby connection).** The connection GET
(`RemoteConnectionResponseModel`) returns `{ address, hasApiKey }` — the stored key **never**
leaves the server, closing a leak where the old design would have served the raw key from an
unauthenticated GET under any-origin CORS. On the connection PUT, a blank/omitted `apiKey` means
*retain the existing key*; a non-blank value sets a new one; the key is **required on first
connect** (no existing secret) → 422. Rationale: GETs aren't behind `X-Api-Key`
(`ApiKeyAuthorizationFilter` only guards mutating verbs), so a secret-bearing GET is a real
exposure regardless of how obscure the route is. **Stated explicitly as an input to #197** (the
planned read-side-auth review for secret-bearing GETs) — #197 should treat "does any GET return a
credential" as one of its checks, not just this one instance.
**Three list-replace identity contracts, not one uniform one.** An earlier draft assumed a single
"`Id<1`=add / missing=delete / id-preserved" contract across all three PUT-replace families; source
inspection proved that false for two of them:
- *Remote library sync preferences* (`PUT .../{id}/libraries`) — the command carries no source id
and the handler toggles only the ids present in the body; a row **absent** from the request is
left untouched, not deleted (libraries are sync-discovered, never created via this PUT, so there
are no `Id=0` adds either). The controller validates the submitted id set against
`Get{Family}LibrariesBySourceId(id)` (422 on any id not owned by the route's source — closes a
cross-source hole). Identity is **not stable across a disable**: `Disable{Family}LibrarySync`
removes and re-adds the row with a fresh id, so the SPA keys its draft to `(name, mediaKind)`,
never to `Id`, and refetches after every save (the PUT returns the reloaded list).
- *Path replacements* (`PUT .../{id}/path-replacements`) — id-based (existing `Id`=update,
`Id<1`=add, absent=delete) as documented, **but** the repo UPDATE SQL had no source-id predicate
(`WHERE Id = @id`, no `AND {Family}MediaSourceId = @id`), so a PUT to source A could silently
overwrite source B's row with the same numeric id. Fixed with a handler-level ownership guard
(reject any incoming positive id not in this source's current set → 422, no partial mutation)
**and** the repo SQL predicate itself (defense-in-depth for any other caller of that repo method).
- *Local library paths* (`PUT /api/libraries/local/{id}`) — identity is the **normalized path
string** (full path, trailing-separator/case-insensitive), not `Id`; `Id` in the request is
advisory. Renaming a path is delete-old+add-new under the hood (its `LibraryPath.Id` changes).
Kept as-is (matches the entrenched, tested Blazor behavior and how the SPA edits by value); not
rewritten to id-based identity, which would be a bigger, riskier change out of #202's scope.
**Plex pin-flow as REST: poll until the lock releases, exception-safe non-handoff unlock.** The
SPA polls `GET /api/media-sources/plex` rather than a per-pin status resource (no pin-addressable
server state exists to expose; SSE/push was already rejected, 2026-07-09). Polling contract is
`isLocked && !isAuthorized` = waiting on the user; `isLocked && isAuthorized` = finalizing
(discovering servers — **do not** stop here, the server list is still empty);
`!isLocked && isAuthorized` = success; `!isLocked && !isAuthorized` = timed out/abandoned. This
required fixing a **latent lock-leak bug**: `TryCompletePlexPinFlowHandler` threw
`OperationCanceledException` on its 2-minute timeout instead of returning `false`, and nothing
unlocked on that path — an abandoned sign-in wedged the Plex lock until restart or manual sign-out.
Fix releases `UnlockPlex()` on the timeout-throw, a poll-exception, and an enqueue-exception — but
**deliberately not** in an unconditional `finally`: on success the lock is handed off to
`SynchronizePlexMediaSources`, the sole releaser after server discovery; a blanket `finally` would
double-release and release *before* discovery completes, re-opening the same race the fix closes.
This is the same non-owner-token discipline as the #231 `EntityLocker` model (2026-07-11 entry
above), applied to the pin-flow's handoff-vs-terminal distinction specifically.
**404 comes from the controller pre-check, not the handler.** `Apply`/`ToEitherAsync` both
`.Join()` errors, which flattens any `NotFoundError` inside a joined `Validation` down to a plain
422. So every id-taking endpoint's real 404 is a controller-side pre-check
(`Get...ById(id)`-is-`None` → `ApiResults.NotFoundProblem`, the `TemplateController.DeleteGroup`
pattern), not a handler-level conversion — converting the joined validators to `NotFoundError`
would be dead code, since the join discards the distinction anyway. This is check-then-act (a
delete racing between the pre-check and the command falls through to the handler's own 422, not a
404); accepted and tested against the actual runtime error type rather than a hoped-for handler 404.
**"Scan All" dropped, not implemented.** The disabled SPA header button on the libraries hub was
speculative UI with **no Blazor equivalent** (`Libraries.razor` only ever supported per-library
scan). Removed rather than backed with a new bulk-scan endpoint; per-library scan (#232) and the
new per-source refresh-libraries endpoints (P8/J9/E9) cover the real capability set.
**App-owned popstate for guarded sub-path routes.** `LocalLibraryEditScreen` and the other
`/app/libraries/*` editors are the first screens to both register a dirty-navigation guard *and*
track their own sub-path pathname — the combination `spa-conventions.md` §8 had flagged as
unvalidated. React commits child passive effects before parent ones, so a sub-path wrapper that
self-registers `popstate` would fire (and switch sub-screen) *before* App's guard-restore listener
could veto. Resolution: App owns `popstate` centrally for the `libraries` route and only pushes an
approved sub-path down to the wrapper (which no longer self-registers `popstate`); on a vetoed pop
App re-pushes the pre-pop URL and the wrapper never sees the rejected path. This is scoped to the
`libraries` route only (gated on `activeRoute === 'libraries'`) so unguarded sub-path routes
(Playouts, Media) stay byte-identical. See `spa-conventions.md` §2/§8 for the updated exemplar
list and the resolved caveat text.
## 2026-07-11 — Legacy→SPA redirect matcher: exact map + ordered segment-template patterns (#204)
`LegacyUiRedirects.TryGetRedirect` grew from a single exact-path dictionary to a **two-tier matcher**
@@ -564,6 +650,39 @@ action of the Step 2 deletion PR merge** (not before — `main` moves until then
Not cut this session — `main` still carries Blazor and will advance before the removal PR.
## 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**).
## 2026-07-11 — Post-commit side effects run on `CancellationToken.None` (generalized from #251 to #254)
Audit #22 (adversarial-reviewer) found ~20 command handlers threading the request `cancellationToken`
@@ -577,7 +696,7 @@ policy across the codebase.
**Decision.** Once a mutation has committed, the *entire* compensating side effect — enqueues, publishes,
reindexes, cache refreshes, and any post-commit lookup that **gates** one of those enqueues — runs on
`CancellationToken.None`. The commit is the point of no return; past it the side effect must not be
half-abortable. Full convention + the two boundaries in `docs/api-conventions.md` §7a.
half-abortable. Full convention + the two boundaries in `docs/api-conventions.md` §7b.
**Scope of the #254 sweep (this PR).** Swept the single-`SaveChanges` handlers under `MediaCollections/`,
`ProgramSchedules/`, `Playouts/`, `Channels/` (20 handlers). Deliberately **excluded**:
+20 -3
View File
@@ -63,14 +63,15 @@ Channel (1) ──< Playout (0..N per channel; ChannelPlayoutSource distinguishe
| **RerunCollection** | One source (collection/media item/multi/smart) with separate `FirstRunPlaybackOrder` vs `RerunPlaybackOrder`. | `RerunCollection` | `/app/rerun-collections` (#152) |
| **Playlist** / **PlaylistGroup** | Ordered `PlaylistItem`s; `IsSystem` flag marks built-in/non-deletable playlists and groups. | `Playlist`, `PlaylistGroup`, `PlaylistItem` | `/app/playlists` |
| **Media kinds** | `CollectionType` enum distinguishes container kinds (Collection/TelevisionShow/TelevisionSeason/Artist/MultiCollection/SmartCollection/Playlist/RerunFirstRun/RerunRerun/SearchQuery) from leaf media kinds (Movie/Episode/MusicVideo/OtherVideo/Song/Image/RemoteStream) plus synthetic `FakeCollection`/`FakePlaylistItem`. Concrete media entities: `Movie`, `Show`/`Season`/`Episode`, `Artist`/`MusicVideo`/`Song`, `OtherVideo`, `Image`, `RemoteStream` (`ErsatzTV.Core/Domain/MediaItem/`). | `MediaItem` subclasses | `/app/media?kind=...` |
| **Library / LibraryPath / LibraryFolder** | `Library` (abstract; Local/Plex/Jellyfin/Emby subclasses) owns one or more `LibraryPath`s (scan roots); each path has a `LibraryFolder` tree used for browsing and image-folder duration metadata. | `Library`, `LibraryPath`, `LibraryFolder` | `/app/libraries` |
| **Media source kind** | `MediaSourceKind`: Local/Plex/Jellyfin/Emby — the origin server type for a `Library`. | `MediaSourceKind` | `/app/libraries` |
| **Library / LibraryPath / LibraryFolder** | `Library` (abstract; Local/Plex/Jellyfin/Emby subclasses) owns one or more `LibraryPath`s (scan roots); each path has a `LibraryFolder` tree used for browsing and image-folder duration metadata. | `Library`, `LibraryPath`, `LibraryFolder` | `/app/libraries` (hub: list + scan); `/app/libraries/local/{id}` (`/new`) for local library name/media-kind/path CRUD + move-path (#202) |
| **Media source kind** | `MediaSourceKind`: Local/Plex/Jellyfin/Emby — the origin server type for a `Library`. | `MediaSourceKind` | `/app/libraries` (hub); connect/edit/disconnect and per-source library-sync + path-replacements now live at `/app/libraries/{plex\|jellyfin\|emby}` (+ `/connection`, `/{id}/sync`, `/{id}/path-replacements`) — #202, previously Blazor-only |
| **MediaItemState** | Health flag on a media item: Normal/FileNotFound/Unavailable/RemoteOnly. Drives the Trash screen. | `MediaItemState` | `/app/trash` |
| **PlayoutItem** | One materialized, built entry in a playout's timeline (the actual thing that will play at a given time). | `PlayoutItem` | (generated, not directly edited) |
| **PlayoutHistory** | Rotation/rerun bookkeeping per block (`BlockId`) + collection `Key`/`ChildKey`, used by block-playout schedulers to avoid repeats; inspectable via Troubleshooting. | `PlayoutHistory` | `/app/troubleshooting/blocks` |
| **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)
@@ -82,7 +83,23 @@ Primary nav: `/app` (dashboard), `/app/channels`, `/app/new-channel`, `/app/guid
Media nav: `/app/media` (generic kind-filtered browse, `?kind=movies|shows|artists|music-videos|
other-videos|remote-streams|images`), `/app/search`, `/app/trash`, `/app/collections` (manual +
smart), `/app/multi-collections` (#151), `/app/rerun-collections` (#152),
`/app/filler-presets`, `/app/libraries`, `/app/trakt-lists`.
`/app/filler-presets`, `/app/libraries` (+ sub-paths, see below), `/app/trakt-lists`.
**Media sources / libraries (#202, 2026-07-11)**: `/app/libraries` is an `allowSubPaths` route
(`LibrariesRouteScreen`, App-owned popstate — see `spa-conventions.md` §2/§8). The hub itself lists
sources/libraries and triggers scans; connecting/editing/removing a source and its libraries now
happens at:
- `/app/libraries/local/new`, `/app/libraries/local/{id}` — `LocalLibraryEditScreen`: name,
media-kind (create-only), path add/move/delete.
- `/app/libraries/plex` — `PlexSourceScreen`: OAuth pin-flow sign-in/fix-credentials/sign-out.
- `/app/libraries/{jellyfin|emby}` — `RemoteSourceScreen`; `/app/libraries/{jellyfin|emby}/connection`
— `RemoteConnectionEditScreen` (address + api-key, key never displayed once set).
- `/app/libraries/{plex|jellyfin|emby}/{id}/sync` — `RemoteLibrariesEditScreen` (per-library sync
toggle); `/app/libraries/{plex|jellyfin|emby}/{id}/path-replacements` — `PathReplacementsEditScreen`.
These replace the Blazor `/media/sources/{local,plex,jellyfin,emby}/...` pages over the new
`/api/libraries/local/*` and `/api/media-sources/{plex|jellyfin|emby}/*` write endpoints — see
`docs/blazor-route-parity.md` Section 2 for the full per-route mapping.
System nav: `/app/settings` (sub-tabs: streaming/system/logging/playout/scanner/general/xmltv —
all mapped 1:1 from legacy `/settings/*` Blazor routes), `/app/logs`, `/app/troubleshooting` (+
+49 -1
View File
@@ -2,7 +2,7 @@
*Generated by `scripts/generate-endpoint-index.py` from `ErsatzTV/wwwroot/openapi/v1.json`. Do not edit by hand -- regenerated by `scripts/update-openapi.sh`.*
133 endpoints, 207 operations.
155 endpoints, 240 operations.
## Artists
@@ -109,6 +109,20 @@
| GET | `/api/decos/{id}` | GetDecoById | Get a deco by id |
| PUT | `/api/decos/{id}` | | Replace a deco |
## Emby
| Method | Path | Operation | Summary |
|---|---|---|---|
| GET | `/api/media-sources/emby` | GetEmbyState | Get Emby connection state and discovered servers |
| GET | `/api/media-sources/emby/connection` | GetEmbyConnection | Get the Emby connection address |
| PUT | `/api/media-sources/emby/connection` | SaveEmbyConnection | Connect, reconnect, or edit the Emby connection |
| POST | `/api/media-sources/emby/disconnect` | DisconnectEmby | Disconnect Emby |
| GET | `/api/media-sources/emby/{id}/libraries` | GetEmbyLibraries | Get an Emby source's libraries |
| PUT | `/api/media-sources/emby/{id}/libraries` | ReplaceEmbyLibraryPreferences | Replace an Emby source's library sync preferences |
| GET | `/api/media-sources/emby/{id}/path-replacements` | GetEmbyPathReplacements | Get an Emby source's path replacements |
| PUT | `/api/media-sources/emby/{id}/path-replacements` | ReplaceEmbyPathReplacements | Replace an Emby source's path replacements |
| POST | `/api/media-sources/emby/{id}/refresh-libraries` | RefreshEmbyLibraries | Refresh an Emby source's libraries |
## FFmpeg Profiles
| Method | Path | Operation | Summary |
@@ -149,6 +163,20 @@
| GET | `/api/images/folders` | GetImageFolders | List image library folders |
| PUT | `/api/images/folders/{id}/duration` | UpdateImageFolderDuration | Set or clear an image folder's playout duration |
## Jellyfin
| Method | Path | Operation | Summary |
|---|---|---|---|
| GET | `/api/media-sources/jellyfin` | GetJellyfinState | Get Jellyfin connection state and discovered servers |
| GET | `/api/media-sources/jellyfin/connection` | GetJellyfinConnection | Get the Jellyfin connection address |
| PUT | `/api/media-sources/jellyfin/connection` | SaveJellyfinConnection | Connect, reconnect, or edit the Jellyfin connection |
| POST | `/api/media-sources/jellyfin/disconnect` | DisconnectJellyfin | Disconnect Jellyfin |
| GET | `/api/media-sources/jellyfin/{id}/libraries` | GetJellyfinLibraries | Get a Jellyfin source's libraries |
| PUT | `/api/media-sources/jellyfin/{id}/libraries` | ReplaceJellyfinLibraryPreferences | Replace a Jellyfin source's library sync preferences |
| GET | `/api/media-sources/jellyfin/{id}/path-replacements` | GetJellyfinPathReplacements | Get a Jellyfin source's path replacements |
| PUT | `/api/media-sources/jellyfin/{id}/path-replacements` | ReplaceJellyfinPathReplacements | Replace a Jellyfin source's path replacements |
| POST | `/api/media-sources/jellyfin/{id}/refresh-libraries` | RefreshJellyfinLibraries | Refresh a Jellyfin source's libraries |
## Languages
| Method | Path | Operation | Summary |
@@ -159,6 +187,13 @@
| Method | Path | Operation | Summary |
|---|---|---|---|
| GET | `/api/libraries/local` | GetLocalLibraries | Get all local libraries |
| POST | `/api/libraries/local` | | Create a local library |
| POST | `/api/libraries/local/path-exists` | | Check whether a filesystem path exists |
| POST | `/api/libraries/local/paths/{pathId}/move` | | Move a local library path to another local library |
| DELETE | `/api/libraries/local/{id}` | | Delete a local library |
| GET | `/api/libraries/local/{id}` | GetLocalLibrary | Get a local library by id |
| PUT | `/api/libraries/local/{id}` | | Update a local library |
| GET | `/api/libraries/scan-status` | GetLibraryScanStatus | Get active library scan status |
| POST | `/api/libraries/{id}/scan` | | Scan library |
| POST | `/api/libraries/{id}/scan-show` | | Scan show |
@@ -248,6 +283,19 @@
| GET | `/api/playouts/{id}/templates` | GetPlayoutTemplates | Get a block playout's templates |
| PUT | `/api/playouts/{id}/templates` | | Replace a block playout's templates |
## Plex
| Method | Path | Operation | Summary |
|---|---|---|---|
| GET | `/api/media-sources/plex` | GetPlexState | Get Plex connection state |
| POST | `/api/media-sources/plex/pin-flow` | StartPlexPinFlow | Start the Plex sign-in pin flow |
| POST | `/api/media-sources/plex/sign-out` | SignOutOfPlex | Sign out of Plex |
| GET | `/api/media-sources/plex/{id}/libraries` | GetPlexLibraries | Get a Plex server's libraries |
| PUT | `/api/media-sources/plex/{id}/libraries` | ReplacePlexLibraryPreferences | Replace a Plex server's library sync preferences |
| GET | `/api/media-sources/plex/{id}/path-replacements` | GetPlexPathReplacements | Get a Plex server's path replacements |
| PUT | `/api/media-sources/plex/{id}/path-replacements` | ReplacePlexPathReplacements | Replace a Plex server's path replacements |
| POST | `/api/media-sources/plex/{id}/refresh-libraries` | RefreshPlexLibraries | Refresh a Plex server's libraries |
## Rerun Collections
| Method | Path | Operation | Summary |
+47 -4
View File
@@ -42,6 +42,13 @@ Exemplars of screens that already do this correctly: `BlocksScreen.tsx`, `Templa
(which owns two sibling sub-paths, `/playouts/{id}/alternate-schedules` and
`/playouts/{id}/templates`, dispatching internally via `parsePlayoutSubRoute`).
**Exception — a guarded sub-path route defers pathname ownership to App.** When a sub-path route's
screens ALSO register a dirty guard (§8), the wrapper must **not** self-listen for `popstate`; App
owns the pathname and passes the approved sub-path down as a prop. The `LibrariesRouteScreen` wrapper
in `App.tsx` is the exemplar (sub-path parsed by `parseLibrariesSubRoute`, dispatched via a flat
`switch`, sub-path supplied by App's `librariesSubPath` state). See §8 for why child-before-parent
effect order makes the self-listening pattern unsafe here.
## 3. Data loading pattern
Reference implementation: `web/src/screens/LogsScreen.tsx`. Structure to copy for any screen that
@@ -126,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
@@ -229,10 +257,25 @@ draft to navigation. The shared module `web/src/navigationGuard.ts` is the seam:
`activeRoute` untouched, effectively undoing the browser's URL change. This same handler also runs
for the **synthetic** pop `navigateToPath()` dispatches, so programmatic in-app navigation is
guarded as well. The re-push does **not** re-fire `popstate`; that's safe because only one screen
is mounted at a time and the guard-registering screen (the schedules editor) owns no internal
`popstate`/sub-path listener — so a blocked pop cannot desync a sub-path screen's own pathname
state (§2). A sub-path screen that both registers a dirty guard *and* tracks its own pathname would
need to re-validate this; none does today.
is mounted at a time.
- **Guarded sub-path routes: App owns pathname/popstate (resolves the old §2 caveat).** A sub-path
wrapper that BOTH tracks its own pathname (§2) AND whose sub-screens register a dirty guard cannot
self-listen for `popstate`: React commits **child** passive effects before the **parent**, so a
wrapper-owned `popstate` listener fires *before* App's guard-restore handler and would switch
sub-screen before App could veto and re-push — desyncing the two. **Resolution (design #202 §D.2,
finding 4):** App is the single `popstate` owner. On a pop it consults `canLeaveCurrentScreen()`,
and **only on approval** does it update a `currentSubPath` state value (`librariesSubPath`) that it
passes **down** into the wrapper; on a veto it re-pushes the pre-pop path and updates nothing, so
the wrapper never sees a vetoed path. The wrapper (`LibrariesRouteScreen`) derives its sub-path
purely from that prop — never from the raw event — so effect-commit order is irrelevant. **Scope
the state write to the guarded route only:** the `setLibrariesSubPath` call is gated on the arrived
route being `libraries`, so unguarded sub-path routes (Playouts/Media) skip it entirely and stay
byte-identical (they still bail App's `setActiveRoute` via `Object.is` and self-own their pathname
per §2). The regression test is the App-owned-popstate case in `App.test.tsx` (dirty editor at
`/app/libraries/local/3`: `confirm→false` keeps URL + mounted sub-screen; `confirm→true`
navigates). Unguarded sub-path screens (`PlayoutsRouteScreen`, `MediaRouteScreen`) keep
self-owning their pathname — only screens that register a dirty guard defer to App.
- The screen **also** guards the paths the module still can't see — an in-screen action that would
replace the draft (schedule switch, opening the properties editor) uses its own
`window.confirm(...)`, and a `beforeunload` listener (installed while `dirty`) covers full-page