Files

649 lines
27 KiB
C#
Raw Permalink Normal View History

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SignalR;
using System.Reflection;
using System.Text.Json;
using System.Net.Http.Json;
using Heimdall.Agent.Services;
using Heimdall.Application.DTOs;
using Heimdall.Application.Security;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NSubstitute;
namespace Heimdall.Agent.Tests;
public class ConfigReceiverServiceTests
{
private static ConfigReceiverService CreateService(
AgentState? state = null,
AgentCredentialStore? store = null,
RuntimeLogLevel? runtimeLogLevel = null,
IHttpClientFactory? httpFactory = null,
CameraConfigStore? cameraStore = null,
string centralUrl = "http://localhost:5000",
ILogger<ConfigReceiverService>? logger = null)
{
state ??= new AgentState { AgentId = Guid.Empty };
var options = Options.Create(new AgentOptions
{
CentralUrl = centralUrl,
SiteToken = "test"
});
logger ??= Substitute.For<ILogger<ConfigReceiverService>>();
httpFactory ??= Substitute.For<IHttpClientFactory>();
var scanTrigger = new DiscoveryScanTrigger();
runtimeLogLevel ??= CreateRuntimeLogLevel().Runtime;
2026-10-21 09:20:07 +02:00
var updateService = new AgentUpdateService(state, options, httpFactory,
Substitute.For<ILogger<AgentUpdateService>>(), new ContainerInfoProvider());
var dockerUpdateService = new DockerUpdateService(options, state, new ContainerInfoProvider(), httpFactory,
Substitute.For<ILogger<DockerUpdateService>>());
return new ConfigReceiverService(state, options, logger, httpFactory, scanTrigger, store ?? new AgentCredentialStore(),
runtimeLogLevel, cameraStore ?? new CameraConfigStore(),
new CameraStreamService(Substitute.For<ILogger<CameraStreamService>>()),
Substitute.For<IDetectionReporter>(), updateService, dockerUpdateService, new ContainerInfoProvider());
}
/// <summary>
/// Builds a RuntimeLogLevel sharing the exact LoggerFilterOptions instance
/// used by its LoggerFactory — mirrors the production DI wiring and makes
/// live log-level changes observable on existing loggers.
/// </summary>
private static (RuntimeLogLevel Runtime, ILoggerFactory Factory) CreateRuntimeLogLevel(List<string>? captured = null)
{
var services = new ServiceCollection();
services.AddLogging(builder =>
{
if (captured is not null)
builder.AddProvider(new ListLoggerProvider(captured));
});
var sp = services.BuildServiceProvider();
var factory = sp.GetRequiredService<ILoggerFactory>();
var options = sp.GetRequiredService<IOptions<LoggerFilterOptions>>();
return (new RuntimeLogLevel(factory, options), factory);
}
[Fact]
public async Task SignalRReconnect_Rejoins_AndReplacesCompleteCameraSnapshot()
{
var initialId = Guid.NewGuid();
var nextId = Guid.NewGuid();
IReadOnlyDictionary<string, string> config = new Dictionary<string, string>
{ [$"camera.{initialId}.rtsp"] = "rtsp://initial" };
var builder = WebApplication.CreateBuilder();
builder.WebHost.UseUrls("http://127.0.0.1:0");
builder.Logging.ClearProviders();
builder.Services.AddSignalR();
await using var app = builder.Build();
app.MapHub<ReconnectFixtureHub>("/hubs/config");
app.MapGet("/api/settings/agent/{id}", (HttpContext context) =>
{
var snapshot = Volatile.Read(ref config);
context.Response.Headers["X-Camera-Config-Version"] = CameraConfigVersion.Compute(snapshot);
return Results.Json(snapshot);
});
app.MapPost("/api/settings/agent/{id}/camera-config-ack", () => Results.NoContent());
await app.StartAsync();
var factory = Substitute.For<IHttpClientFactory>();
factory.CreateClient("Central").Returns(_ => new HttpClient());
var store = new CameraConfigStore();
using var receiver = CreateService(new AgentState { AgentId = Guid.NewGuid(), ApiKey = "fixture" },
httpFactory: factory, cameraStore: store, centralUrl: app.Urls.Single());
await receiver.StartAsync(CancellationToken.None);
try
{
await WaitForAsync(() => store.Cameras.Any(c => c.CameraId == initialId));
Volatile.Write(ref config, new Dictionary<string, string>
{ [$"camera.{nextId}.rtsp"] = "rtsp://next", [$"camera.{nextId}.enabled"] = "false" });
// Abort the HTTP transport without sending a SignalR close message.
ReconnectFixtureHub.AbortTransport!();
await WaitForAsync(() => store.Cameras.Count == 1 && store.Cameras[0].CameraId == nextId &&
ReconnectFixtureHub.JoinCount >= 2);
store.Cameras.Single().Enabled.ShouldBeFalse();
}
finally { await receiver.StopAsync(CancellationToken.None); }
}
private static async Task WaitForAsync(Func<bool> condition)
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(20));
while (!condition()) await Task.Delay(50, timeout.Token);
}
[Fact]
public void Sensitive_setting_values_are_never_logged_even_when_invalid_or_unknown()
{
var messages = new List<string>();
using var factory = LoggerFactory.Create(b => b.SetMinimumLevel(LogLevel.Trace).AddProvider(new ListLoggerProvider(messages)));
using var service = CreateService(logger: factory.CreateLogger<ConfigReceiverService>());
var apply = typeof(ConfigReceiverService).GetMethod("ApplySetting", BindingFlags.NonPublic | BindingFlags.Instance)!;
foreach (var key in new[] { "heartbeat.interval.seconds", "log.level", "autoUpdateEnabled", "unknown.setting", "model.api_key", "discovery.credentials" })
apply.Invoke(service, [key, "SENSITIVE_VALUE_SENTINEL"]);
messages.ShouldNotBeEmpty();
string.Join("\n", messages).ShouldNotContain("SENSITIVE_VALUE_SENTINEL");
}
[Fact]
public void Constructor_WithDependencies_DoesNotThrow()
{
var service = CreateService();
service.ShouldNotBeNull();
}
[Fact]
public async Task StartStop_WhenNotRegistered_StopsGracefully()
{
var state = new AgentState { AgentId = Guid.Empty };
var service = CreateService(state);
await service.StartAsync(CancellationToken.None);
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3));
await service.StopAsync(cts.Token);
}
[Fact]
public async Task StartStop_WhenRegistered_StopsGracefully()
{
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var service = CreateService(state);
await service.StartAsync(CancellationToken.None);
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await service.StopAsync(cts.Token);
}
[Fact]
public async Task StopAsync_WithoutStart_DoesNotThrow()
{
var service = CreateService();
await service.StopAsync(CancellationToken.None);
}
[Fact]
public async Task ExecuteAsync_CancelledWhileWaitingForAgentId_StopsGracefully()
{
var state = new AgentState { AgentId = Guid.Empty };
var service = CreateService(state);
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
await service.StartAsync(cts.Token);
await service.StopAsync(CancellationToken.None);
}
[Fact]
public async Task ExecuteAsync_ConnectionRetriesThenCancels_StopsGracefully()
{
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var service = CreateService(state);
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(2));
await service.StartAsync(cts.Token);
await service.StopAsync(CancellationToken.None);
}
[Fact]
public void ApplySetting_InvalidHeartbeatValue_DoesNotThrow()
{
var service = CreateService();
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
// Below minimum threshold (5)
Record.Exception(() => method.Invoke(service, ["heartbeat.interval.seconds", "3"]))
.ShouldBeNull();
// Non-numeric value
Record.Exception(() => method.Invoke(service, ["heartbeat.interval.seconds", "not-a-number"]))
.ShouldBeNull();
}
[Fact]
public void ApplySetting_KnownAndUnknownKeys_DoesNotThrow()
{
var service = CreateService();
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
Record.Exception(() => method.Invoke(service, ["log.level", "Debug"]))
.ShouldBeNull();
Record.Exception(() => method.Invoke(service, ["unknown.key", "some-value"]))
.ShouldBeNull();
}
[Fact]
public void ApplySetting_ValidHeartbeatInterval_DoesNotThrow()
{
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var service = CreateService(state);
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
Record.Exception(() => method.Invoke(service, ["heartbeat.interval.seconds", "30"]))
.ShouldBeNull();
// The setting is applied live to the shared state
state.HeartbeatIntervalSeconds.ShouldBe(30);
}
[Fact]
public void ApplySetting_ScanRequested_DoesNotThrow()
{
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var service = CreateService(state);
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
// Scan request is fire-and-forget (triggered via DiscoveryScanTrigger)
Record.Exception(() => method.Invoke(service, ["discovery.scan.requested", "1"]))
.ShouldBeNull();
}
[Fact]
public void ApplySetting_CredentialPool_DecryptsAndStores()
{
const string apiKey = "test-agent-api-key";
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = apiKey };
var store = new AgentCredentialStore();
var service = CreateService(state, store);
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
var key = AgentCredentialEnvelope.DeriveKeyFromApiKey(apiKey);
var envelope = AgentCredentialEnvelope.Encrypt(
[new AgentCameraCredential("admin", "admin", "secret")], key);
Record.Exception(() => method.Invoke(service, ["discovery.credentials", envelope]))
.ShouldBeNull();
store.Pool.Count.ShouldBe(1);
store.Pool[0].Label.ShouldBe("admin");
store.Pool[0].Password.ShouldBe("secret");
}
[Fact]
public void ApplySetting_CredentialPool_WrongKey_KeepsPreviousPool()
{
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "real-key" };
var store = new AgentCredentialStore();
store.Set([new AgentCameraCredential("old", "old", "old")]);
var service = CreateService(state, store);
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
// Envelope encrypted with a DIFFERENT key than the agent's API key.
var wrongKey = AgentCredentialEnvelope.DeriveKeyFromApiKey("other-key");
var envelope = AgentCredentialEnvelope.Encrypt(
[new AgentCameraCredential("new", "new", "new")], wrongKey);
Record.Exception(() => method.Invoke(service, ["discovery.credentials", envelope]))
.ShouldBeNull();
store.Pool.Count.ShouldBe(1);
store.Pool[0].Label.ShouldBe("old");
}
[Fact]
public void ApplySetting_InvalidHeartbeatInterval_DoesNotMutateState()
{
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var service = CreateService(state);
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
// Below minimum (5)
method.Invoke(service, ["heartbeat.interval.seconds", "3"]);
state.HeartbeatIntervalSeconds.ShouldBeNull();
// Above maximum (300)
method.Invoke(service, ["heartbeat.interval.seconds", "999"]);
state.HeartbeatIntervalSeconds.ShouldBeNull();
// Non-numeric
method.Invoke(service, ["heartbeat.interval.seconds", "abc"]);
state.HeartbeatIntervalSeconds.ShouldBeNull();
}
[Fact]
public void ApplySetting_LogLevel_AppliesLive()
{
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var runtime = CreateRuntimeLogLevel().Runtime;
var service = CreateService(state, runtimeLogLevel: runtime);
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
method.Invoke(service, ["log.level", "Warning"]);
// The setting is applied live to the shared runtime level (observable effect)
runtime.Level.ShouldBe(LogLevel.Warning);
}
[Fact]
public void ApplySetting_LogLevel_HasObservableEffectOnExistingLoggers()
{
var captured = new List<string>();
var (runtime, factory) = CreateRuntimeLogLevel(captured);
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var service = CreateService(state, runtimeLogLevel: runtime);
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
// A logger created BEFORE the change…
var logger = factory.CreateLogger("Heimdall.Agent.SomeService");
logger.IsEnabled(LogLevel.Information).ShouldBeTrue();
logger.LogInformation("before-change");
// …must re-filter immediately after a remote log.level change.
method.Invoke(service, ["log.level", "Warning"]);
logger.IsEnabled(LogLevel.Information).ShouldBeFalse();
logger.IsEnabled(LogLevel.Warning).ShouldBeTrue();
// The real log pipeline reflects the new minimum: Information is
// dropped, Warning passes through.
logger.LogInformation("after-change-info");
logger.LogWarning("after-change-warning");
captured.ShouldNotContain(m => m.Contains("after-change-info", StringComparison.Ordinal));
captured.ShouldContain(m => m.Contains("after-change-warning", StringComparison.Ordinal));
}
[Fact]
public void ApplySetting_LogLevel_CanBeLoweredAgain()
{
var captured = new List<string>();
var (runtime, factory) = CreateRuntimeLogLevel(captured);
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var service = CreateService(state, runtimeLogLevel: runtime);
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
var logger = factory.CreateLogger("Heimdall.Agent.SomeService");
method.Invoke(service, ["log.level", "Warning"]);
logger.IsEnabled(LogLevel.Information).ShouldBeFalse();
// Lowering back to Debug must not be blocked by a stale Warning rule
method.Invoke(service, ["log.level", "Debug"]);
logger.IsEnabled(LogLevel.Debug).ShouldBeTrue();
}
[Fact]
public void ApplySetting_LogLevel_InvalidValue_KeepsCurrentLevel()
{
var runtime = CreateRuntimeLogLevel().Runtime;
var service = CreateService(runtimeLogLevel: runtime);
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
method.Invoke(service, ["log.level", "NotALevel"]);
runtime.Level.ShouldBe(LogLevel.Information);
}
[Fact]
public void ApplySetting_RestartRequiredKey_LogsExplicitly()
{
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var service = CreateService(state);
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
Record.Exception(() => method.Invoke(service, ["ai.detection.enabled", "true"]))
.ShouldBeNull();
}
[Fact]
public async Task FetchFullConfigAsync_AppliesAllSettings()
{
const string apiKey = "test-agent-api-key";
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = apiKey };
var store = new AgentCredentialStore();
var runtime = CreateRuntimeLogLevel().Runtime;
var key = AgentCredentialEnvelope.DeriveKeyFromApiKey(apiKey);
var envelope = AgentCredentialEnvelope.Encrypt(
[new AgentCameraCredential("admin", "admin", "secret")], key);
var json = $$"""
{
"heartbeat.interval.seconds": "60",
"log.level": "Warning",
"ai.detection.enabled": "true",
"discovery.credentials": "{{envelope}}"
}
""";
var httpFactory = Substitute.For<IHttpClientFactory>();
httpFactory.CreateClient("Central").Returns(new HttpClient(new StubHttpMessageHandler(json)));
var service = CreateService(state, store, runtime, httpFactory);
var method = typeof(ConfigReceiverService).GetMethod("FetchFullConfigAsync",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
await (Task)method.Invoke(service, [CancellationToken.None])!;
// Heartbeat applied live from full reload
state.HeartbeatIntervalSeconds.ShouldBe(60);
// Log level applied live from full reload
runtime.Level.ShouldBe(LogLevel.Warning);
// Credential pool decrypted and stored from full reload
store.Pool.Count.ShouldBe(1);
store.Pool[0].Password.ShouldBe("secret");
}
[Fact]
public async Task FetchFullConfigAsync_AppliesCameraKeys_AndDropsLocalFallback()
{
const string apiKey = "test-agent-api-key";
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = apiKey };
var cameraStore = new CameraConfigStore();
cameraStore.SetLocalFallback(
[new AgentCameraConfig(Guid.NewGuid(), "Locale", "rtsp://local/stream", null, true)]);
var cameraId = Guid.NewGuid();
var json = $$"""
{
"camera.{{cameraId}}.name": "Entrée",
"camera.{{cameraId}}.rtsp": "rtsp://central/stream",
"camera.{{cameraId}}.enabled": "true"
}
""";
var httpFactory = Substitute.For<IHttpClientFactory>();
httpFactory.CreateClient("Central").Returns(new HttpClient(new StubHttpMessageHandler(json)));
var service = CreateService(state, httpFactory: httpFactory, cameraStore: cameraStore);
var method = typeof(ConfigReceiverService).GetMethod("FetchFullConfigAsync",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
await (Task)method.Invoke(service, [CancellationToken.None])!;
// Central camera list replaced the local fallback.
var camera = cameraStore.Cameras.ShouldHaveSingleItem();
camera.CameraId.ShouldBe(cameraId);
camera.Name.ShouldBe("Entrée");
camera.RtspUrl.ShouldBe("rtsp://central/stream");
camera.Enabled.ShouldBeTrue();
}
[Fact]
public async Task FetchFullConfigAsync_RetriesTransientAcknowledgementUntilCentralPersistsIt()
{
var cameraId = Guid.NewGuid();
var settings = new Dictionary<string, string> { [$"camera.{cameraId}.enabled"] = "true" };
var expectedVersion = CameraConfigVersion.Compute(settings);
var configFetches = 0;
var ackAttempts = 0;
var persistedAcks = 0;
var acknowledgedVersions = new List<string>();
var builder = WebApplication.CreateBuilder();
var fixturePort = int.TryParse(Environment.GetEnvironmentVariable("HEIMDALL_ACK_FIXTURE_PORT"), out var configuredPort) &&
configuredPort is > 0 and <= 65535 ? configuredPort : 0;
var fixtureBindHost = Environment.GetEnvironmentVariable("HEIMDALL_ACK_FIXTURE_BIND_HOST") ?? "127.0.0.1";
var fixtureApiKey = Environment.GetEnvironmentVariable("HEIMDALL_ACK_FIXTURE_API_KEY") ?? "fixture-key";
builder.WebHost.UseUrls($"http://{fixtureBindHost}:{fixturePort}");
builder.Logging.ClearProviders();
await using var central = builder.Build();
central.MapGet("/api/settings/agent/{id:guid}", (HttpContext context) =>
{
Interlocked.Increment(ref configFetches);
if (!string.Equals(context.Request.Headers["X-API-Key"], fixtureApiKey, StringComparison.Ordinal))
return Results.Unauthorized();
context.Response.Headers["X-Camera-Config-Version"] = expectedVersion;
return Results.Json(settings);
});
central.MapPost("/api/settings/agent/{id:guid}/camera-config-ack", async (HttpRequest request) =>
{
Interlocked.Increment(ref ackAttempts);
if (!string.Equals(request.Headers["X-API-Key"], fixtureApiKey, StringComparison.Ordinal))
return Results.Unauthorized();
var ack = await request.ReadFromJsonAsync<CameraConfigAckRequest>();
if (ack is null || !string.Equals(ack.Version, expectedVersion, StringComparison.Ordinal))
return Results.BadRequest();
acknowledgedVersions.Add(ack.Version);
if (ackAttempts == 1) return Results.StatusCode(StatusCodes.Status503ServiceUnavailable);
Interlocked.Increment(ref persistedAcks);
return Results.NoContent();
});
await central.StartAsync();
var factory = Substitute.For<IHttpClientFactory>();
factory.CreateClient("Central").Returns(_ => new HttpClient());
var cameraStore = new CameraConfigStore();
var configurationApplications = 0;
cameraStore.Changed += (_, _) => Interlocked.Increment(ref configurationApplications);
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = fixtureApiKey };
using var service = CreateService(state, httpFactory: factory, cameraStore: cameraStore,
centralUrl: fixturePort == 0 ? central.Urls.Single() : $"http://127.0.0.1:{fixturePort}");
var fetch = typeof(ConfigReceiverService).GetMethod("FetchFullConfigAsync",
BindingFlags.NonPublic | BindingFlags.Instance);
fetch.ShouldNotBeNull();
await (Task)fetch.Invoke(service, [CancellationToken.None])!;
configFetches.ShouldBe(1);
ackAttempts.ShouldBe(2);
persistedAcks.ShouldBe(1);
acknowledgedVersions.ShouldBe([expectedVersion, expectedVersion]);
configurationApplications.ShouldBe(1);
cameraStore.Cameras.ShouldHaveSingleItem().CameraId.ShouldBe(cameraId);
cameraStore.CurrentVersion.ShouldBe(expectedVersion);
}
[Fact]
public void ApplySetting_CameraKey_UpdatesCameraStore()
{
var cameraStore = new CameraConfigStore();
var service = CreateService(cameraStore: cameraStore);
var method = typeof(ConfigReceiverService).GetMethod("ApplySetting",
BindingFlags.NonPublic | BindingFlags.Instance);
method.ShouldNotBeNull();
var id = Guid.NewGuid();
method.Invoke(service, [$"camera.{id}.rtsp", "rtsp://live/stream"]);
method.Invoke(service, [$"camera.{id}.enabled", "false"]);
var camera = cameraStore.Cameras.ShouldHaveSingleItem();
camera.RtspUrl.ShouldBe("rtsp://live/stream");
camera.Enabled.ShouldBeFalse();
}
[Fact]
public async Task StartStop_MultipleTimes_DoesNotThrow()
{
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var service = CreateService(state);
// First start/stop cycle
await service.StartAsync(CancellationToken.None);
await service.StopAsync(CancellationToken.None);
// Second start/stop cycle
await service.StartAsync(CancellationToken.None);
await service.StopAsync(CancellationToken.None);
}
/// <summary>Returns the versioned Central config and accepts its acknowledgement.</summary>
private sealed class StubHttpMessageHandler : HttpMessageHandler
{
private readonly string _json;
public StubHttpMessageHandler(string json) => _json = json;
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.Method == HttpMethod.Post)
return Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.NoContent));
var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK)
{
Content = new StringContent(_json, System.Text.Encoding.UTF8, "application/json")
};
var settings = JsonSerializer.Deserialize<Dictionary<string, string>>(_json)!;
response.Headers.Add("X-Camera-Config-Version", CameraConfigVersion.Compute(settings));
return Task.FromResult(response);
}
}
private sealed record CameraConfigAckRequest(string Version);
/// <summary>Captures formatted log messages for assertions (in-memory, no sinks).</summary>
private sealed class ListLoggerProvider : ILoggerProvider
{
private readonly List<string> _captured;
public ListLoggerProvider(List<string> captured) => _captured = captured;
public ILogger CreateLogger(string categoryName) => new ListLogger(_captured);
public void Dispose() { }
private sealed class ListLogger : ILogger
{
private readonly List<string> _captured;
public ListLogger(List<string> captured) => _captured = captured;
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(
LogLevel logLevel,
EventId eventId,
TState state,
Exception? exception,
Func<TState, Exception?, string> formatter)
{
_captured.Add(formatter(state, exception));
}
}
}
}
public sealed class ReconnectFixtureHub : Hub
{
public static Action? AbortTransport { get; private set; }
private static int _joinCount;
public static int JoinCount => Volatile.Read(ref _joinCount);
public Task JoinAgentGroup(string agentId)
{
Interlocked.Increment(ref _joinCount);
AbortTransport = Context.GetHttpContext()!.Abort;
return Groups.AddToGroupAsync(Context.ConnectionId, $"agent_{agentId}");
}
}