174 lines
6.4 KiB
C#
174 lines
6.4 KiB
C#
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
|
||
}
|
||
}
|