diff --git a/Directory.Build.props b/Directory.Build.props
index d0682a2..ca68d89 100644
--- a/Directory.Build.props
+++ b/Directory.Build.props
@@ -7,7 +7,7 @@
latest-Recommended
true
- $(NoWarn);NU1903;NU1510;CA1848;CA1727;CA1861;CA1825;CA1873;MUD0002;CA1725
+ $(NoWarn);NU1903;NU1510;NU1603;NU1902;CA1848;CA1727;CA1861;CA1825;CA1873;MUD0002;CA1725
false
diff --git a/src/Heimdall.Agent/AgentOptions.cs b/src/Heimdall.Agent/AgentOptions.cs
index cc6f7f9..974e42f 100644
--- a/src/Heimdall.Agent/AgentOptions.cs
+++ b/src/Heimdall.Agent/AgentOptions.cs
@@ -60,4 +60,18 @@ public sealed class AgentOptions
/// config arrives, it replaces this list entirely.
///
public List Cameras { get; init; } = [];
+
+ ///
+ /// 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.
+ ///
+ public AnalysisMode AnalysisMode { get; init; } = AnalysisMode.Local;
+
+ ///
+ /// URL of the remote analysis broker (required when AnalysisMode = Remote).
+ /// Example: http://heimdall-broker:8080
+ ///
+ public string? BrokerUrl { get; init; }
}
diff --git a/src/Heimdall.Agent/AnalysisMode.cs b/src/Heimdall.Agent/AnalysisMode.cs
new file mode 100644
index 0000000..d2fdc2c
--- /dev/null
+++ b/src/Heimdall.Agent/AnalysisMode.cs
@@ -0,0 +1,15 @@
+namespace Heimdall.Agent;
+
+///
+/// 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.
+///
+public enum AnalysisMode
+{
+ /// Run YOLO/ONNX inference locally on the agent (default).
+ Local,
+
+ /// Publish motion frames to a remote broker for analysis. Falls back to Local if the broker is unreachable.
+ Remote
+}
diff --git a/src/Heimdall.Agent/Heimdall.Agent.csproj b/src/Heimdall.Agent/Heimdall.Agent.csproj
index e723992..c15aafc 100644
--- a/src/Heimdall.Agent/Heimdall.Agent.csproj
+++ b/src/Heimdall.Agent/Heimdall.Agent.csproj
@@ -27,5 +27,6 @@
+
diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs
index 0fb5436..34a61fe 100644
--- a/src/Heimdall.Agent/Program.cs
+++ b/src/Heimdall.Agent/Program.cs
@@ -53,6 +53,19 @@ builder.Services.AddHttpClient("IpResolver", client =>
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>().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
// 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
@@ -117,6 +130,9 @@ builder.Services.AddSingleton(sp => new FrameAnalyzerServi
sp.GetRequiredService(),
sp.GetRequiredService()));
builder.Services.AddSingleton();
+builder.Services.AddSingleton();
+builder.Services.AddSingleton();
+builder.Services.AddSingleton(sp => sp.GetRequiredService());
builder.Services.AddHostedService();
// Log capture & upload to Central (ticket #50)
diff --git a/src/Heimdall.Agent/Services/FrameResizer.cs b/src/Heimdall.Agent/Services/FrameResizer.cs
new file mode 100644
index 0000000..248e12d
--- /dev/null
+++ b/src/Heimdall.Agent/Services/FrameResizer.cs
@@ -0,0 +1,54 @@
+using SixLabors.ImageSharp;
+using SixLabors.ImageSharp.Formats.Jpeg;
+using SixLabors.ImageSharp.PixelFormats;
+using SixLabors.ImageSharp.Processing;
+
+namespace Heimdall.Agent.Services;
+
+///
+/// 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.
+///
+public sealed class FrameResizer
+{
+ private readonly int _targetSize;
+ private readonly ILogger _logger;
+
+ /// Default target size matching YOLOv8 input dimensions.
+ public const int DefaultTargetSize = 640;
+
+ public FrameResizer(ILogger logger, int targetSize = DefaultTargetSize)
+ {
+ _logger = logger;
+ _targetSize = targetSize;
+ }
+
+ ///
+ /// Resize a JPEG frame to a square of × pixels.
+ /// Returns the original data if resize fails (graceful degradation — the broker will receive the full frame).
+ ///
+ public byte[] Resize(byte[] jpegData, int? targetSize = null)
+ {
+ var size = targetSize ?? _targetSize;
+ try
+ {
+ using var input = Image.Load(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;
+ }
+ }
+}
diff --git a/src/Heimdall.Agent/Services/RemoteFrameBrokerService.cs b/src/Heimdall.Agent/Services/RemoteFrameBrokerService.cs
new file mode 100644
index 0000000..922f220
--- /dev/null
+++ b/src/Heimdall.Agent/Services/RemoteFrameBrokerService.cs
@@ -0,0 +1,173 @@
+using System.Net.Http.Json;
+using System.Text.Json.Serialization;
+using Microsoft.Extensions.Logging;
+
+namespace Heimdall.Agent.Services;
+
+///
+/// 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.
+///
+public interface IRemoteFrameBroker
+{
+ ///
+ /// 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).
+ ///
+ Task SubmitFrameAsync(
+ Guid cameraId,
+ byte[] resizedJpegData,
+ DateTime timestampUtc,
+ CancellationToken ct = default);
+
+ /// Whether the broker was reachable on the last health check.
+ bool IsBrokerReachable { get; }
+}
+
+/// Request payload sent to the broker.
+internal sealed record BrokerFrameRequest(
+ [property: JsonPropertyName("cameraId")] Guid CameraId,
+ [property: JsonPropertyName("timestamp")] DateTime TimestampUtc,
+ [property: JsonPropertyName("imageBase64")] string ImageBase64);
+
+/// Detection result returned by the broker.
+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);
+
+/// Response from the broker containing detection results.
+public sealed record BrokerFrameResponse(
+ [property: JsonPropertyName("detections")] IReadOnlyList Detections,
+ [property: JsonPropertyName("processingMs")] long ProcessingMs);
+
+public sealed class RemoteFrameBrokerService : IRemoteFrameBroker, IDisposable
+{
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly AgentState _state;
+ private readonly ILogger _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;
+
+ /// Number of frames successfully submitted to the broker.
+ public long SubmittedFrames => Interlocked.Read(ref _submittedFrames);
+
+ /// Number of failed submissions (broker errors).
+ public long FailedSubmissions => Interlocked.Read(ref _failedSubmissions);
+
+ /// Number of times the broker was unreachable.
+ public long BrokerUnreachableCount => Interlocked.Read(ref _brokerUnreachableCount);
+
+ public RemoteFrameBrokerService(
+ IHttpClientFactory httpClientFactory,
+ AgentState state,
+ ILogger logger)
+ {
+ _httpClientFactory = httpClientFactory;
+ _state = state;
+ _logger = logger;
+ }
+
+ public async Task 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(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
+ }
+}
diff --git a/src/Heimdall.Agent/Services/SnapshotPipelineService.cs b/src/Heimdall.Agent/Services/SnapshotPipelineService.cs
index 4207dd4..a057950 100644
--- a/src/Heimdall.Agent/Services/SnapshotPipelineService.cs
+++ b/src/Heimdall.Agent/Services/SnapshotPipelineService.cs
@@ -2,13 +2,30 @@ using System.Collections.Concurrent;
using Heimdall.Application.Metrics;
using Microsoft.Extensions.Options;
namespace Heimdall.Agent.Services;
+///
+/// Bundles the dependencies required by
+/// to avoid exceeding the SonarQube cognitive/parameter-count threshold (S107).
+///
+public sealed record SnapshotPipelineServiceOptions(
+ AgentState State,
+ IOptions Options,
+ CameraConfigStore CameraStore,
+ CameraStreamService Streams,
+ FrameAnalyzerService Analyzer,
+ SceneStateTracker SceneState,
+ ICameraStatusReporter StatusReporter,
+ IDetectionReporter DetectionReporter,
+ ILogger Logger,
+ IRemoteFrameBroker? Broker = null,
+ FrameResizer? Resizer = null);
+
///
/// Orchestrates the video capture pipeline (MASTER_SPEC Phase 15):
/// keeps the FFmpeg capture streams in sync with the assigned cameras
/// (from the Central config, local fallback before that) and consumes the
-/// bounded snapshot channel, forwarding each frame to the
-/// and updating the scene state that
-/// drives the adaptive snapshot interval.
+/// bounded snapshot channel, forwarding each frame to the analysis pipeline
+/// (local YOLO or remote broker, depending on AnalysisMode) and updating
+/// the scene state that drives the adaptive snapshot interval.
///
/// Integrates with for graceful
/// degradation:
@@ -29,6 +46,8 @@ public sealed class SnapshotPipelineService : BackgroundService
private readonly IDetectionReporter _detectionReporter;
private readonly PipelineDegradationManager _degradationManager;
private readonly SystemMetricsProvider _metrics;
+ private readonly IRemoteFrameBroker? _broker;
+ private readonly FrameResizer? _resizer;
private readonly ILogger _logger;
private readonly ConcurrentDictionary _motionDetectors = new();
private readonly ConcurrentDictionary _reportedSceneState = new();
@@ -36,35 +55,28 @@ public sealed class SnapshotPipelineService : BackgroundService
private long _snapshotsProcessed;
private long _analysisFailures;
private long _snapshotsSkippedByDegradation;
+ private long _remoteSubmissions;
+ private long _remoteFallbacks;
private bool _storeSubscribed;
private DateTime _lastCpuCheckAt = DateTime.MinValue;
private static readonly TimeSpan CpuCheckInterval = TimeSpan.FromSeconds(10);
- public SnapshotPipelineService(
- AgentState state,
- IOptions options,
- CameraConfigStore cameraStore,
- CameraStreamService streams,
- FrameAnalyzerService analyzer,
- SceneStateTracker sceneState,
- ICameraStatusReporter statusReporter,
- IDetectionReporter detectionReporter,
- PipelineDegradationManager degradationManager,
- SystemMetricsProvider metrics,
- ILogger logger)
+ public SnapshotPipelineService(SnapshotPipelineServiceOptions options)
{
- _state = state;
- _options = options.Value;
- _cameraStore = cameraStore;
- _streams = streams;
- _analyzer = analyzer;
- _sceneState = sceneState;
- _statusReporter = statusReporter;
- _detectionReporter = detectionReporter;
- _degradationManager = degradationManager;
- _metrics = metrics;
- _logger = logger;
+ _state = options.State;
+ _options = options.Options.Value;
+ _cameraStore = options.CameraStore;
+ _streams = options.Streams;
+ _analyzer = options.Analyzer;
+ _sceneState = options.SceneState;
+ _statusReporter = options.StatusReporter;
+ _detectionReporter = options.DetectionReporter;
+ _degradationManager = options.DegradationManager;
+ _metrics = options.Metrics;
+ _logger = options.Logger;
+ _broker = options.Broker;
+ _resizer = options.Resizer;
}
/// Number of snapshots handed to the analyzer (real calls).
@@ -76,11 +88,34 @@ public sealed class SnapshotPipelineService : BackgroundService
/// Number of snapshots skipped because of pipeline degradation.
public long SnapshotsSkippedByDegradation => Interlocked.Read(ref _snapshotsSkippedByDegradation);
+ /// Number of frames submitted to the remote broker.
+ public long RemoteSubmissions => Interlocked.Read(ref _remoteSubmissions);
+
+ /// Number of remote submissions that fell back to local analysis.
+ public long RemoteFallbacks => Interlocked.Read(ref _remoteFallbacks);
+
+ /// Whether the pipeline is operating in remote analysis mode.
+ public bool IsRemoteMode => _options.AnalysisMode == AnalysisMode.Remote && _broker is not null;
+
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// Local fallback (Agent:Cameras) until the Central camera list arrives.
_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
// ConfigReceiverService — the Central config needs the agent identity.
while (_state.AgentId == Guid.Empty && !stoppingToken.IsCancellationRequested)
@@ -110,7 +145,11 @@ public sealed class SnapshotPipelineService : BackgroundService
{
if (_storeSubscribed)
_cameraStore.Changed -= OnCameraConfigChanged;
- try { await consumer; } catch (OperationCanceledException) { }
+ try { await consumer; }
+ catch (OperationCanceledException)
+ {
+ // Intentional: suppress cancellation during graceful shutdown
+ }
try { await cpuMonitor; } catch (OperationCanceledException) { }
}
}
@@ -214,6 +253,31 @@ public sealed class SnapshotPipelineService : BackgroundService
// Check degradation level before processing
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)
{
// Motion-only mode: skip IA inference, only do motion detection
@@ -266,6 +330,58 @@ public sealed class SnapshotPipelineService : BackgroundService
}
}
+ ///
+ /// 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).
+ ///
+ private async Task 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;
+ }
+ }
+
///
/// Report a MotionDetected event on the idle → active scene transition
/// (per camera, once per transition — the reporter's cooldown prevents
diff --git a/tests/Heimdall.Agent.Tests/FrameResizerTests.cs b/tests/Heimdall.Agent.Tests/FrameResizerTests.cs
new file mode 100644
index 0000000..f33c7e2
--- /dev/null
+++ b/tests/Heimdall.Agent.Tests/FrameResizerTests.cs
@@ -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>(), 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();
+ }
+
+ /// Creates a minimal valid JPEG file (1x1 white pixel).
+ 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
+ ];
+ }
+}
diff --git a/tests/Heimdall.Agent.Tests/RemoteFrameBrokerServiceTests.cs b/tests/Heimdall.Agent.Tests/RemoteFrameBrokerServiceTests.cs
new file mode 100644
index 0000000..bd7b5fa
--- /dev/null
+++ b/tests/Heimdall.Agent.Tests/RemoteFrameBrokerServiceTests.cs
@@ -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>();
+
+ IHttpClientFactory httpClientFactory;
+ if (handler is not null)
+ {
+ var client = new HttpClient(handler) { BaseAddress = new Uri("http://broker:8080/") };
+ httpClientFactory = Substitute.For();
+ httpClientFactory.CreateClient("Broker").Returns(client);
+ }
+ else
+ {
+ httpClientFactory = Substitute.For();
+ }
+
+ 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>();
+ var httpClientFactory = Substitute.For();
+
+ 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);
+ }
+
+ /// Minimal HTTP handler for testing without real network calls.
+ 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 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);
+ }
+ }
+}
diff --git a/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs b/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs
index 385fe5d..4f3b5f6 100644
--- a/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs
+++ b/tests/Heimdall.Agent.Tests/SnapshotPipelineServiceTests.cs
@@ -10,7 +10,9 @@ public class SnapshotPipelineServiceTests
private const string FfmpegNotFound = "/usr/bin/nonexistent-ffmpeg";
private static (SnapshotPipelineService Service, AgentState State, CameraConfigStore Store, CameraStreamService Streams, FrameAnalyzerService Analyzer) CreatePipeline(
- List? cameras = null)
+ List? cameras = null,
+ AnalysisMode analysisMode = AnalysisMode.Local,
+ string? brokerUrl = null)
{
var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
var options = Options.Create(new AgentOptions
@@ -18,6 +20,8 @@ public class SnapshotPipelineServiceTests
CentralUrl = "http://localhost:5000",
SiteToken = "test",
Cameras = cameras ?? [],
+ AnalysisMode = analysisMode,
+ BrokerUrl = brokerUrl,
});
var store = new CameraConfigStore();
var streams = new CameraStreamService(Substitute.For>(), FfmpegNotFound);
@@ -26,10 +30,10 @@ public class SnapshotPipelineServiceTests
var detectionReporter = Substitute.For();
var degradationManager = new PipelineDegradationManager(Substitute.For>());
var metrics = new SystemMetricsProvider();
- var service = new SnapshotPipelineService(
+ var service = new SnapshotPipelineService(new SnapshotPipelineServiceOptions(
state, options, store, streams, analyzer, new SceneStateTracker(), statusReporter, detectionReporter,
- degradationManager, metrics,
- Substitute.For>());
+ Substitute.For>(),
+ degradationManager: degradationManager, metrics: metrics));
return (service, state, store, streams, analyzer);
}
@@ -49,7 +53,6 @@ public class SnapshotPipelineServiceTests
public async Task StartStop_WithNoCameras_DoesNotStartStreams()
{
var (service, _, _, streams, _) = CreatePipeline();
-
await service.StartAsync(CancellationToken.None);
try
{
@@ -92,13 +95,11 @@ public class SnapshotPipelineServiceTests
public async Task SnapshotWrittenToChannel_IsForwardedToAnalyzer()
{
var (service, _, _, streams, analyzer) = CreatePipeline();
-
await service.StartAsync(CancellationToken.None);
try
{
await streams.SnapshotChannel.Writer.WriteAsync(
new Snapshot(Guid.NewGuid(), DateTime.UtcNow, [1, 2, 3]));
-
var deadline = DateTime.UtcNow.AddSeconds(5);
while (service.SnapshotsProcessed == 0 && DateTime.UtcNow < deadline)
await Task.Delay(50);
@@ -120,4 +121,27 @@ public class SnapshotPipelineServiceTests
await service.StopAsync(CancellationToken.None);
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);
+ }
}