fix(473): review fixes — only a redirected 404 fails closed

Adversarial review of PR #479 found the stated fail-open contract was not
what the code measured, plus four smaller gaps. All fixed here as a
follow-up commit (no amend/force-push).

High — a 404 from ErsatzTV's OWN endpoint was treated as "media gone".
/media/{provider}/... is served by InternalController, which returns
NotFound when the media source is unconfigured or momentarily missing
(a media-source edit that deletes+reinserts connections, a restore, a
partially-configured server). Probing for "any 404" therefore failed
CLOSED for every item on that source -- exactly the case the fail-open
contract exists to prevent. A media-server 404 always arrives after a
redirect, so an un-redirected 404 is now treated as available.

Medium — the new switch label was untested and its benefit overstated.
maybeDuration/finish are computed before the switch, so `default:`
already sized the error card to the next playout item; the label only
changes the caption. The handler test asserted call counts only, so
deleting the label still passed. It now asserts the error message, and
removing the label fails the test (verified).

Medium — Plex/Emby branches changed but had no coverage. Added an Emby
handler test asserting the probe is called with the emby URL.

Low — caller cancellation was swallowed and pinned as desired behaviour.
A shutdown / client disconnect is a genuine signal, not a probe failure;
it now propagates, and only the probe's own 2s timeout fails open.

Low — the response stream was disposed unread, aborting the connection
instead of returning it to the pool. The one requested byte is drained.

Nit — fully-qualified RangeHeaderValue replaced with a using.

