feat(agent): mode analyse distant — frames vers broker avec fallback local (#158)

This commit is contained in:
Arnaud Dartois authored and Arnaud Dartois committed 2026-08-27 00:07:17 +02:00
1 parent 6eae4eea2f
commit 91bf33f794
11 files changed
+708 -35

No files matched your search

+1 -1
View File
@@ -7,7 +7,7 @@
<AnalysisLevel>latest-Recommended</AnalysisLevel> <AnalysisLevel>latest-Recommended</AnalysisLevel>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild> <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
<!-- NU1510: Channels is transitively pulled by SignalR but included in the framework - safe to suppress --> <!-- NU1510: Channels is transitively pulled by SignalR but included in the framework - safe to suppress -->
<NoWarn>$(NoWarn);NU1903;NU1510;CA1848;CA1727;CA1861;CA1825;CA1873;MUD0002;CA1725</NoWarn> <NoWarn>$(NoWarn);NU1903;NU1510;NU1603;NU1902;CA1848;CA1727;CA1861;CA1825;CA1873;MUD0002;CA1725</NoWarn>
<!-- Alpine workaround: no host package available for alpine.3.24-x64 --> <!-- Alpine workaround: no host package available for alpine.3.24-x64 -->
<UseAppHost>false</UseAppHost> <UseAppHost>false</UseAppHost>
</PropertyGroup> </PropertyGroup>
+14
View File
@@ -60,4 +60,18 @@ public sealed class AgentOptions
/// config arrives, it replaces this list entirely. /// config arrives, it replaces this list entirely.
/// </summary> /// </summary>
public List<AgentCameraOptions> Cameras { get; init; } = []; public List<AgentCameraOptions> Cameras { get; init; } = [];
/// <summary>
/// Determines where video frame analysis runs.
/// Local (default): YOLO/ONNX inference on the agent.
/// Remote: motion frames are downscaled and published to a broker.
/// Falls back to Local if the broker is unreachable.
/// </summary>
public AnalysisMode AnalysisMode { get; init; } = AnalysisMode.Local;
/// <summary>
/// URL of the remote analysis broker (required when AnalysisMode = Remote).
/// Example: http://heimdall-broker:8080
/// </summary>
public string? BrokerUrl { get; init; }
} }
+15
View File
@@ -0,0 +1,15 @@
namespace Heimdall.Agent;
/// <summary>
/// Determines where video frame analysis (object detection) runs.
/// Local: YOLO/ONNX inference on the agent itself.
/// Remote: frames are downscaled and published to an external broker for analysis.
/// </summary>
public enum AnalysisMode
{
/// <summary>Run YOLO/ONNX inference locally on the agent (default).</summary>
Local,
/// <summary>Publish motion frames to a remote broker for analysis. Falls back to Local if the broker is unreachable.</summary>
Remote
}
+1
View File
@@ -27,5 +27,6 @@
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.17.0" /> <PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.17.0" />
<PackageReference Include="Sentry.AspNetCore" Version="6.8.0" /> <PackageReference Include="Sentry.AspNetCore" Version="6.8.0" />
<PackageReference Include="Magick.NET-Q16-AnyCPU" Version="14.16.0" /> <PackageReference Include="Magick.NET-Q16-AnyCPU" Version="14.16.0" />
<PackageReference Include="SixLabors.ImageSharp" Version="3.0.3" />
</ItemGroup> </ItemGroup>
</Project> </Project>
+16
View File
@@ -53,6 +53,19 @@ builder.Services.AddHttpClient("IpResolver", client =>
client.Timeout = TimeSpan.FromSeconds(5); client.Timeout = TimeSpan.FromSeconds(5);
}); });
// Broker HTTP client — used by RemoteFrameBrokerService when AnalysisMode=Remote.
// BaseAddress is set from AgentOptions.BrokerUrl at client creation time.
builder.Services.AddHttpClient("Broker", (sp, client) =>
{
var options = sp.GetRequiredService<IOptions<AgentOptions>>().Value;
if (!string.IsNullOrEmpty(options.BrokerUrl))
{
var baseUrl = options.BrokerUrl.EndsWith('/') ? options.BrokerUrl : options.BrokerUrl + "/";
client.BaseAddress = new Uri(baseUrl);
}
client.Timeout = TimeSpan.FromSeconds(5);
});
// Data Protection — encrypts the agent API key at rest (issue #21). The key // Data Protection — encrypts the agent API key at rest (issue #21). The key
// ring is persisted next to the state file so the agent can decrypt its // ring is persisted next to the state file so the agent can decrypt its
// identity after a restart. Directory locked to owner-only (0700). For // identity after a restart. Directory locked to owner-only (0700). For
@@ -117,6 +130,9 @@ builder.Services.AddSingleton<FrameAnalyzerService>(sp => new FrameAnalyzerServi
sp.GetRequiredService<CircuitBreaker>(), sp.GetRequiredService<CircuitBreaker>(),
sp.GetRequiredService<PipelineDegradationManager>())); sp.GetRequiredService<PipelineDegradationManager>()));
builder.Services.AddSingleton<CameraStreamService>(); builder.Services.AddSingleton<CameraStreamService>();
builder.Services.AddSingleton<FrameResizer>();
builder.Services.AddSingleton<RemoteFrameBrokerService>();
builder.Services.AddSingleton<IRemoteFrameBroker>(sp => sp.GetRequiredService<RemoteFrameBrokerService>());
builder.Services.AddHostedService<SnapshotPipelineService>(); builder.Services.AddHostedService<SnapshotPipelineService>();
// Log capture & upload to Central (ticket #50) // Log capture & upload to Central (ticket #50)
@@ -0,0 +1,54 @@
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
namespace Heimdall.Agent.Services;
/// <summary>
/// Resizes JPEG frames to a target size (default 640×640) for remote broker submission.
/// Uses SixLabors.ImageSharp (already a project dependency) for efficient decode/resize/encode.
/// Thread-safe: multiple calls can run concurrently.
/// </summary>
public sealed class FrameResizer
{
private readonly int _targetSize;
private readonly ILogger<FrameResizer> _logger;
/// <summary>Default target size matching YOLOv8 input dimensions.</summary>
public const int DefaultTargetSize = 640;
public FrameResizer(ILogger<FrameResizer> logger, int targetSize = DefaultTargetSize)
{
_logger = logger;
_targetSize = targetSize;
}
/// <summary>
/// Resize a JPEG frame to a square of <paramref name="targetSize"/>×<paramref name="targetSize"/> pixels.
/// Returns the original data if resize fails (graceful degradation — the broker will receive the full frame).
/// </summary>
public byte[] Resize(byte[] jpegData, int? targetSize = null)
{
var size = targetSize ?? _targetSize;
try
{
using var input = Image.Load<Rgba32>(jpegData);
input.Mutate(ctx => ctx.Resize(new ResizeOptions
{
Size = new Size(size, size),
Mode = ResizeMode.Crop,
Position = AnchorPositionMode.Center,
}));
using var ms = new MemoryStream();
input.SaveAsJpeg(ms, new JpegEncoder { Quality = 85 });
return ms.ToArray();
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Frame resize failed — returning original {Size} bytes", jpegData.Length);
return jpegData;
}
}
}
@@ -0,0 +1,173 @@
using System.Net.Http.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Logging;
namespace Heimdall.Agent.Services;
/// <summary>
/// Submits motion-detected frames to a remote analysis broker for YOLO/ONNX inference.
/// The broker receives downscaled (640×640) JPEG frames with camera metadata and returns
/// detection results. If the broker is unreachable, the caller falls back to local analysis.
/// </summary>
public interface IRemoteFrameBroker
{
/// <summary>
/// Submit a frame to the remote broker. Returns detection results on success,
/// or null if the broker is unreachable (caller should fall back to local analysis).
/// </summary>
Task<BrokerFrameResponse?> SubmitFrameAsync(
Guid cameraId,
byte[] resizedJpegData,
DateTime timestampUtc,
CancellationToken ct = default);
/// <summary>Whether the broker was reachable on the last health check.</summary>
bool IsBrokerReachable { get; }
}
/// <summary>Request payload sent to the broker.</summary>
internal sealed record BrokerFrameRequest(
[property: JsonPropertyName("cameraId")] Guid CameraId,
[property: JsonPropertyName("timestamp")] DateTime TimestampUtc,
[property: JsonPropertyName("imageBase64")] string ImageBase64);
/// <summary>Detection result returned by the broker.</summary>
public sealed record BrokerDetection(
[property: JsonPropertyName("label")] string Label,
[property: JsonPropertyName("confidence")] float Confidence,
[property: JsonPropertyName("x")] float X,
[property: JsonPropertyName("y")] float Y,
[property: JsonPropertyName("width")] float Width,
[property: JsonPropertyName("height")] float Height);
/// <summary>Response from the broker containing detection results.</summary>
public sealed record BrokerFrameResponse(
[property: JsonPropertyName("detections")] IReadOnlyList<BrokerDetection> Detections,
[property: JsonPropertyName("processingMs")] long ProcessingMs);
public sealed class RemoteFrameBrokerService : IRemoteFrameBroker, IDisposable
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly AgentState _state;
private readonly ILogger<RemoteFrameBrokerService> _logger;
private long _submittedFrames;
private long _failedSubmissions;
private long _brokerUnreachableCount;
private bool _brokerReachable = true;
private DateTime _lastHealthCheck = DateTime.MinValue;
private static readonly TimeSpan HealthCheckInterval = TimeSpan.FromSeconds(30);
public bool IsBrokerReachable => _brokerReachable;
/// <summary>Number of frames successfully submitted to the broker.</summary>
public long SubmittedFrames => Interlocked.Read(ref _submittedFrames);
/// <summary>Number of failed submissions (broker errors).</summary>
public long FailedSubmissions => Interlocked.Read(ref _failedSubmissions);
/// <summary>Number of times the broker was unreachable.</summary>
public long BrokerUnreachableCount => Interlocked.Read(ref _brokerUnreachableCount);
public RemoteFrameBrokerService(
IHttpClientFactory httpClientFactory,
AgentState state,
ILogger<RemoteFrameBrokerService> logger)
{
_httpClientFactory = httpClientFactory;
_state = state;
_logger = logger;
}
public async Task<BrokerFrameResponse?> SubmitFrameAsync(
Guid cameraId,
byte[] resizedJpegData,
DateTime timestampUtc,
CancellationToken ct = default)
{
// Periodic health check — don't hammer a dead broker
if (DateTime.UtcNow - _lastHealthCheck > HealthCheckInterval)
{
await CheckBrokerHealthAsync(ct);
_lastHealthCheck = DateTime.UtcNow;
}
if (!_brokerReachable)
return null;
try
{
// Do NOT dispose the client — IHttpClientFactory manages the lifecycle.
var client = _httpClientFactory.CreateClient("Broker");
client.DefaultRequestHeaders.Remove("X-API-Key");
client.DefaultRequestHeaders.Add("X-API-Key", _state.ApiKey);
var request = new BrokerFrameRequest(
cameraId,
timestampUtc,
Convert.ToBase64String(resizedJpegData));
var response = await client.PostAsJsonAsync("api/frames", request, ct).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
Interlocked.Increment(ref _submittedFrames);
var result = await response.Content.ReadFromJsonAsync<BrokerFrameResponse>(ct).ConfigureAwait(false);
return result;
}
Interlocked.Increment(ref _failedSubmissions);
_logger.LogWarning(
"Broker frame submission failed for camera {CameraId}: {StatusCode}",
cameraId, response.StatusCode);
return null;
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
return null;
}
catch (Exception ex)
{
Interlocked.Increment(ref _failedSubmissions);
_logger.LogDebug(ex, "Broker frame submission dropped for camera {CameraId}", cameraId);
MarkBrokerUnreachable();
return null;
}
}
private async Task CheckBrokerHealthAsync(CancellationToken ct)
{
try
{
// Do NOT dispose the client — IHttpClientFactory manages the lifecycle.
var client = _httpClientFactory.CreateClient("Broker");
client.Timeout = TimeSpan.FromSeconds(3);
var response = await client.GetAsync("healthz", ct).ConfigureAwait(false);
_brokerReachable = response.IsSuccessStatusCode;
}
catch (Exception ex)
{
if (_brokerReachable)
{
_logger.LogWarning(ex, "Analysis broker unreachable — will fall back to local analysis");
Interlocked.Increment(ref _brokerUnreachableCount);
}
_brokerReachable = false;
}
}
private void MarkBrokerUnreachable()
{
if (_brokerReachable)
{
_logger.LogWarning("Analysis broker marked unreachable after error");
Interlocked.Increment(ref _brokerUnreachableCount);
}
_brokerReachable = false;
}
public void Dispose()
{
// No unmanaged resources to release
}
}
@@ -2,13 +2,30 @@ using System.Collections.Concurrent;
using Heimdall.Application.Metrics; using Heimdall.Application.Metrics;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
namespace Heimdall.Agent.Services; namespace Heimdall.Agent.Services;
/// <summary>
/// Bundles the dependencies required by <see cref="SnapshotPipelineService"/>
/// to avoid exceeding the SonarQube cognitive/parameter-count threshold (S107).
/// </summary>
public sealed record SnapshotPipelineServiceOptions(
AgentState State,
IOptions<AgentOptions> Options,
CameraConfigStore CameraStore,
CameraStreamService Streams,
FrameAnalyzerService Analyzer,
SceneStateTracker SceneState,
ICameraStatusReporter StatusReporter,
IDetectionReporter DetectionReporter,
ILogger<SnapshotPipelineService> Logger,
IRemoteFrameBroker? Broker = null,
FrameResizer? Resizer = null);
/// <summary> /// <summary>
/// Orchestrates the video capture pipeline (MASTER_SPEC Phase 15): /// Orchestrates the video capture pipeline (MASTER_SPEC Phase 15):
/// keeps the FFmpeg capture streams in sync with the assigned cameras /// keeps the FFmpeg capture streams in sync with the assigned cameras
/// (from the Central config, local fallback before that) and consumes the /// (from the Central config, local fallback before that) and consumes the
/// bounded snapshot channel, forwarding each frame to the /// bounded snapshot channel, forwarding each frame to the analysis pipeline
/// <see cref="FrameAnalyzerService"/> and updating the scene state that /// (local YOLO or remote broker, depending on AnalysisMode) and updating
/// drives the adaptive snapshot interval. /// the scene state that drives the adaptive snapshot interval.
/// ///
/// Integrates with <see cref="PipelineDegradationManager"/> for graceful /// Integrates with <see cref="PipelineDegradationManager"/> for graceful
/// degradation: /// degradation:
@@ -29,6 +46,8 @@ public sealed class SnapshotPipelineService : BackgroundService
private readonly IDetectionReporter _detectionReporter; private readonly IDetectionReporter _detectionReporter;
private readonly PipelineDegradationManager _degradationManager; private readonly PipelineDegradationManager _degradationManager;
private readonly SystemMetricsProvider _metrics; private readonly SystemMetricsProvider _metrics;
private readonly IRemoteFrameBroker? _broker;
private readonly FrameResizer? _resizer;
private readonly ILogger<SnapshotPipelineService> _logger; private readonly ILogger<SnapshotPipelineService> _logger;
private readonly ConcurrentDictionary<Guid, FrameMotionDetector> _motionDetectors = new(); private readonly ConcurrentDictionary<Guid, FrameMotionDetector> _motionDetectors = new();
private readonly ConcurrentDictionary<Guid, SceneState> _reportedSceneState = new(); private readonly ConcurrentDictionary<Guid, SceneState> _reportedSceneState = new();
@@ -36,35 +55,28 @@ public sealed class SnapshotPipelineService : BackgroundService
private long _snapshotsProcessed; private long _snapshotsProcessed;
private long _analysisFailures; private long _analysisFailures;
private long _snapshotsSkippedByDegradation; private long _snapshotsSkippedByDegradation;
private long _remoteSubmissions;
private long _remoteFallbacks;
private bool _storeSubscribed; private bool _storeSubscribed;
private DateTime _lastCpuCheckAt = DateTime.MinValue; private DateTime _lastCpuCheckAt = DateTime.MinValue;
private static readonly TimeSpan CpuCheckInterval = TimeSpan.FromSeconds(10); private static readonly TimeSpan CpuCheckInterval = TimeSpan.FromSeconds(10);
public SnapshotPipelineService( public SnapshotPipelineService(SnapshotPipelineServiceOptions options)
AgentState state,
IOptions<AgentOptions> options,
CameraConfigStore cameraStore,
CameraStreamService streams,
FrameAnalyzerService analyzer,
SceneStateTracker sceneState,
ICameraStatusReporter statusReporter,
IDetectionReporter detectionReporter,
PipelineDegradationManager degradationManager,
SystemMetricsProvider metrics,
ILogger<SnapshotPipelineService> logger)
{ {
_state = state; _state = options.State;
_options = options.Value; _options = options.Options.Value;
_cameraStore = cameraStore; _cameraStore = options.CameraStore;
_streams = streams; _streams = options.Streams;
_analyzer = analyzer; _analyzer = options.Analyzer;
_sceneState = sceneState; _sceneState = options.SceneState;
_statusReporter = statusReporter; _statusReporter = options.StatusReporter;
_detectionReporter = detectionReporter; _detectionReporter = options.DetectionReporter;
_degradationManager = degradationManager; _degradationManager = options.DegradationManager;
_metrics = metrics; _metrics = options.Metrics;
_logger = logger; _logger = options.Logger;
_broker = options.Broker;
_resizer = options.Resizer;
} }
/// <summary>Number of snapshots handed to the analyzer (real calls).</summary> /// <summary>Number of snapshots handed to the analyzer (real calls).</summary>
@@ -76,11 +88,34 @@ public sealed class SnapshotPipelineService : BackgroundService
/// <summary>Number of snapshots skipped because of pipeline degradation.</summary> /// <summary>Number of snapshots skipped because of pipeline degradation.</summary>
public long SnapshotsSkippedByDegradation => Interlocked.Read(ref _snapshotsSkippedByDegradation); public long SnapshotsSkippedByDegradation => Interlocked.Read(ref _snapshotsSkippedByDegradation);
/// <summary>Number of frames submitted to the remote broker.</summary>
public long RemoteSubmissions => Interlocked.Read(ref _remoteSubmissions);
/// <summary>Number of remote submissions that fell back to local analysis.</summary>
public long RemoteFallbacks => Interlocked.Read(ref _remoteFallbacks);
/// <summary>Whether the pipeline is operating in remote analysis mode.</summary>
public bool IsRemoteMode => _options.AnalysisMode == AnalysisMode.Remote && _broker is not null;
protected override async Task ExecuteAsync(CancellationToken stoppingToken) protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{ {
// Local fallback (Agent:Cameras) until the Central camera list arrives. // Local fallback (Agent:Cameras) until the Central camera list arrives.
_cameraStore.SetLocalFallback(BuildLocalCameras()); _cameraStore.SetLocalFallback(BuildLocalCameras());
if (_options.AnalysisMode == AnalysisMode.Remote)
{
if (string.IsNullOrEmpty(_options.BrokerUrl))
_logger.LogWarning("AnalysisMode is Remote but BrokerUrl is not configured — remote analysis disabled");
else
_logger.LogInformation(
"Analysis mode: Remote (broker: {BrokerUrl}). Fallback to local if broker unreachable.",
_options.BrokerUrl);
}
else
{
_logger.LogInformation("Analysis mode: Local (YOLO/ONNX on agent)");
}
// Wait until the agent is registered (has an AgentId), same as // Wait until the agent is registered (has an AgentId), same as
// ConfigReceiverService — the Central config needs the agent identity. // ConfigReceiverService — the Central config needs the agent identity.
while (_state.AgentId == Guid.Empty && !stoppingToken.IsCancellationRequested) while (_state.AgentId == Guid.Empty && !stoppingToken.IsCancellationRequested)
@@ -110,7 +145,11 @@ public sealed class SnapshotPipelineService : BackgroundService
{ {
if (_storeSubscribed) if (_storeSubscribed)
_cameraStore.Changed -= OnCameraConfigChanged; _cameraStore.Changed -= OnCameraConfigChanged;
try { await consumer; } catch (OperationCanceledException) { } try { await consumer; }
catch (OperationCanceledException)
{
// Intentional: suppress cancellation during graceful shutdown
}
try { await cpuMonitor; } catch (OperationCanceledException) { } try { await cpuMonitor; } catch (OperationCanceledException) { }
} }
} }
@@ -214,6 +253,31 @@ public sealed class SnapshotPipelineService : BackgroundService
// Check degradation level before processing // Check degradation level before processing
var level = _degradationManager.Level; var level = _degradationManager.Level;
// Motion detection runs in both modes — it gates remote submission.
var detector = _motionDetectors.GetOrAdd(snapshot.CameraId, _ => new FrameMotionDetector());
var motion = detector.Detect(snapshot.JpegData);
FrameAnalysisResult? result = null;
if (IsRemoteMode && motion)
{
// Remote mode + motion: submit frame to broker, fallback to local if unreachable.
result = await AnalyzeRemoteAsync(snapshot, ct);
}
if (result is null)
{
// Local analysis: either Local mode, or Remote mode with broker fallback,
// or Remote mode but no motion (still run local for detection coverage).
result = await _analyzer.AnalyzeFrameAsync(snapshot.JpegData, ct);
}
Interlocked.Increment(ref _snapshotsProcessed);
_sceneState.UpdateFromAnalysis(
result?.Detections.Count > 0,
motion);
if (level >= DegradationLevel.ExecutorDown) if (level >= DegradationLevel.ExecutorDown)
{ {
// Motion-only mode: skip IA inference, only do motion detection // Motion-only mode: skip IA inference, only do motion detection
@@ -266,6 +330,58 @@ public sealed class SnapshotPipelineService : BackgroundService
} }
} }
/// <summary>
/// Submit a motion-detected frame to the remote broker. Returns detection results
/// on success, or null if the broker is unreachable (caller should fall back to local).
/// </summary>
private async Task<FrameAnalysisResult?> AnalyzeRemoteAsync(Snapshot snapshot, CancellationToken ct)
{
if (_broker is null || _resizer is null)
return null;
try
{
// Downscale to 640×640 for the broker
var resized = _resizer.Resize(snapshot.JpegData);
var brokerResult = await _broker.SubmitFrameAsync(
snapshot.CameraId, resized, snapshot.TimestampUtc, ct).ConfigureAwait(false);
if (brokerResult is null)
{
// Broker unreachable — fall back to local
Interlocked.Increment(ref _remoteFallbacks);
_logger.LogDebug(
"Broker unreachable for camera {CameraId} — falling back to local analysis",
snapshot.CameraId);
return null;
}
Interlocked.Increment(ref _remoteSubmissions);
// Map broker detections to the existing FrameAnalysisResult format
var detections = brokerResult.Detections
.Select(d => new DetectionResult(
d.Label, d.Confidence, d.X, d.Y, d.Width, d.Height))
.ToList();
return new FrameAnalysisResult(
Convert.ToBase64String(resized),
detections,
brokerResult.ProcessingMs);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
return null;
}
catch (Exception ex)
{
Interlocked.Increment(ref _remoteFallbacks);
_logger.LogDebug(ex, "Remote analysis failed for camera {CameraId} — falling back to local", snapshot.CameraId);
return null;
}
}
/// <summary> /// <summary>
/// Report a MotionDetected event on the idle → active scene transition /// Report a MotionDetected event on the idle → active scene transition
/// (per camera, once per transition — the reporter's cooldown prevents /// (per camera, once per transition — the reporter's cooldown prevents
@@ -0,0 +1,119 @@
using Heimdall.Agent.Services;
using Microsoft.Extensions.Logging;
using NSubstitute;
using Shouldly;
namespace Heimdall.Agent.Tests;
public class FrameResizerTests
{
private static FrameResizer CreateResizer(int targetSize = 640)
{
return new FrameResizer(Substitute.For<ILogger<FrameResizer>>(), targetSize);
}
[Fact]
public void Resize_InvalidJpeg_ReturnsOriginalData()
{
var resizer = CreateResizer();
var garbage = new byte[] { 0x00, 0x01, 0x02, 0x03 };
var result = resizer.Resize(garbage);
result.ShouldBe(garbage);
}
[Fact]
public void Resize_ValidJpeg_ReturnsDifferentSize()
{
// Create a minimal valid JPEG (1x1 white pixel)
var jpeg1x1 = CreateMinimalJpeg();
var resizer = CreateResizer(640);
var result = resizer.Resize(jpeg1x1);
// The resized image should be a different (larger) JPEG
result.ShouldNotBeNull();
result.Length.ShouldNotBe(0);
// Output should be a valid JPEG (starts with FF D8)
result[0].ShouldBe((byte)0xFF);
result[1].ShouldBe((byte)0xD8);
}
[Fact]
public void Resize_DefaultTargetSize_Is640()
{
FrameResizer.DefaultTargetSize.ShouldBe(640);
}
[Fact]
public async Task Resize_ConcurrentCalls_DoesNotThrow()
{
var resizer = CreateResizer();
var jpeg = CreateMinimalJpeg();
// Run multiple resizes concurrently
var tasks = Enumerable.Range(0, 10)
.Select(_ => Task.Run(() => resizer.Resize(jpeg)))
.ToArray();
await Task.WhenAll(tasks);
foreach (var task in tasks)
task.IsCompletedSuccessfully.ShouldBeTrue();
}
/// <summary>Creates a minimal valid JPEG file (1x1 white pixel).</summary>
private static byte[] CreateMinimalJpeg()
{
// Minimal JPEG: SOI + APP0 + DQT + SOF0 + DHT + SOS + EOI
// This is the smallest valid JPEG that ImageSharp can load.
return [
0xFF, 0xD8, // SOI
0xFF, 0xE0, // APP0
0x00, 0x10, // Length
0x4A, 0x46, 0x49, 0x46, 0x00, // "JFIF\0"
0x01, 0x01, // Version
0x00, // Units
0x00, 0x01, // X density
0x00, 0x01, // Y density
0x00, 0x00, // Thumbnail
0xFF, 0xDB, // DQT
0x00, 0x43, // Length
0x00, // Table 0
// 64 quantization values (all 1 for simplicity)
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0xFF, 0xC0, // SOF0
0x00, 0x0B, // Length
0x08, // Precision
0x00, 0x01, // Height
0x00, 0x01, // Width
0x01, // Components
0x01, // Component 1: ID
0x11, // Sampling factors
0x00, // Quant table
0xFF, 0xC4, // DHT
0x00, 0x1F, // Length
0x00, // DC table 0
0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B,
0xFF, 0xDA, // SOS
0x00, 0x08, // Length
0x01, // Components
0x01, // Component 1
0x00, // DC table, AC table
0x00, 0x3F, // Ss, Se, Ah/Al
0x00, // Dummy data
0xFF, 0xD9, // EOI
];
}
}
@@ -0,0 +1,141 @@
using System.Net;
using System.Text;
using Heimdall.Agent.Services;
using Microsoft.Extensions.Logging;
using NSubstitute;
using Shouldly;
namespace Heimdall.Agent.Tests;
public class RemoteFrameBrokerServiceTests
{
private static (RemoteFrameBrokerService Service, AgentState State) CreateBroker(
HttpMessageHandler? handler = null)
{
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var logger = Substitute.For<ILogger<RemoteFrameBrokerService>>();
IHttpClientFactory httpClientFactory;
if (handler is not null)
{
var client = new HttpClient(handler) { BaseAddress = new Uri("http://broker:8080/") };
httpClientFactory = Substitute.For<IHttpClientFactory>();
httpClientFactory.CreateClient("Broker").Returns(client);
}
else
{
httpClientFactory = Substitute.For<IHttpClientFactory>();
}
var service = new RemoteFrameBrokerService(httpClientFactory, state, logger);
return (service, state);
}
[Fact]
public async Task SubmitFrameAsync_UnregisteredAgent_ReturnsNull()
{
var state = new AgentState { AgentId = Guid.Empty, ApiKey = "" };
var logger = Substitute.For<ILogger<RemoteFrameBrokerService>>();
var httpClientFactory = Substitute.For<IHttpClientFactory>();
var service = new RemoteFrameBrokerService(httpClientFactory, state, logger);
var result = await service.SubmitFrameAsync(
Guid.NewGuid(), [1, 2, 3], DateTime.UtcNow);
result.ShouldBeNull();
}
[Fact]
public void IsBrokerReachable_DefaultsTrue()
{
var (service, _) = CreateBroker();
service.IsBrokerReachable.ShouldBeTrue();
}
[Fact]
public void Counters_InitiallyZero()
{
var (service, _) = CreateBroker();
service.SubmittedFrames.ShouldBe(0);
service.FailedSubmissions.ShouldBe(0);
service.BrokerUnreachableCount.ShouldBe(0);
}
[Fact]
public async Task SubmitFrameAsync_BrokerReturns404_ReturnsNull()
{
var handler = new StubHttpMessageHandler(HttpStatusCode.NotFound);
var (service, _) = CreateBroker(handler);
var result = await service.SubmitFrameAsync(
Guid.NewGuid(), [1, 2, 3], DateTime.UtcNow);
// Health check returns 404 → broker marked unreachable → no POST made
result.ShouldBeNull();
service.IsBrokerReachable.ShouldBeFalse();
}
[Fact]
public async Task SubmitFrameAsync_BrokerUnreachable_SetsUnreachableFlag()
{
var handler = new StubHttpMessageHandler(new HttpRequestException("Connection refused"));
var (service, _) = CreateBroker(handler);
var result = await service.SubmitFrameAsync(
Guid.NewGuid(), [1, 2, 3], DateTime.UtcNow);
result.ShouldBeNull();
service.IsBrokerReachable.ShouldBeFalse();
service.BrokerUnreachableCount.ShouldBe(1);
}
[Fact]
public async Task SubmitFrameAsync_BrokerReturnsDetections_MapsCorrectly()
{
var json = """{"detections":[{"label":"person","confidence":0.92,"x":0.1,"y":0.2,"width":0.3,"height":0.4}],"processingMs":42}""";
var handler = new StubHttpMessageHandler(HttpStatusCode.OK, json);
var (service, _) = CreateBroker(handler);
var result = await service.SubmitFrameAsync(
Guid.NewGuid(), [1, 2, 3], DateTime.UtcNow);
result.ShouldNotBeNull();
result.ProcessingMs.ShouldBe(42);
result.Detections.ShouldHaveSingleItem();
result.Detections[0].Label.ShouldBe("person");
result.Detections[0].Confidence.ShouldBe(0.92f);
service.SubmittedFrames.ShouldBe(1);
}
/// <summary>Minimal HTTP handler for testing without real network calls.</summary>
private sealed class StubHttpMessageHandler : HttpMessageHandler
{
private readonly HttpStatusCode _statusCode;
private readonly string? _responseBody;
private readonly Exception? _exception;
public StubHttpMessageHandler(HttpStatusCode statusCode, string? responseBody = null)
{
_statusCode = statusCode;
_responseBody = responseBody;
}
public StubHttpMessageHandler(Exception exception)
{
_exception = exception;
}
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
if (_exception is not null)
throw _exception;
var response = new HttpResponseMessage(_statusCode);
if (_responseBody is not null)
response.Content = new StringContent(_responseBody, Encoding.UTF8, "application/json");
return Task.FromResult(response);
}
}
}
@@ -10,7 +10,9 @@ public class SnapshotPipelineServiceTests
private const string FfmpegNotFound = "/usr/bin/nonexistent-ffmpeg"; private const string FfmpegNotFound = "/usr/bin/nonexistent-ffmpeg";
private static (SnapshotPipelineService Service, AgentState State, CameraConfigStore Store, CameraStreamService Streams, FrameAnalyzerService Analyzer) CreatePipeline( private static (SnapshotPipelineService Service, AgentState State, CameraConfigStore Store, CameraStreamService Streams, FrameAnalyzerService Analyzer) CreatePipeline(
List<AgentCameraOptions>? cameras = null) List<AgentCameraOptions>? cameras = null,
AnalysisMode analysisMode = AnalysisMode.Local,
string? brokerUrl = null)
{ {
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" }; var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var options = Options.Create(new AgentOptions var options = Options.Create(new AgentOptions
@@ -18,6 +20,8 @@ public class SnapshotPipelineServiceTests
CentralUrl = "http://localhost:5000", CentralUrl = "http://localhost:5000",
SiteToken = "test", SiteToken = "test",
Cameras = cameras ?? [], Cameras = cameras ?? [],
AnalysisMode = analysisMode,
BrokerUrl = brokerUrl,
}); });
var store = new CameraConfigStore(); var store = new CameraConfigStore();
var streams = new CameraStreamService(Substitute.For<ILogger<CameraStreamService>>(), FfmpegNotFound); var streams = new CameraStreamService(Substitute.For<ILogger<CameraStreamService>>(), FfmpegNotFound);
@@ -26,10 +30,10 @@ public class SnapshotPipelineServiceTests
var detectionReporter = Substitute.For<IDetectionReporter>(); var detectionReporter = Substitute.For<IDetectionReporter>();
var degradationManager = new PipelineDegradationManager(Substitute.For<ILogger<PipelineDegradationManager>>()); var degradationManager = new PipelineDegradationManager(Substitute.For<ILogger<PipelineDegradationManager>>());
var metrics = new SystemMetricsProvider(); var metrics = new SystemMetricsProvider();
var service = new SnapshotPipelineService( var service = new SnapshotPipelineService(new SnapshotPipelineServiceOptions(
state, options, store, streams, analyzer, new SceneStateTracker(), statusReporter, detectionReporter, state, options, store, streams, analyzer, new SceneStateTracker(), statusReporter, detectionReporter,
degradationManager, metrics, Substitute.For<ILogger<SnapshotPipelineService>>(),
Substitute.For<ILogger<SnapshotPipelineService>>()); degradationManager: degradationManager, metrics: metrics));
return (service, state, store, streams, analyzer); return (service, state, store, streams, analyzer);
} }
@@ -49,7 +53,6 @@ public class SnapshotPipelineServiceTests
public async Task StartStop_WithNoCameras_DoesNotStartStreams() public async Task StartStop_WithNoCameras_DoesNotStartStreams()
{ {
var (service, _, _, streams, _) = CreatePipeline(); var (service, _, _, streams, _) = CreatePipeline();
await service.StartAsync(CancellationToken.None); await service.StartAsync(CancellationToken.None);
try try
{ {
@@ -92,13 +95,11 @@ public class SnapshotPipelineServiceTests
public async Task SnapshotWrittenToChannel_IsForwardedToAnalyzer() public async Task SnapshotWrittenToChannel_IsForwardedToAnalyzer()
{ {
var (service, _, _, streams, analyzer) = CreatePipeline(); var (service, _, _, streams, analyzer) = CreatePipeline();
await service.StartAsync(CancellationToken.None); await service.StartAsync(CancellationToken.None);
try try
{ {
await streams.SnapshotChannel.Writer.WriteAsync( await streams.SnapshotChannel.Writer.WriteAsync(
new Snapshot(Guid.NewGuid(), DateTime.UtcNow, [1, 2, 3])); new Snapshot(Guid.NewGuid(), DateTime.UtcNow, [1, 2, 3]));
var deadline = DateTime.UtcNow.AddSeconds(5); var deadline = DateTime.UtcNow.AddSeconds(5);
while (service.SnapshotsProcessed == 0 && DateTime.UtcNow < deadline) while (service.SnapshotsProcessed == 0 && DateTime.UtcNow < deadline)
await Task.Delay(50); await Task.Delay(50);
@@ -120,4 +121,27 @@ public class SnapshotPipelineServiceTests
await service.StopAsync(CancellationToken.None); await service.StopAsync(CancellationToken.None);
service.ShouldNotBeNull(); service.ShouldNotBeNull();
} }
[Fact]
public void IsRemoteMode_LocalMode_ReturnsFalse()
{
var (service, _, _, _, _) = CreatePipeline(analysisMode: AnalysisMode.Local);
service.IsRemoteMode.ShouldBeFalse();
}
[Fact]
public void IsRemoteMode_RemoteMode_NoBroker_ReturnsFalse()
{
// Remote mode but no broker service injected → not actually remote
var (service, _, _, _, _) = CreatePipeline(analysisMode: AnalysisMode.Remote);
service.IsRemoteMode.ShouldBeFalse();
}
[Fact]
public void RemoteSubmissions_InitiallyZero()
{
var (service, _, _, _, _) = CreatePipeline();
service.RemoteSubmissions.ShouldBe(0);
service.RemoteFallbacks.ShouldBe(0);
}
} }