diff --git a/ErsatzTV.Infrastructure.Tests/Streaming/HttpRemoteStreamProberTests.cs b/ErsatzTV.Infrastructure.Tests/Streaming/HttpRemoteStreamProberTests.cs index 49e769e79..0f1ab7f49 100644 --- a/ErsatzTV.Infrastructure.Tests/Streaming/HttpRemoteStreamProberTests.cs +++ b/ErsatzTV.Infrastructure.Tests/Streaming/HttpRemoteStreamProberTests.cs @@ -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(() => 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>()); 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 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 }); } } diff --git a/ErsatzTV.Infrastructure/Streaming/HttpRemoteStreamProber.cs b/ErsatzTV.Infrastructure/Streaming/HttpRemoteStreamProber.cs index 6ef74ec0e..ed4bd698a 100644 --- a/ErsatzTV.Infrastructure/Streaming/HttpRemoteStreamProber.cs +++ b/ErsatzTV.Infrastructure/Streaming/HttpRemoteStreamProber.cs @@ -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. /// /// -/// 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 /media/{provider}/... 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) /// 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); + } } diff --git a/ErsatzTV.Tests/Application/Streaming/GetPlayoutItemProcessByChannelNumberHandlerTests.cs b/ErsatzTV.Tests/Application/Streaming/GetPlayoutItemProcessByChannelNumberHandlerTests.cs index 7e25874e0..9c4598238 100644 --- a/ErsatzTV.Tests/Application/Streaming/GetPlayoutItemProcessByChannelNumberHandlerTests.cs +++ b/ErsatzTV.Tests/Application/Streaming/GetPlayoutItemProcessByChannelNumberHandlerTests.cs @@ -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 _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()); - CallsTo(nameof(IFFmpegProcessService.ForError)).Count.ShouldBe(1); + List 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().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(), Arg.Any()).Returns(false); + + Either 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()); + + CallsTo(nameof(IFFmpegProcessService.ForError)).Count.ShouldBe(1); + CallsTo(nameof(IFFmpegProcessService.ForPlayoutItem)).Count.ShouldBe(0); + } + private List 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. /// /// The "now" the request should use. - private async Task SeedAll() + private async Task 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 metadata = + [new EpisodeMetadata { Title = "Missing", SortTitle = "Missing", Subtitles = [] }]; + List 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(); diff --git a/docs/decisions.md b/docs/decisions.md index 8a0cf6d1f..5ea8707c8 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -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.