Files
ersatztv/ErsatzTV.Infrastructure/Streaming/HttpRemoteStreamProber.cs
T
timothyandClaude Opus 4.8 bad19f8d26 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>
2026-07-19 21:42:20 +02:00

91 lines
4.0 KiB
C#

using System.Net;
using System.Net.Http.Headers;
using ErsatzTV.Core.Interfaces.Streaming;
using Microsoft.Extensions.Logging;
namespace ErsatzTV.Infrastructure.Streaming;
/// <summary>
/// Probes a media-server remote-stream URL over HTTP.
/// </summary>
/// <remarks>
/// 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,
ILogger<HttpRemoteStreamProber> logger) : IRemoteStreamProber
{
private static readonly TimeSpan ProbeTimeout = TimeSpan.FromSeconds(2);
public async Task<bool> 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 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)
{
// 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
logger.LogDebug(ex, "Unable to probe remote stream {Url}; assuming it is available", url);
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);
}
}