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
}
}