docs/decisions.md corrected where it overstated: the switch label's role,
the "fixes the class for all three media servers" claim (external-JSON
channels bypass ValidatePlayoutItemPath entirely -- filed as #480), and
the unmeasured latency assertion. Deferred HEAD-instead-of-GET recorded
with its reason rather than silently dropped.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-19 21:42:20 +02:00
co-authored by Claude Opus 4.8
parent 90dc864ce5
commit bad19f8d26
4 changed files with 169 additions and 55 deletions
@@ -13,15 +13,32 @@ public class HttpRemoteStreamProberTests
private const string Url = "http://localhost:8409/media/jellyfin/abc123";
[Test]
public async Task Should_Report_Unavailable_On_404()
public async Task Should_Report_Unavailable_On_404_From_The_Media_Server()
{
HttpRemoteStreamProber prober = ProberReturning(HttpStatusCode.NotFound);
// a media-server 404 arrives after our /media/... endpoint redirected, so the response's
// final request uri is the media server's, not the probe url
HttpRemoteStreamProber prober = ProberReturning(
HttpStatusCode.NotFound,
finalUri: "http://jellyfin:8096/Videos/abc123/stream?static=true");
bool result = await prober.IsAvailable(Url, CancellationToken.None);
result.ShouldBeFalse();
}
// ersatztv#473 review finding: our OWN /media/{provider}/... endpoint 404s when the media source
// is unconfigured or momentarily missing. Failing closed there would blank every item on that
// source, which is exactly what the fail-open contract exists to prevent.
[Test]
public async Task Should_Fail_Open_On_404_That_Was_Not_Redirected()
{
HttpRemoteStreamProber prober = ProberReturning(HttpStatusCode.NotFound, finalUri: Url);
bool result = await prober.IsAvailable(Url, CancellationToken.None);
result.ShouldBeTrue();
}
[TestCase(HttpStatusCode.OK)]
[TestCase(HttpStatusCode.PartialContent)]
[TestCase(HttpStatusCode.NoContent)]
@@ -73,22 +90,22 @@ public class HttpRemoteStreamProberTests
result.ShouldBeTrue();
}
// caller cancellation (shutdown / client disconnect) is a genuine signal, NOT a probe failure --
// swallowing it would let the handler go on building an ffmpeg command on a dead token.
[Test]
public async Task Should_Fail_Open_When_Caller_Cancels()
public async Task Should_Propagate_Caller_Cancellation()
{
HttpRemoteStreamProber prober = ProberReturning(HttpStatusCode.OK);
using var cts = new CancellationTokenSource();
await cts.CancelAsync();
bool result = await prober.IsAvailable(Url, cts.Token);
result.ShouldBeTrue();
await Should.ThrowAsync<OperationCanceledException>(() => prober.IsAvailable(Url, cts.Token));
}
private static HttpRemoteStreamProber ProberReturning(HttpStatusCode statusCode) =>
private static HttpRemoteStreamProber ProberReturning(HttpStatusCode statusCode, string finalUri = null) =>
new(
new StubHttpClientFactory(new StatusCodeHttpMessageHandler(statusCode)),
new StubHttpClientFactory(new StatusCodeHttpMessageHandler(statusCode, finalUri)),
Substitute.For<ILogger<HttpRemoteStreamProber>>());
private sealed class StubHttpClientFactory(HttpMessageHandler handler) : IHttpClientFactory
@@ -96,14 +113,23 @@ public class HttpRemoteStreamProberTests
public HttpClient CreateClient(string name) => new(handler, disposeHandler: false);
}
private sealed class StatusCodeHttpMessageHandler(HttpStatusCode statusCode) : HttpMessageHandler
private sealed class StatusCodeHttpMessageHandler(HttpStatusCode statusCode, string finalUri = null)
: HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return Task.FromResult(new HttpResponseMessage(statusCode));
// HttpClient rewrites RequestMessage.RequestUri to the final hop when it follows a
// redirect; finalUri lets a test stand in for "the media server answered this".
if (finalUri is not null)
{
request.RequestUri = new Uri(finalUri);
}
return Task.FromResult(new HttpResponseMessage(statusCode) { RequestMessage = request });
}
}
@@ -1,4 +1,5 @@
using System.Net;
using System.Net.Http.Headers;
using ErsatzTV.Core.Interfaces.Streaming;
using Microsoft.Extensions.Logging;
@@ -8,9 +9,11 @@ namespace ErsatzTV.Infrastructure.Streaming;
/// Probes a media-server remote-stream URL over HTTP.
/// </summary>
/// <remarks>
/// Deliberately fail-open: only a definitive HTTP 404 reports the media as gone. A probe that
/// times out, errors, or returns any other status must never turn a tune that would have worked
/// into an error card, so every other outcome reports available. (ersatztv#473)
/// Deliberately fail-open: the only outcome that reports the media as gone is a 404 that came
/// from the media server itself (i.e. arrived after our <c>/media/{provider}/...</c> endpoint
/// redirected). A timeout, a transport failure, any other status, or a 404 raised by ErsatzTV's
/// own endpoint all report available, so a probe that cannot answer never turns a tune that
/// would have worked into an error card. (ersatztv#473)
/// </remarks>
public class HttpRemoteStreamProber(
IHttpClientFactory httpClientFactory,
@@ -29,7 +32,7 @@ public class HttpRemoteStreamProber(
// ask for a single byte; media servers vary in their HEAD support, and this exercises the
// same redirect chain ffmpeg will follow
request.Headers.Range = new System.Net.Http.Headers.RangeHeaderValue(0, 0);
request.Headers.Range = new RangeHeaderValue(0, 0);
using HttpClient client = httpClientFactory.CreateClient();
using HttpResponseMessage response = await client.SendAsync(
@@ -39,12 +42,38 @@ public class HttpRemoteStreamProber(
if (response.StatusCode is HttpStatusCode.NotFound)
{
logger.LogWarning("Media server reported 404 for remote stream {Url}", url);
return false;
// only the MEDIA SERVER's 404 is evidence that the item is gone. our own
// /media/{provider}/... endpoint also returns 404 when the media source is
// unconfigured or momentarily missing (InternalController maps a failed
// connection-parameter lookup to NotFound), and treating that as "gone" would fail
// CLOSED for every item on that source. A media-server 404 always arrives after a
// redirect, so an un-redirected 404 came from us and must fail open.
if (WasRedirected(response, url))
{
logger.LogWarning("Media server reported 404 for remote stream {Url}", url);
return false;
}
logger.LogDebug(
"Probe of {Url} returned 404 without redirecting to a media server; assuming the "
+ "item is available rather than failing closed on our own endpoint",
url);
return true;
}
// drain the single byte we asked for so the connection goes back to the pool instead of
// being aborted when the unread response stream is disposed
await response.Content.ReadAsByteArrayAsync(timeoutCts.Token);
return true;
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
// the CALLER cancelled (shutdown / client disconnect). that is a genuine signal, not a
// probe failure, so it must propagate rather than be swallowed as fail-open.
throw;
}
catch (Exception ex)
{
// fail open - a probe failure is not evidence that the media is gone
@@ -52,4 +81,10 @@ public class HttpRemoteStreamProber(
return true;
}
}
private static bool WasRedirected(HttpResponseMessage response, string probeUrl)
{
Uri finalUri = response.RequestMessage?.RequestUri;
return finalUri is not null && !string.Equals(finalUri.ToString(), probeUrl, StringComparison.Ordinal);
}
}
@@ -33,6 +33,7 @@ public class GetPlayoutItemProcessByChannelNumberHandlerTests
{
private const string ChannelNumber = "1";
private const string JellyfinItemId = "abc123";
private const string EmbyItemId = "def456";
private readonly List<string> _tempFiles = [];
private InMemoryTvContext _db = null!;
@@ -84,8 +85,16 @@ public class GetPlayoutItemProcessByChannelNumberHandlerTests
await _remoteStreamProber.Received(1)
.IsAvailable($"http://localhost:{Settings.StreamingPort}/media/jellyfin/{JellyfinItemId}", Arg.Any<CancellationToken>());
CallsTo(nameof(IFFmpegProcessService.ForError)).Count.ShouldBe(1);
List<ICall> errorCalls = CallsTo(nameof(IFFmpegProcessService.ForError));
errorCalls.Count.ShouldBe(1);
CallsTo(nameof(IFFmpegProcessService.ForPlayoutItem)).Count.ShouldBe(0);
// the `case PlayoutItemNotAvailableFromMediaServer:` arm exists to surface the real error
// text; without it the error falls to `default:` and the card says "Channel is Offline".
// Assert the message, or the case label is untested dead weight.
object?[] arguments = errorCalls[0].GetArguments();
string errorMessage = arguments.OfType<string>().Single(a => a.Contains("not available"));
errorMessage.ShouldContain($"/media/jellyfin/{JellyfinItemId}");
}
[Test]
@@ -109,6 +118,28 @@ public class GetPlayoutItemProcessByChannelNumberHandlerTests
arguments[6].ShouldBe($"http://localhost:{Settings.StreamingPort}/media/jellyfin/{JellyfinItemId}");
}
// the fix changed all three remote-stream branches; Jellyfin above covers one, this pins that a
// second provider is probed too rather than the fix being Jellyfin-only (ersatztv#473 review)
[Test]
public async Task Should_Render_Error_Card_When_Emby_Remote_Stream_Is_Unavailable()
{
DateTimeOffset now = await SeedAll(emby: true);
_remoteStreamProber.IsAvailable(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(false);
Either<BaseError, PlayoutItemProcessModel> result =
await CreateHandler().Handle(Request(now), CancellationToken.None);
result.IsRight.ShouldBeTrue();
await _remoteStreamProber.Received(1)
.IsAvailable(
$"http://localhost:{Settings.StreamingPort}/media/emby/{EmbyItemId}",
Arg.Any<CancellationToken>());
CallsTo(nameof(IFFmpegProcessService.ForError)).Count.ShouldBe(1);
CallsTo(nameof(IFFmpegProcessService.ForPlayoutItem)).Count.ShouldBe(0);
}
private List<ICall> CallsTo(string methodName) =>
_ffmpegProcessService.ReceivedCalls()
.Where(c => c.GetMethodInfo().Name == methodName)
@@ -157,7 +188,7 @@ public class GetPlayoutItemProcessByChannelNumberHandlerTests
/// covering "now" whose media item is a jellyfin episode missing from disk.
/// </summary>
/// <returns>The "now" the request should use.</returns>
private async Task<DateTimeOffset> SeedAll()
private async Task<DateTimeOffset> SeedAll(bool emby = false)
{
string ffmpeg = Path.GetTempFileName();
string ffprobe = Path.GetTempFileName();
@@ -197,21 +228,23 @@ public class GetPlayoutItemProcessByChannelNumberHandlerTests
};
context.Channels.Add(channel);
var episode = new JellyfinEpisode
{
ItemId = JellyfinItemId,
EpisodeMetadata = [new EpisodeMetadata { Title = "Missing", SortTitle = "Missing", Subtitles = [] }],
MediaVersions =
[
new MediaVersion
{
Name = "Main",
Duration = TimeSpan.FromMinutes(30),
MediaFiles = [new MediaFile { Path = "/gone/episode.mkv", PathHash = "gone" }],
Streams = []
}
]
};
List<EpisodeMetadata> metadata =
[new EpisodeMetadata { Title = "Missing", SortTitle = "Missing", Subtitles = [] }];
List<MediaVersion> versions =
[
new MediaVersion
{
Name = "Main",
Duration = TimeSpan.FromMinutes(30),
MediaFiles = [new MediaFile { Path = "/gone/episode.mkv", PathHash = "gone" }],
Streams = []
}
];
Episode episode = emby
? new EmbyEpisode { ItemId = EmbyItemId, EpisodeMetadata = metadata, MediaVersions = versions }
: new JellyfinEpisode { ItemId = JellyfinItemId, EpisodeMetadata = metadata, MediaVersions = versions };
context.AddRange(episode);
await context.SaveChangesAsync();
+42 -22
View File
@@ -2081,30 +2081,48 @@ Disabling the servers is worth it (consistent reduction, no resident server), bu
off the live test-job peak-anon this instrument now reports, not off the build-only A/B. The older
#411 probe (`anon 7134 MiB`) read higher than these swap-off sampled numbers and is superseded
(swap/read-method move the figure >1 GiB).
## 2026-07-19 — Media-server remote-stream URLs are probed before use: 404 fails closed, everything else fails open, no toggle (#473)
## 2026-07-19 — Media-server remote-stream URLs are probed before use: a redirected 404 fails closed, everything else fails open, no toggle (#473)
`GetPlayoutItemProcessByChannelNumberHandler.ValidatePlayoutItemPath` now probes the Plex/Jellyfin/Emby
remote-stream URL via the new `IRemoteStreamProber` seam before returning it, and on a definitive HTTP
**404** returns the new `PlayoutItemNotAvailableFromMediaServer` error instead of a playable path.
remote-stream URL via the new `IRemoteStreamProber` seam before returning it, and on a 404 **from the media
server** returns the new `PlayoutItemNotAvailableFromMediaServer` error instead of a playable path.
- **The bug this closes.** The method's local branch checked `_fileSystem.File.Exists(path)`, but the
three remote-stream branches returned `http://localhost:{port}/media/{plex,jellyfin,emby}/{id}`
*unconditionally*. When the media was gone from the media server too, validation "succeeded", ffmpeg was
launched against a URL that 404s and died with **exit 8**. That bypassed the good error path the handler
already had (`PlayoutItemDoesNotExistOnDisk` → an error card sized to run until the **next** playout item,
i.e. the dead item is skipped) and instead landed in `HlsSessionWorker`'s generic ffmpeg-failure path,
which sizes its error card to the failed **44s work-ahead chunk** and then re-selects the *same* broken
item — a repeating error card for the item's whole slot (~22 min for an episode). Restoring the method's
own invariant — every `PlayoutItemWithPath` it returns has been checked for existence — fixes the class
for all three media servers, not just the reported Jellyfin instance.
- **404-only, fail-open on everything else.** A timeout, a 5xx, an auth error or a transport failure
returns *available*, so a probe that cannot answer can never turn a tune that would have worked into an
error card. This is the load-bearing property and is pinned by tests
(`HttpRemoteStreamProberTests.Should_Fail_Open_*`) precisely so a later refactor can't quietly invert it.
- **No `ConfigElement` toggle.** The behaviour strictly dominates the status quo (fail-open means it can
only ever convert an ffmpeg-404 into a better-labelled error card), and the cost is one LAN round trip
bounded by a 2s timeout — noise against the ~7s cold start that #350 is about. A toggle would be surface
for a switch nobody has a reason to flip.
launched against a URL that 404s and died with **exit 8** — landing in `HlsSessionWorker`'s generic
ffmpeg-failure path, which sizes its error card to the failed **44s work-ahead chunk** and then
re-selects the *same* broken item, so a dead item produces a repeating error card for its whole slot
(~22 min for an episode). The fix restores the method's own invariant — every `PlayoutItemWithPath` it
returns has been checked for existence — so the failure now returns an **error** rather than a playable
URL, and the handler's error path sizes the card to run until the **next** playout item.
- **What the new `case` label does and does not do** (a review corrected an earlier draft of this entry):
the skip-to-next-item sizing comes from `maybeDuration`/`finish`, computed *before* the switch — the
`default:` arm already had it. Adding `case PlayoutItemNotAvailableFromMediaServer:` alongside
`PlayoutItemDoesNotExistOnDisk` changes only the **caption** on the card (the real error text instead of
"Channel is Offline"). Worth having, but not where the fix lives. A handler test asserts that message
specifically, so the label cannot silently decay into dead weight.
- **Scope: the generated-playout path only.** All three remote branches of `ValidatePlayoutItemPath` are
covered. `ExternalJsonPlayoutItemProvider` builds its own `/media/plex/...` URL and its result is
assigned *without* passing through `ValidatePlayoutItemPath`, so external-JSON channels keep the old
behaviour — tracked as #480 rather than silently claimed as fixed. The troubleshooting and
subtitle-extraction paths build the same URLs and are deliberately **left unprobed**: troubleshooting
should surface the raw ffmpeg failure, and a subtitle-extraction miss is not a channel outage.
- **Fail-open on everything except a *redirected* 404.** A timeout, a 5xx, an auth error or a transport
failure returns *available* — and so does a **404 that arrived without a redirect**. ErsatzTV's own
`InternalController` returns `NotFound` when the media source is unconfigured or momentarily missing, so
honouring that would fail *closed* for every item on that source; the first draft probed for "any 404",
which made this contract untrue. Only a 404 reached *after* the redirect to the media server is evidence
the item is gone. Pinned by tests (`Should_Fail_Open_*`,
`Should_Fail_Open_On_404_That_Was_Not_Redirected`) so a later refactor can't quietly invert it. Caller
cancellation is **not** swallowed — it propagates, because a shutdown is a genuine signal, not a probe
failure.
- **No `ConfigElement` toggle.** The behaviour strictly dominates the status quo, and the probe is bounded
by a 2s linked-CTS timeout (not `HttpClient.Timeout`, which defaults to 100s). A toggle would be surface
for a switch nobody has a reason to flip. **Not yet measured:** on an install without path replacement
every item selection pays this probe, and a slow media server could cost up to the full 2s. That is a
worst case rather than a typical one, but it has not been measured against #350's cold-start budget —
measure before assuming it is noise.
- **Rejected — resizing the `HlsSessionWorker` retry loop to skip the item on any ffmpeg failure.** It buys
the viewer nothing the above doesn't (the slot is dead either way) and cannot distinguish "this item is
dead" from "this transcoder hiccupped". Prod shows real *transient* channel-wide failures (VAAPI
@@ -2116,7 +2134,9 @@ remote-stream URL via the new `IRemoteStreamProber` seam before returning it, an
`PlayoutBuilder`'s `PlayoutSkipMissingItems` skip does not exclude. On Jellyfin (`ServerSupportsRemoteStreaming`)
`RemoteOnly` is the *normal* state for every item when path replacement isn't configured, so it carries no
signal about playability — never key availability decisions off it.
- **Known consequence.** A removed/misconfigured media source makes `InternalController` return 404 itself,
so every item on it now probes 404 and renders an error card. Same viewer outcome as before (the tune was
failing anyway), better message — but worth knowing before reading "all my channels show error cards" as
a regression.
- **Deferred — HEAD instead of GET.** The probe sends `GET` with `Range: bytes=0-0`, which on
`/Videos/{id}/stream?static=true` is a real (if minimal) playback request and may register a session or
touch play-state on some media-server versions. `GET` was chosen because HEAD support varies across
media servers — that is a reasonable prior but an *unverified* one. A HEAD-with-GET-fallback would avoid
the side effect; deferred rather than guessed at, since it trades a known-working request for an
untested one.