diff --git a/skills/webrtc-live/SKILL.md b/skills/webrtc-live/SKILL.md
index 2d78318..7b50df9 100644
--- a/skills/webrtc-live/SKILL.md
+++ b/skills/webrtc-live/SKILL.md
@@ -32,15 +32,22 @@ and external network behavior is measured.
FFmpeg process count, and session lifetime. Ensure cancellation/config changes
reap child processes and release permits.
-## Current configuration-change limitation
+## Source-change lifecycle acceptance
-`LiveCameraRelayService` currently tracks a running relay by CameraId and its
-renewal time; it does not compare the source URL used to start FFmpeg with a new
-configuration for the same camera. Such a source change may keep publishing the
-old input until the renewal boundary (about 7.5 minutes with the current ticket
-lifetime). This is a known Agent defect tracked in Gitea issue #355, not the
-expected architecture. Do not claim immediate source-change handling until that
-issue's acceptance evidence is complete.
+`LiveCameraRelayService` compares the effective RTSP source configured for each
+camera (substream when configured, otherwise primary stream) with the source attached to its running FFmpeg relay. If the source
+changes while the CameraId remains assigned and enabled, synchronization stops
+and disposes the old process before starting a relay with the updated source.
+The normal synchronization interval is five seconds.
+
+Run `bash skills/webrtc-live/source-change-acceptance.sh` for the focused
+disposable Compose acceptance. It packages tracked and non-ignored source into
+an isolated .NET 10 SDK container and runs the Agent relay tests, including the
+same-CameraId primary and substream source changes, unchanged-source stability, renewal-boundary,
+child-process stop, and log-redaction assertions. It publishes no host ports,
+uses no persistent volumes or deployment credentials, builds no local image,
+and keeps only the upstream SDK image. The EXIT trap tears down the unique
+Compose project and verifies its containers, volumes, and network are absent.
## Implementation references
diff --git a/skills/webrtc-live/source-change-acceptance.sh b/skills/webrtc-live/source-change-acceptance.sh
new file mode 100755
index 0000000..7874051
--- /dev/null
+++ b/skills/webrtc-live/source-change-acceptance.sh
@@ -0,0 +1,76 @@
+#!/usr/bin/env bash
+set -Eeuo pipefail
+
+repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
+suffix="$(date -u +%Y%m%d%H%M%S)-$(od -An -N4 -tx1 /dev/urandom | tr -d ' \n')"
+project="heimdall-live-source-change-${suffix}"
+temp_dir="$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")"
+compose_file="${temp_dir}/compose.json"
+source_archive="${temp_dir}/source.tar"
+local_image_tags=()
+
+if ! command -v docker >/dev/null 2>&1 || ! docker compose version >/dev/null 2>&1; then
+ printf 'Docker Compose is required for live source-change acceptance.\n' >&2
+ rmdir -- "$temp_dir"
+ exit 2
+fi
+
+cleanup() {
+ status=$?
+ trap - EXIT
+ cleanup_failed=0
+ if [[ -f "$compose_file" ]]; then
+ docker compose -p "$project" -f "$compose_file" down --volumes --remove-orphans >/dev/null 2>&1 || cleanup_failed=1
+ fi
+ containers="$(docker ps -aq --filter "label=com.docker.compose.project=${project}")" || cleanup_failed=1
+ volumes="$(docker volume ls -q --filter "label=com.docker.compose.project=${project}")" || cleanup_failed=1
+ networks="$(docker network ls -q --filter "label=com.docker.compose.project=${project}")" || cleanup_failed=1
+ [[ -z "$containers" && -z "$volumes" && -z "$networks" ]] || cleanup_failed=1
+ for tag in "${local_image_tags[@]}"; do
+ docker image rm "$tag" >/dev/null 2>&1 || true
+ docker image inspect "$tag" >/dev/null 2>&1 && cleanup_failed=1
+ done
+ rm -f -- "$compose_file" "$source_archive" || cleanup_failed=1
+ rmdir -- "$temp_dir" || cleanup_failed=1
+ if (( cleanup_failed )); then
+ printf 'Disposable acceptance cleanup failed for project %s\n' "$project" >&2
+ status=1
+ fi
+ exit "$status"
+}
+trap cleanup EXIT
+
+python3 - "$compose_file" "$source_archive" <<'PY'
+import json
+import sys
+
+compose_path, archive_path = sys.argv[1:]
+test_command = """set -euo pipefail
+mkdir -p /tmp/heimdall-source
+tar -xf /source.tar -C /tmp/heimdall-source
+cd /tmp/heimdall-source
+dotnet restore tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --locked-mode
+dotnet test tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --no-restore --configuration Release -m:1 --filter FullyQualifiedName~LiveCameraRelayServiceTests
+"""
+document = {
+ "services": {
+ "source-change-tests": {
+ "image": "mcr.microsoft.com/dotnet/sdk:10.0",
+ "entrypoint": ["bash", "-euc"],
+ "command": [test_command],
+ "volumes": [f"{archive_path}:/source.tar:ro"],
+ }
+ }
+}
+with open(compose_path, "w", encoding="utf-8") as compose_file:
+ json.dump(document, compose_file)
+PY
+
+# Archive only tracked and non-ignored working files; exclude multi-gigabyte
+# ignored build/model outputs from the disposable SDK container.
+git -C "$repo_root" ls-files -z --cached --others --exclude-standard |
+ tar -C "$repo_root" --null -T - -cf "$source_archive"
+
+printf 'Project: %s\n' "$project"
+printf 'Local images built: none (upstream .NET SDK image only)\n'
+docker compose -p "$project" -f "$compose_file" up --abort-on-container-exit --exit-code-from source-change-tests
diff --git a/src/Heimdall.Agent/Services/LiveCameraRelayService.cs b/src/Heimdall.Agent/Services/LiveCameraRelayService.cs
index caaa120..c45ee17 100644
--- a/src/Heimdall.Agent/Services/LiveCameraRelayService.cs
+++ b/src/Heimdall.Agent/Services/LiveCameraRelayService.cs
@@ -5,20 +5,85 @@ using Microsoft.Extensions.Options;
namespace Heimdall.Agent.Services;
-/// Re-publishes assigned primary streams to the configured Central MediaMTX.
-public sealed class LiveCameraRelayService(
- AgentState state,
- IOptions options,
- CameraConfigStore cameras,
- IHttpClientFactory clients,
- ILogger 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();
+ }
+}
+
+/// Re-publishes assigned effective camera streams to the configured Central MediaMTX.
+public sealed class LiveCameraRelayService : BackgroundService
+{
+ private readonly AgentState _state;
+ private readonly IOptions _options;
+ private readonly CameraConfigStore _cameras;
+ private readonly IHttpClientFactory _clients;
+ private readonly ILiveRelayProcessFactory _processFactory;
+ private readonly TimeProvider _timeProvider;
+ private readonly ILogger _logger;
private const int MaxPublishers = 2;
private readonly Dictionary _relays = [];
private readonly Dictionary _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 options,
+ CameraConfigStore cameras,
+ IHttpClientFactory clients,
+ ILogger logger)
+ : this(state, options, cameras, clients, new LiveRelayProcessFactory(), TimeProvider.System, logger) { }
+
+ internal LiveCameraRelayService(
+ AgentState state,
+ IOptions options,
+ CameraConfigStore cameras,
+ IHttpClientFactory clients,
+ ILiveRelayProcessFactory processFactory,
+ TimeProvider timeProvider,
+ ILogger 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 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();
@@ -63,26 +129,26 @@ public sealed class LiveCameraRelayService(
private async Task 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(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);
}
diff --git a/tests/Heimdall.Agent.Tests/LiveCameraRelayServiceTests.cs b/tests/Heimdall.Agent.Tests/LiveCameraRelayServiceTests.cs
index 277ce00..67b969f 100644
--- a/tests/Heimdall.Agent.Tests/LiveCameraRelayServiceTests.cs
+++ b/tests/Heimdall.Agent.Tests/LiveCameraRelayServiceTests.cs
@@ -1,4 +1,9 @@
using Heimdall.Agent.Services;
+using System.Diagnostics;
+using System.Net;
+using System.Net.Http.Json;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Options;
namespace Heimdall.Agent.Tests;
@@ -48,6 +53,250 @@ public sealed class LiveCameraRelayServiceTests
Assert.DoesNotContain(invalidId, selected.Keys);
}
+ [Fact]
+ public async Task Synchronize_stops_and_restarts_relay_when_source_changes_for_same_camera()
+ {
+ var cameraId = Guid.NewGuid();
+ const string oldSource = "rtsp://camera-user:synthetic-secret@127.0.0.1:18554/old";
+ const string newSource = "rtsp://camera-user:synthetic-secret@127.0.0.1:18554/new";
+ var cameras = new CameraConfigStore();
+ SetCameraSource(cameras, cameraId, oldSource);
+ var processFactory = new FakeRelayProcessFactory();
+ var logMessages = new List();
+ using var loggerFactory = LoggerFactory.Create(builder => builder.AddProvider(new ListLoggerProvider(logMessages)));
+ var service = CreateService(cameras, processFactory, loggerFactory.CreateLogger());
+
+ await service.SynchronizeAsync(CancellationToken.None);
+ var first = Assert.Single(processFactory.Started);
+ Assert.False(first.Process.HasExited);
+ Assert.Equal(oldSource, InputSource(first.StartInfo));
+
+ await service.SynchronizeAsync(CancellationToken.None);
+ Assert.Single(processFactory.Started);
+ Assert.False(first.Process.HasExited);
+
+ SetCameraSource(cameras, cameraId, newSource);
+ await service.SynchronizeAsync(CancellationToken.None);
+
+ Assert.Equal(2, processFactory.Started.Count);
+ Assert.True(first.Process.HasExited);
+ Assert.True(first.Process.KilledEntireProcessTree);
+ Assert.True(first.Process.WaitedForExit);
+ Assert.True(first.Process.Disposed);
+ var second = processFactory.Started[1];
+ Assert.False(second.Process.HasExited);
+ Assert.Equal(newSource, InputSource(second.StartInfo));
+ var logs = string.Join('\n', logMessages);
+ Assert.DoesNotContain("synthetic-secret", logs, StringComparison.Ordinal);
+ Assert.DoesNotContain("synthetic-agent-key", logs, StringComparison.Ordinal);
+ Assert.DoesNotContain("synthetic-publish-token", logs, StringComparison.Ordinal);
+ Assert.DoesNotContain(oldSource, logs, StringComparison.Ordinal);
+ Assert.DoesNotContain(newSource, logs, StringComparison.Ordinal);
+
+ await service.StopAllAsync();
+ Assert.True(second.Process.HasExited);
+ }
+
+ [Fact]
+ public async Task Synchronize_stops_and_restarts_relay_when_substream_source_changes()
+ {
+ var cameraId = Guid.NewGuid();
+ const string primarySource = "rtsp://127.0.0.1:18554/primary";
+ const string oldSubSource = "rtsp://camera-user:synthetic-secret@127.0.0.1:18554/sub-old";
+ const string newSubSource = "rtsp://camera-user:synthetic-secret@127.0.0.1:18554/sub-new";
+ var cameras = new CameraConfigStore();
+ SetCameraSource(cameras, cameraId, primarySource, oldSubSource);
+ var processFactory = new FakeRelayProcessFactory();
+ using var loggerFactory = LoggerFactory.Create(_ => { });
+ var service = CreateService(cameras, processFactory, loggerFactory.CreateLogger());
+
+ await service.SynchronizeAsync(CancellationToken.None);
+ var first = Assert.Single(processFactory.Started);
+ Assert.Equal(oldSubSource, InputSource(first.StartInfo));
+
+ SetCameraSource(cameras, cameraId, primarySource, newSubSource);
+ await service.SynchronizeAsync(CancellationToken.None);
+
+ Assert.Equal(2, processFactory.Started.Count);
+ Assert.True(first.Process.HasExited);
+ Assert.True(first.Process.Disposed);
+ Assert.Equal(newSubSource, InputSource(processFactory.Started[1].StartInfo));
+ await service.StopAllAsync();
+ }
+
+ [Fact]
+ public async Task Process_factory_kills_and_waits_for_a_child_process()
+ {
+ var startInfo = new ProcessStartInfo
+ {
+ FileName = OperatingSystem.IsWindows() ? "cmd.exe" : "/bin/sh",
+ UseShellExecute = false,
+ RedirectStandardError = true,
+ CreateNoWindow = true
+ };
+ if (OperatingSystem.IsWindows())
+ {
+ startInfo.ArgumentList.Add("/c");
+ startInfo.ArgumentList.Add("ping -t 127.0.0.1");
+ }
+ else
+ {
+ startInfo.ArgumentList.Add("-c");
+ startInfo.ArgumentList.Add("exec sleep 30");
+ }
+
+ using var process = new LiveRelayProcessFactory().Start(startInfo);
+ Assert.NotNull(process);
+ try
+ {
+ Assert.False(process.HasExited);
+ process.KillEntireProcessTree();
+ await process.WaitForExitAsync(TimeSpan.FromSeconds(5));
+ Assert.True(process.HasExited);
+ }
+ finally
+ {
+ if (!process.HasExited)
+ {
+ process.KillEntireProcessTree();
+ await process.WaitForExitAsync(TimeSpan.FromSeconds(5));
+ }
+ }
+ }
+
+ [Fact]
+ public async Task Synchronize_keeps_unchanged_source_until_renewal_boundary()
+ {
+ var cameraId = Guid.NewGuid();
+ const string source = "rtsp://127.0.0.1:18554/stable";
+ var cameras = new CameraConfigStore();
+ SetCameraSource(cameras, cameraId, source);
+ var timeProvider = new ManualTimeProvider(DateTimeOffset.UtcNow);
+ var processFactory = new FakeRelayProcessFactory();
+ using var loggerFactory = LoggerFactory.Create(_ => { });
+ var service = CreateService(cameras, processFactory,
+ loggerFactory.CreateLogger(),
+ () => timeProvider.GetUtcNow().AddMinutes(8), timeProvider);
+
+ await service.SynchronizeAsync(CancellationToken.None);
+ var first = Assert.Single(processFactory.Started);
+ await service.SynchronizeAsync(CancellationToken.None);
+ Assert.Single(processFactory.Started);
+ Assert.False(first.Process.HasExited);
+
+ timeProvider.Advance(TimeSpan.FromMinutes(7.5));
+ await service.SynchronizeAsync(CancellationToken.None);
+
+ Assert.Equal(2, processFactory.Started.Count);
+ Assert.True(first.Process.HasExited);
+ Assert.False(processFactory.Started[1].Process.HasExited);
+ await service.StopAllAsync();
+ }
+
+ private static LiveCameraRelayService CreateService(
+ CameraConfigStore cameras,
+ ILiveRelayProcessFactory processFactory,
+ ILogger logger,
+ Func? renewAtProvider = null,
+ TimeProvider? timeProvider = null)
+ {
+ var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "synthetic-agent-key" };
+ var clients = new TestHttpClientFactory(() => new HttpResponseMessage(HttpStatusCode.OK)
+ {
+ Content = JsonContent.Create(new
+ {
+ url = "rtsps://media.invalid/camera?token=synthetic-publish-token",
+ renewAt = renewAtProvider?.Invoke() ?? DateTimeOffset.UtcNow.AddMinutes(8)
+ })
+ });
+ return new LiveCameraRelayService(state,
+ Options.Create(new AgentOptions { CentralUrl = "https://central.invalid" }),
+ cameras, clients, processFactory, timeProvider ?? TimeProvider.System, logger);
+ }
+
+ private sealed class ManualTimeProvider(DateTimeOffset current) : TimeProvider
+ {
+ private DateTimeOffset _current = current;
+ public override DateTimeOffset GetUtcNow() => _current;
+ public void Advance(TimeSpan duration) => _current = _current.Add(duration);
+ }
+
+ private static void SetCameraSource(CameraConfigStore store, Guid cameraId, string source, string? subSource = null)
+ {
+ var settings = new Dictionary
+ {
+ [$"camera.{cameraId}.rtsp"] = source,
+ [$"camera.{cameraId}.enabled"] = "true"
+ };
+ if (subSource is not null) settings[$"camera.{cameraId}.sub_rtsp"] = subSource;
+ store.ReplaceCentral(settings);
+ }
+
+ private static string InputSource(ProcessStartInfo startInfo)
+ {
+ var args = startInfo.ArgumentList.ToArray();
+ return args[Array.IndexOf(args, "-i") + 1];
+ }
+
+ private sealed class TestHttpClientFactory(Func responseFactory) : IHttpClientFactory
+ {
+ public HttpClient CreateClient(string name) => new(new TestHttpMessageHandler(responseFactory));
+ }
+
+ private sealed class TestHttpMessageHandler(Func responseFactory) : HttpMessageHandler
+ {
+ protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
+ Task.FromResult(responseFactory());
+ }
+
+ private sealed class FakeRelayProcessFactory : ILiveRelayProcessFactory
+ {
+ public List<(ProcessStartInfo StartInfo, FakeRelayProcess Process)> Started { get; } = [];
+
+ public ILiveRelayProcess Start(ProcessStartInfo startInfo)
+ {
+ var process = new FakeRelayProcess();
+ Started.Add((startInfo, process));
+ return process;
+ }
+ }
+
+ private sealed class FakeRelayProcess : ILiveRelayProcess
+ {
+ public bool HasExited { get; private set; }
+ public bool KilledEntireProcessTree { get; private set; }
+ public bool WaitedForExit { get; private set; }
+ public bool Disposed { get; private set; }
+
+ public void KillEntireProcessTree()
+ {
+ KilledEntireProcessTree = true;
+ HasExited = true;
+ }
+
+ public Task WaitForExitAsync(TimeSpan timeout)
+ {
+ WaitedForExit = true;
+ return Task.CompletedTask;
+ }
+
+ public void Dispose() => Disposed = true;
+ }
+
+ private sealed class ListLoggerProvider(List messages) : ILoggerProvider
+ {
+ public ILogger CreateLogger(string categoryName) => new ListLogger(messages);
+ public void Dispose() { }
+
+ private sealed class ListLogger(List messages) : ILogger
+ {
+ public IDisposable? BeginScope(TState state) where TState : notnull => null;
+ public bool IsEnabled(LogLevel logLevel) => true;
+ public void Log(LogLevel logLevel, EventId eventId, TState state,
+ Exception? exception, Func formatter) => messages.Add(formatter(state, exception));
+ }
+ }
+
private static string OptionValue(string[] args, string option, int occurrence = 0)
{
var indices = args.Select((arg, index) => (arg, index)).Where(item => item.arg == option)