fix(agent): restart live relay when effective source changes (#355)
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 25m55s
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Successful in 25m39s
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Successful in 9m1s
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 1s

Handle primary and configured substream changes in the live relay.

Co-authored-by: Arnaud Dartois <admin@tordais.cc>
This commit was merged in pull request #356.
This commit is contained in:
arnaud.dartois authored and Arnaud Dartois committed 2026-11-13 02:16:04 +01:00
1 parent 561feb424c
commit 96d53b201f
4 files changed
+435 -43

No files matched your search

@@ -5,20 +5,85 @@ using Microsoft.Extensions.Options;
namespace Heimdall.Agent.Services;
/// <summary>Re-publishes assigned primary streams to the configured Central MediaMTX.</summary>
public sealed class LiveCameraRelayService(
AgentState state,
IOptions<AgentOptions> options,
CameraConfigStore cameras,
IHttpClientFactory clients,
ILogger<LiveCameraRelayService> logger) : BackgroundService
internal interface ILiveRelayProcess : IDisposable
{
bool HasExited { get; }
void KillEntireProcessTree();
Task WaitForExitAsync(TimeSpan timeout);
}
internal interface ILiveRelayProcessFactory
{
ILiveRelayProcess? Start(ProcessStartInfo startInfo);
}
internal sealed class LiveRelayProcessFactory : ILiveRelayProcessFactory
{
public ILiveRelayProcess? Start(ProcessStartInfo startInfo)
{
var process = Process.Start(startInfo);
if (process is null) return null;
_ = DrainErrorsAsync(process);
return new LiveRelayProcess(process);
}
private static async Task DrainErrorsAsync(Process process)
{
try { while (await process.StandardError.ReadLineAsync() is not null) { } }
catch (IOException) { }
}
private sealed class LiveRelayProcess(Process process) : ILiveRelayProcess
{
public bool HasExited => process.HasExited;
public void KillEntireProcessTree() => process.Kill(entireProcessTree: true);
public Task WaitForExitAsync(TimeSpan timeout) => process.WaitForExitAsync().WaitAsync(timeout);
public void Dispose() => process.Dispose();
}
}
/// <summary>Re-publishes assigned effective camera streams to the configured Central MediaMTX.</summary>
public sealed class LiveCameraRelayService : BackgroundService
{
private readonly AgentState _state;
private readonly IOptions<AgentOptions> _options;
private readonly CameraConfigStore _cameras;
private readonly IHttpClientFactory _clients;
private readonly ILiveRelayProcessFactory _processFactory;
private readonly TimeProvider _timeProvider;
private readonly ILogger<LiveCameraRelayService> _logger;
private const int MaxPublishers = 2;
private readonly Dictionary<Guid, Relay> _relays = [];
private readonly Dictionary<Guid, DateTimeOffset> _retryAt = [];
private sealed record Relay(Process Process, DateTimeOffset RenewAt);
private sealed record Relay(ILiveRelayProcess Process, DateTimeOffset RenewAt, string SourceUrl);
private sealed record PublishSession(string Url, DateTimeOffset RenewAt);
public LiveCameraRelayService(
AgentState state,
IOptions<AgentOptions> options,
CameraConfigStore cameras,
IHttpClientFactory clients,
ILogger<LiveCameraRelayService> logger)
: this(state, options, cameras, clients, new LiveRelayProcessFactory(), TimeProvider.System, logger) { }
internal LiveCameraRelayService(
AgentState state,
IOptions<AgentOptions> options,
CameraConfigStore cameras,
IHttpClientFactory clients,
ILiveRelayProcessFactory processFactory,
TimeProvider timeProvider,
ILogger<LiveCameraRelayService> logger)
{
_state = state;
_options = options;
_cameras = cameras;
_clients = clients;
_processFactory = processFactory;
_timeProvider = timeProvider;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
@@ -27,7 +92,7 @@ public sealed class LiveCameraRelayService(
{
try { await SynchronizeAsync(stoppingToken); }
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; }
catch (Exception ex) { logger.LogWarning("Live relay synchronization failed ({ErrorType})", ex.GetType().Name); }
catch (Exception ex) { _logger.LogWarning("Live relay synchronization failed ({ErrorType})", ex.GetType().Name); }
try { await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken); }
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; }
}
@@ -35,26 +100,27 @@ public sealed class LiveCameraRelayService(
finally { await StopAllAsync(); }
}
private async Task SynchronizeAsync(CancellationToken ct)
internal async Task SynchronizeAsync(CancellationToken ct)
{
var assigned = SelectAssignedCameras(cameras);
var assigned = SelectAssignedCameras(_cameras);
foreach (var id in _relays.Keys.Where(id => !assigned.ContainsKey(id)).ToArray())
await StopAsync(id);
foreach (var camera in assigned.Values)
{
if (_relays.TryGetValue(camera.CameraId, out var relay) && !relay.Process.HasExited &&
relay.RenewAt > DateTimeOffset.UtcNow) continue;
relay.RenewAt > _timeProvider.GetUtcNow() &&
string.Equals(relay.SourceUrl, camera.EffectiveRtspUrl, StringComparison.Ordinal)) continue;
await StopAsync(camera.CameraId);
if (state.AgentId == Guid.Empty || string.IsNullOrWhiteSpace(state.ApiKey) ||
_retryAt.GetValueOrDefault(camera.CameraId) > DateTimeOffset.UtcNow) continue;
if (!await StartAsync(camera, ct)) _retryAt[camera.CameraId] = DateTimeOffset.UtcNow.AddSeconds(20);
if (_state.AgentId == Guid.Empty || string.IsNullOrWhiteSpace(_state.ApiKey) ||
_retryAt.GetValueOrDefault(camera.CameraId) > _timeProvider.GetUtcNow()) continue;
if (!await StartAsync(camera, ct)) _retryAt[camera.CameraId] = _timeProvider.GetUtcNow().AddSeconds(20);
}
}
internal static IReadOnlyDictionary<Guid, AgentCameraConfig> SelectAssignedCameras(CameraConfigStore cameras) =>
cameras.HasCentralConfiguration
? cameras.Cameras.Where(c => c.Enabled && IsRtspSource(c.RtspUrl))
? cameras.Cameras.Where(c => c.Enabled && IsRtspSource(c.EffectiveRtspUrl))
.Take(MaxPublishers).ToDictionary(c => c.CameraId)
: new Dictionary<Guid, AgentCameraConfig>();
@@ -63,26 +129,26 @@ public sealed class LiveCameraRelayService(
private async Task<bool> StartAsync(AgentCameraConfig camera, CancellationToken ct)
{
var client = clients.CreateClient();
client.DefaultRequestHeaders.TryAddWithoutValidation("X-API-Key", state.ApiKey);
var client = _clients.CreateClient();
client.DefaultRequestHeaders.TryAddWithoutValidation("X-API-Key", _state.ApiKey);
using var response = await client.PostAsync(
$"{options.Value.CentralUrl.TrimEnd('/')}/api/live-media/agents/{state.AgentId:D}/cameras/{camera.CameraId:D}/publish-session",
$"{_options.Value.CentralUrl.TrimEnd('/')}/api/live-media/agents/{_state.AgentId:D}/cameras/{camera.CameraId:D}/publish-session",
content: null, ct);
if (!response.IsSuccessStatusCode) return false;
var session = await response.Content.ReadFromJsonAsync<PublishSession>(cancellationToken: ct);
if (session is null || !Uri.TryCreate(session.Url, UriKind.Absolute, out var destination)) return false;
var start = CreateStartInfo("ffmpeg", camera.RtspUrl, destination);
var sourceUrl = camera.EffectiveRtspUrl;
var start = CreateStartInfo("ffmpeg", sourceUrl, destination);
try
{
var process = Process.Start(start);
var process = _processFactory.Start(start);
if (process is null) return false;
_ = DrainErrorsAsync(process);
_relays[camera.CameraId] = new Relay(process, session.RenewAt.AddSeconds(-30));
logger.LogInformation("Live relay started for camera {CameraId}", camera.CameraId);
_relays[camera.CameraId] = new Relay(process, session.RenewAt.AddSeconds(-30), sourceUrl);
_logger.LogInformation("Live relay started for camera {CameraId}", camera.CameraId);
return true;
}
catch (Exception ex) { logger.LogWarning("Live relay failed for camera {CameraId} ({ErrorType})", camera.CameraId, ex.GetType().Name); return false; }
catch (Exception ex) { _logger.LogWarning("Live relay failed for camera {CameraId} ({ErrorType})", camera.CameraId, ex.GetType().Name); return false; }
}
internal static ProcessStartInfo CreateStartInfo(string ffmpegPath, string source, Uri destination)
@@ -95,26 +161,20 @@ public sealed class LiveCameraRelayService(
return start;
}
private static async Task DrainErrorsAsync(Process process)
{
try { while (await process.StandardError.ReadLineAsync() is not null) { } }
catch (IOException) { }
}
private async Task StopAsync(Guid cameraId)
{
if (!_relays.Remove(cameraId, out var relay)) return;
try
{
if (!relay.Process.HasExited) relay.Process.Kill(entireProcessTree: true);
await relay.Process.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(3));
if (!relay.Process.HasExited) relay.Process.KillEntireProcessTree();
await relay.Process.WaitForExitAsync(TimeSpan.FromSeconds(3));
}
catch (Exception ex) when (ex is InvalidOperationException or System.ComponentModel.Win32Exception or TimeoutException)
{ logger.LogDebug("Live relay cleanup for camera {CameraId} ended with {ErrorType}", cameraId, ex.GetType().Name); }
{ _logger.LogDebug("Live relay cleanup for camera {CameraId} ended with {ErrorType}", cameraId, ex.GetType().Name); }
finally { relay.Process.Dispose(); }
}
private async Task StopAllAsync()
internal async Task StopAllAsync()
{
foreach (var cameraId in _relays.Keys.ToArray()) await StopAsync(cameraId);
}