From 90dc864ce5e71ed89118d07bbde7d4411eee16a2 Mon Sep 17 00:00:00 2001 From: Timothy Date: Sun, 19 Jul 2026 21:05:56 +0200 Subject: [PATCH] fix(473): probe media-server remote streams before handing the URL to ffmpeg Tuning a channel intermittently hard-failed with ffmpeg exit 8 and `Server returned 404 Not Found` on /media/jellyfin/{itemId}. Root cause: ValidatePlayoutItemPath checked `File.Exists` on the local branch, but the three media-server 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" and ffmpeg was launched against a URL that 404s. That bypassed the good error path the handler already had (PlayoutItemDoesNotExistOnDisk renders an error card sized to run until the NEXT playout item, so 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). Restore the method's own invariant: every PlayoutItemWithPath it returns has been checked for existence. A definitive 404 now returns the new PlayoutItemNotAvailableFromMediaServer error, handled in the same switch arm as PlayoutItemDoesNotExistOnDisk. The probe is deliberately fail-open: only a 404 reports the media gone. A timeout, 5xx, auth error or transport failure reports available, so a probe that cannot answer can never break a tune that would have worked. That contract is pinned by tests so a later refactor cannot invert it. Rejected alternatives (see docs/decisions.md): resizing the HlsSessionWorker retry loop (cannot distinguish a dead item from a transient transcoder failure -- prod has live VAAPI hwupload -22 failures that must keep retrying), and writing MediaItemState from the streaming path (breaks scanner ownership, and would not have fixed this: the item is RemoteOnly, which PlayoutBuilder's skip does not exclude). Scanner-side follow-ups filed separately: #476 (FileNotFound does not cascade show -> episodes, the reason dead items keep being scheduled), fixes #473 Co-Authored-By: Claude Opus 4.8 (1M context) --- ...layoutItemProcessByChannelNumberHandler.cs | 40 ++- .../PlayoutItemNotAvailableFromMediaServer.cs | 9 + .../Streaming/IRemoteStreamProber.cs | 17 ++ .../Streaming/HttpRemoteStreamProberTests.cs | 117 +++++++++ .../Streaming/HttpRemoteStreamProber.cs | 55 ++++ ...tItemProcessByChannelNumberHandlerTests.cs | 244 ++++++++++++++++++ ErsatzTV/Startup.cs | 1 + docs/decisions.md | 39 +++ 8 files changed, 512 insertions(+), 10 deletions(-) create mode 100644 ErsatzTV.Core/Errors/PlayoutItemNotAvailableFromMediaServer.cs create mode 100644 ErsatzTV.Core/Interfaces/Streaming/IRemoteStreamProber.cs create mode 100644 ErsatzTV.Infrastructure.Tests/Streaming/HttpRemoteStreamProberTests.cs create mode 100644 ErsatzTV.Infrastructure/Streaming/HttpRemoteStreamProber.cs create mode 100644 ErsatzTV.Tests/Application/Streaming/GetPlayoutItemProcessByChannelNumberHandlerTests.cs diff --git a/ErsatzTV.Application/Streaming/Queries/GetPlayoutItemProcessByChannelNumberHandler.cs b/ErsatzTV.Application/Streaming/Queries/GetPlayoutItemProcessByChannelNumberHandler.cs index b6184f4f1..10cebdbc2 100644 --- a/ErsatzTV.Application/Streaming/Queries/GetPlayoutItemProcessByChannelNumberHandler.cs +++ b/ErsatzTV.Application/Streaming/Queries/GetPlayoutItemProcessByChannelNumberHandler.cs @@ -1,4 +1,4 @@ -using System.IO.Abstractions; +using System.IO.Abstractions; using CliWrap; using Dapper; using ErsatzTV.Application.Playouts; @@ -42,6 +42,7 @@ public class GetPlayoutItemProcessByChannelNumberHandler : FFmpegProcessHandler< private readonly IGraphicsElementSelector _graphicsElementSelector; private readonly IDecoSelector _decoSelector; private readonly IPlexPathReplacementService _plexPathReplacementService; + private readonly IRemoteStreamProber _remoteStreamProber; private readonly ISongVideoGenerator _songVideoGenerator; private readonly ITelevisionRepository _televisionRepository; private readonly bool _isDebugNoSync; @@ -62,9 +63,11 @@ public class GetPlayoutItemProcessByChannelNumberHandler : FFmpegProcessHandler< IWatermarkSelector watermarkSelector, IGraphicsElementSelector graphicsElementSelector, IDecoSelector decoSelector, + IRemoteStreamProber remoteStreamProber, ILogger logger) : base(dbContextFactory) { + _remoteStreamProber = remoteStreamProber; _ffmpegProcessService = ffmpegProcessService; _fileSystem = fileSystem; _externalJsonPlayoutItemProvider = externalJsonPlayoutItemProvider; @@ -549,6 +552,7 @@ public class GetPlayoutItemProcessByChannelNumberHandler : FFmpegProcessHandler< Optional(channel.PlayoutOffset), !request.HlsRealtime); case PlayoutItemDoesNotExistOnDisk: + case PlayoutItemNotAvailableFromMediaServer: Command doesNotExistProcess = await _ffmpegProcessService.ForError( ffmpegPath, channel, @@ -850,9 +854,15 @@ public class GetPlayoutItemProcessByChannelNumberHandler : FFmpegProcessHandler< pmf.Path, pmf.Key); - return new PlayoutItemWithPath( - playoutItem, - $"http://localhost:{Settings.StreamingPort}/media/plex/{plexMediaSourceId}/{pmf.Key}"); + var plexUrl = + $"http://localhost:{Settings.StreamingPort}/media/plex/{plexMediaSourceId}/{pmf.Key}"; + + if (!await _remoteStreamProber.IsAvailable(plexUrl, cancellationToken)) + { + return new PlayoutItemNotAvailableFromMediaServer(plexUrl); + } + + return new PlayoutItemWithPath(playoutItem, plexUrl); } break; @@ -868,9 +878,14 @@ public class GetPlayoutItemProcessByChannelNumberHandler : FFmpegProcessHandler< foreach (string itemId in jellyfinItemId) { - return new PlayoutItemWithPath( - playoutItem, - $"http://localhost:{Settings.StreamingPort}/media/jellyfin/{itemId}"); + var jellyfinUrl = $"http://localhost:{Settings.StreamingPort}/media/jellyfin/{itemId}"; + + if (!await _remoteStreamProber.IsAvailable(jellyfinUrl, cancellationToken)) + { + return new PlayoutItemNotAvailableFromMediaServer(jellyfinUrl); + } + + return new PlayoutItemWithPath(playoutItem, jellyfinUrl); } // attempt to remotely stream emby @@ -883,9 +898,14 @@ public class GetPlayoutItemProcessByChannelNumberHandler : FFmpegProcessHandler< foreach (string itemId in embyItemId) { - return new PlayoutItemWithPath( - playoutItem, - $"http://localhost:{Settings.StreamingPort}/media/emby/{itemId}"); + var embyUrl = $"http://localhost:{Settings.StreamingPort}/media/emby/{itemId}"; + + if (!await _remoteStreamProber.IsAvailable(embyUrl, cancellationToken)) + { + return new PlayoutItemNotAvailableFromMediaServer(embyUrl); + } + + return new PlayoutItemWithPath(playoutItem, embyUrl); } return new PlayoutItemDoesNotExistOnDisk(path); diff --git a/ErsatzTV.Core/Errors/PlayoutItemNotAvailableFromMediaServer.cs b/ErsatzTV.Core/Errors/PlayoutItemNotAvailableFromMediaServer.cs new file mode 100644 index 000000000..40021e11f --- /dev/null +++ b/ErsatzTV.Core/Errors/PlayoutItemNotAvailableFromMediaServer.cs @@ -0,0 +1,9 @@ +namespace ErsatzTV.Core.Errors; + +public class PlayoutItemNotAvailableFromMediaServer : BaseError +{ + public PlayoutItemNotAvailableFromMediaServer(string url) : base( + $"Playout item is not available from media server\n{url}") + { + } +} diff --git a/ErsatzTV.Core/Interfaces/Streaming/IRemoteStreamProber.cs b/ErsatzTV.Core/Interfaces/Streaming/IRemoteStreamProber.cs new file mode 100644 index 000000000..3ba2cb94e --- /dev/null +++ b/ErsatzTV.Core/Interfaces/Streaming/IRemoteStreamProber.cs @@ -0,0 +1,17 @@ +namespace ErsatzTV.Core.Interfaces.Streaming; + +/// +/// Checks whether a media-server remote-stream URL still resolves to playable media. +/// +public interface IRemoteStreamProber +{ + /// + /// Probes (following redirects, as ffmpeg would). + /// + /// + /// false only when the media is definitively gone (HTTP 404). Every other outcome — + /// any other status code, a timeout, or a transport failure — returns true so that a + /// probe problem can never prevent a tune that would otherwise have succeeded (fail-open). + /// + Task IsAvailable(string url, CancellationToken cancellationToken); +} diff --git a/ErsatzTV.Infrastructure.Tests/Streaming/HttpRemoteStreamProberTests.cs b/ErsatzTV.Infrastructure.Tests/Streaming/HttpRemoteStreamProberTests.cs new file mode 100644 index 000000000..49e769e79 --- /dev/null +++ b/ErsatzTV.Infrastructure.Tests/Streaming/HttpRemoteStreamProberTests.cs @@ -0,0 +1,117 @@ +using System.Net; +using ErsatzTV.Infrastructure.Streaming; +using Microsoft.Extensions.Logging; +using NSubstitute; +using NUnit.Framework; +using Shouldly; + +namespace ErsatzTV.Infrastructure.Tests.Streaming; + +[TestFixture] +public class HttpRemoteStreamProberTests +{ + private const string Url = "http://localhost:8409/media/jellyfin/abc123"; + + [Test] + public async Task Should_Report_Unavailable_On_404() + { + HttpRemoteStreamProber prober = ProberReturning(HttpStatusCode.NotFound); + + bool result = await prober.IsAvailable(Url, CancellationToken.None); + + result.ShouldBeFalse(); + } + + [TestCase(HttpStatusCode.OK)] + [TestCase(HttpStatusCode.PartialContent)] + [TestCase(HttpStatusCode.NoContent)] + public async Task Should_Report_Available_On_Success(HttpStatusCode statusCode) + { + HttpRemoteStreamProber prober = ProberReturning(statusCode); + + bool result = await prober.IsAvailable(Url, CancellationToken.None); + + result.ShouldBeTrue(); + } + + // the fail-open contract: a probe that cannot answer must never block a tune that would + // otherwise have worked. these cases exist so a future refactor can't silently invert it. + [TestCase(HttpStatusCode.InternalServerError)] + [TestCase(HttpStatusCode.BadGateway)] + [TestCase(HttpStatusCode.Unauthorized)] + [TestCase(HttpStatusCode.Forbidden)] + public async Task Should_Fail_Open_On_Other_Status_Codes(HttpStatusCode statusCode) + { + HttpRemoteStreamProber prober = ProberReturning(statusCode); + + bool result = await prober.IsAvailable(Url, CancellationToken.None); + + result.ShouldBeTrue(); + } + + [Test] + public async Task Should_Fail_Open_On_Transport_Failure() + { + var prober = new HttpRemoteStreamProber( + new StubHttpClientFactory(new ThrowingHttpMessageHandler(new HttpRequestException("no route to host"))), + Substitute.For>()); + + bool result = await prober.IsAvailable(Url, CancellationToken.None); + + result.ShouldBeTrue(); + } + + [Test] + public async Task Should_Fail_Open_On_Timeout() + { + var prober = new HttpRemoteStreamProber( + new StubHttpClientFactory(new ThrowingHttpMessageHandler(new TaskCanceledException("timed out"))), + Substitute.For>()); + + bool result = await prober.IsAvailable(Url, CancellationToken.None); + + result.ShouldBeTrue(); + } + + [Test] + public async Task Should_Fail_Open_When_Caller_Cancels() + { + HttpRemoteStreamProber prober = ProberReturning(HttpStatusCode.OK); + + using var cts = new CancellationTokenSource(); + await cts.CancelAsync(); + + bool result = await prober.IsAvailable(Url, cts.Token); + + result.ShouldBeTrue(); + } + + private static HttpRemoteStreamProber ProberReturning(HttpStatusCode statusCode) => + new( + new StubHttpClientFactory(new StatusCodeHttpMessageHandler(statusCode)), + Substitute.For>()); + + private sealed class StubHttpClientFactory(HttpMessageHandler handler) : IHttpClientFactory + { + public HttpClient CreateClient(string name) => new(handler, disposeHandler: false); + } + + private sealed class StatusCodeHttpMessageHandler(HttpStatusCode statusCode) : HttpMessageHandler + { + protected override Task SendAsync( + HttpRequestMessage request, + CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + return Task.FromResult(new HttpResponseMessage(statusCode)); + } + } + + private sealed class ThrowingHttpMessageHandler(Exception exception) : HttpMessageHandler + { + protected override Task SendAsync( + HttpRequestMessage request, + CancellationToken cancellationToken) => + Task.FromException(exception); + } +} diff --git a/ErsatzTV.Infrastructure/Streaming/HttpRemoteStreamProber.cs b/ErsatzTV.Infrastructure/Streaming/HttpRemoteStreamProber.cs new file mode 100644 index 000000000..6ef74ec0e --- /dev/null +++ b/ErsatzTV.Infrastructure/Streaming/HttpRemoteStreamProber.cs @@ -0,0 +1,55 @@ +using System.Net; +using ErsatzTV.Core.Interfaces.Streaming; +using Microsoft.Extensions.Logging; + +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) +/// +public class HttpRemoteStreamProber( + IHttpClientFactory httpClientFactory, + ILogger logger) : IRemoteStreamProber +{ + private static readonly TimeSpan ProbeTimeout = TimeSpan.FromSeconds(2); + + public async Task IsAvailable(string url, CancellationToken cancellationToken) + { + try + { + using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeoutCts.CancelAfter(ProbeTimeout); + + using var request = new HttpRequestMessage(HttpMethod.Get, url); + + // 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); + + using HttpClient client = httpClientFactory.CreateClient(); + using HttpResponseMessage response = await client.SendAsync( + request, + HttpCompletionOption.ResponseHeadersRead, + timeoutCts.Token); + + if (response.StatusCode is HttpStatusCode.NotFound) + { + logger.LogWarning("Media server reported 404 for remote stream {Url}", url); + return false; + } + + return true; + } + catch (Exception ex) + { + // fail open - a probe failure is not evidence that the media is gone + logger.LogDebug(ex, "Unable to probe remote stream {Url}; assuming it is available", url); + return true; + } + } +} diff --git a/ErsatzTV.Tests/Application/Streaming/GetPlayoutItemProcessByChannelNumberHandlerTests.cs b/ErsatzTV.Tests/Application/Streaming/GetPlayoutItemProcessByChannelNumberHandlerTests.cs new file mode 100644 index 000000000..7e25874e0 --- /dev/null +++ b/ErsatzTV.Tests/Application/Streaming/GetPlayoutItemProcessByChannelNumberHandlerTests.cs @@ -0,0 +1,244 @@ +using System.IO.Abstractions; +using CliWrap; +using ErsatzTV.Application.Streaming; +using ErsatzTV.Core; +using ErsatzTV.Core.Domain; +using ErsatzTV.Core.Interfaces.Emby; +using ErsatzTV.Core.Interfaces.FFmpeg; +using ErsatzTV.Core.Interfaces.Jellyfin; +using ErsatzTV.Core.Interfaces.Plex; +using ErsatzTV.Core.Interfaces.Repositories; +using ErsatzTV.Core.Interfaces.Streaming; +using ErsatzTV.FFmpeg; +using ErsatzTV.Infrastructure.Data; +using ErsatzTV.Tests.Support; +using LanguageExt; +using Microsoft.Extensions.Logging.Abstractions; +using NSubstitute; +using NSubstitute.Core; +using NSubstitute.Extensions; +using NUnit.Framework; +using Shouldly; +using DomainChannel = ErsatzTV.Core.Domain.Channel; + +namespace ErsatzTV.Tests.Application.Streaming; + +/// +/// ersatztv#473: a media-server item that is missing from disk used to fall back to the +/// remote-stream URL unconditionally. It must now be probed first, and an unavailable +/// remote stream must render an error card instead of a real playout process. +/// +[TestFixture] +public class GetPlayoutItemProcessByChannelNumberHandlerTests +{ + private const string ChannelNumber = "1"; + private const string JellyfinItemId = "abc123"; + + private readonly List _tempFiles = []; + private InMemoryTvContext _db = null!; + private IFFmpegProcessService _ffmpegProcessService = null!; + private IRemoteStreamProber _remoteStreamProber = null!; + + [SetUp] + public async Task SetUp() + { + _db = await InMemoryTvContext.CreateAsync(); + _remoteStreamProber = Substitute.For(); + + _ffmpegProcessService = Substitute.For(); + + // both ForError and ForPlayoutItem must hand back a real value; the handler dereferences them + _ffmpegProcessService.ReturnsForAll(Task.FromResult(Cli.Wrap("ffmpeg"))); + _ffmpegProcessService.ReturnsForAll( + Task.FromResult( + new PlayoutItemResult( + Cli.Wrap("ffmpeg"), + Option.None, + Option.None))); + } + + [TearDown] + public async Task TearDown() + { + await _db.DisposeAsync(); + foreach (string tempFile in _tempFiles) + { + if (File.Exists(tempFile)) + { + File.Delete(tempFile); + } + } + } + + [Test] + public async Task Should_Render_Error_Card_When_Remote_Stream_Is_Unavailable() + { + DateTimeOffset now = await SeedAll(); + _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/jellyfin/{JellyfinItemId}", Arg.Any()); + + CallsTo(nameof(IFFmpegProcessService.ForError)).Count.ShouldBe(1); + CallsTo(nameof(IFFmpegProcessService.ForPlayoutItem)).Count.ShouldBe(0); + } + + [Test] + public async Task Should_Stream_Remotely_When_Remote_Stream_Is_Available() + { + DateTimeOffset now = await SeedAll(); + _remoteStreamProber.IsAvailable(Arg.Any(), Arg.Any()).Returns(true); + + Either result = + await CreateHandler().Handle(Request(now), CancellationToken.None); + + result.IsRight.ShouldBeTrue(); + + CallsTo(nameof(IFFmpegProcessService.ForError)).Count.ShouldBe(0); + + List playoutCalls = CallsTo(nameof(IFFmpegProcessService.ForPlayoutItem)); + playoutCalls.Count.ShouldBe(1); + + // videoPath is the 7th parameter of ForPlayoutItem + object?[] arguments = playoutCalls[0].GetArguments(); + arguments[6].ShouldBe($"http://localhost:{Settings.StreamingPort}/media/jellyfin/{JellyfinItemId}"); + } + + private List CallsTo(string methodName) => + _ffmpegProcessService.ReceivedCalls() + .Where(c => c.GetMethodInfo().Name == methodName) + .ToList(); + + private static GetPlayoutItemProcessByChannelNumber Request(DateTimeOffset now) => + new( + ChannelNumber, + StreamingMode.TransportStream, + now, + StartAtZero: false, + HlsRealtime: true, + ChannelStart: now, + PtsOffset: TimeSpan.Zero, + TargetFramerate: Option.None, + IsTroubleshooting: false, + FFmpegProfileId: Option.None); + + private GetPlayoutItemProcessByChannelNumberHandler CreateHandler() + { + var fileSystem = Substitute.For(); + fileSystem.File.Exists(Arg.Any()).Returns(false); + + return new GetPlayoutItemProcessByChannelNumberHandler( + _db.Factory, + _ffmpegProcessService, + fileSystem, + Substitute.For(), + Substitute.For(), + Substitute.For(), + Substitute.For(), + Substitute.For(), + Substitute.For(), + Substitute.For(), + Substitute.For(), + Substitute.For(), + Substitute.For(), + Substitute.For(), + Substitute.For(), + _remoteStreamProber, + NullLogger.Instance); + } + + /// + /// Seeds ffmpeg/ffprobe config, an ffmpeg profile, a channel, a playout and a playout item + /// covering "now" whose media item is a jellyfin episode missing from disk. + /// + /// The "now" the request should use. + private async Task SeedAll() + { + string ffmpeg = Path.GetTempFileName(); + string ffprobe = Path.GetTempFileName(); + _tempFiles.Add(ffmpeg); + _tempFiles.Add(ffprobe); + + var now = new DateTimeOffset(2026, 1, 1, 12, 0, 0, TimeSpan.Zero); + + await using TvContext context = _db.CreateContext(); + + context.ConfigElements.Add(new ConfigElement { Key = ConfigElementKey.FFmpegPath.Key, Value = ffmpeg }); + context.ConfigElements.Add(new ConfigElement { Key = ConfigElementKey.FFprobePath.Key, Value = ffprobe }); + + var profile = new FFmpegProfile + { + Name = "Test", + Resolution = new Resolution { Name = "1080p", Width = 1920, Height = 1080 } + }; + context.FFmpegProfiles.Add(profile); + await context.SaveChangesAsync(); + + var channel = new DomainChannel(Guid.NewGuid()) + { + Number = ChannelNumber, + Name = "Test", + Group = "ErsatzTV", + Categories = string.Empty, + FFmpegProfileId = profile.Id, + StreamSelector = string.Empty, + PreferredAudioLanguageCode = string.Empty, + PreferredAudioTitle = string.Empty, + PreferredSubtitleLanguageCode = string.Empty, + MusicVideoCreditsTemplate = string.Empty, + StreamingMode = StreamingMode.TransportStream, + PlayoutSource = ChannelPlayoutSource.Generated, + PlayoutMode = ChannelPlayoutMode.Continuous + }; + 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 = [] + } + ] + }; + context.AddRange(episode); + await context.SaveChangesAsync(); + + var playout = new Playout + { + ChannelId = channel.Id, + ScheduleKind = PlayoutScheduleKind.Classic + }; + context.Playouts.Add(playout); + await context.SaveChangesAsync(); + + context.PlayoutItems.Add( + new PlayoutItem + { + PlayoutId = playout.Id, + MediaItemId = episode.Id, + Start = now.AddMinutes(-5).UtcDateTime, + Finish = now.AddMinutes(25).UtcDateTime, + InPoint = TimeSpan.FromMinutes(5), + OutPoint = TimeSpan.FromMinutes(30), + Watermarks = [], + PlayoutItemWatermarks = [], + GraphicsElements = [], + PlayoutItemGraphicsElements = [] + }); + await context.SaveChangesAsync(); + + return now; + } +} diff --git a/ErsatzTV/Startup.cs b/ErsatzTV/Startup.cs index c147544ca..a26e1fe5a 100644 --- a/ErsatzTV/Startup.cs +++ b/ErsatzTV/Startup.cs @@ -1084,6 +1084,7 @@ public class Startup services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/docs/decisions.md b/docs/decisions.md index 4e7ba3687..8a0cf6d1f 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -2081,3 +2081,42 @@ 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) + +`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. + +- **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. +- **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 + `hwupload -22` / exit 234), and retrying those is correct; converting them into whole-item blackouts is a + regression. The retry loop is deliberately left intact — it also remains the backstop for the probe's + TOCTOU window (media can vanish between a 200 probe and ffmpeg's own request). +- **Rejected — writing `MediaItemState` from the streaming path.** Only the scanner writes `State`, and + breaking that ownership wouldn't even have fixed this: the failing item is `RemoteOnly`, which + `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.