Track manual snapshots and apply versioned camera config
Heimdall Gitea / Build and tests (pull_request) Failing after 1m34s
Heimdall Gitea / Publish versioned release (pull_request) Skipped

This commit is contained in:
Arnaud Dartois committed 2026-10-23 07:30:58 +02:00
1 parent f4a8f4a668
commit 8f00f69a5f
30 files changed
+645 -63

No files matched your search

@@ -99,25 +99,38 @@ public sealed class ConfigReceiverService : BackgroundService
_connection.On("DiscoveryScanRequested", () => _scanTrigger.Trigger());
_connection.On<Guid, Guid>("ManualSnapshotRequested", async (cameraId, requestId) =>
{
if (requestId == Guid.Empty || !_cameraStore.Cameras.Any(c => c.CameraId == cameraId && c.Enabled))
return;
if (requestId == Guid.Empty) return;
try
{
if (!_cameraStore.Cameras.Any(c => c.CameraId == cameraId && c.Enabled))
{
await ReportSnapshotFailureAsync(cameraId, requestId, "camera_unavailable", stoppingToken);
return;
}
var snapshot = await _streams.CaptureNextFrameAsync(cameraId, stoppingToken).ConfigureAwait(false);
if (snapshot is null)
{
_logger.LogWarning("Manual snapshot request {RequestId} has no active frame for camera {CameraId}", requestId, cameraId);
await ReportSnapshotFailureAsync(cameraId, requestId, "no_frame", stoppingToken);
return;
}
if (!await _detectionReporter.ReportAsync(cameraId, EventType.ManualSnapshot, 1, "manual",
occurredAt: snapshot.TimestampUtc, snapshotJpeg: snapshot.JpegData,
eventId: requestId, ct: stoppingToken).ConfigureAwait(false))
{
_logger.LogWarning("Manual snapshot request {RequestId} could not be queued", requestId);
await ReportSnapshotFailureAsync(cameraId, requestId, "queue_failed", stoppingToken);
}
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { }
catch (Exception ex)
{
_logger.LogWarning(ex, "Manual snapshot request {RequestId} failed", requestId);
try { await ReportSnapshotFailureAsync(cameraId, requestId, "agent_error", stoppingToken); }
catch (Exception reportError)
{
_logger.LogWarning(reportError, "Could not report manual snapshot failure {RequestId}", requestId);
}
}
});
_connection.On("AgentUpdateRequested", () => _containerInfo.Collect().IsContainer
@@ -129,7 +142,8 @@ public sealed class ConfigReceiverService : BackgroundService
{
// Keys may identify secret settings; never log their values.
_logger.LogInformation("Config update received: {Key}", key);
if (key == "config.invalidated") await FetchFullConfigAsync(stoppingToken);
if (key == "config.invalidated" || key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase))
await FetchFullConfigAsync(stoppingToken);
else ApplySetting(key, value);
});
@@ -194,6 +208,15 @@ public sealed class ConfigReceiverService : BackgroundService
}
}
private async Task ReportSnapshotFailureAsync(Guid cameraId, Guid requestId, string code, CancellationToken ct)
{
using var http = _httpClientFactory.CreateClient("Central");
http.DefaultRequestHeaders.Add("X-API-Key", _state.ApiKey);
var url = $"{_options.CentralUrl.TrimEnd('/')}/api/cameras/{cameraId:D}/snapshot/{requestId:D}/failure";
using var response = await http.PutAsJsonAsync(url, new { code }, ct).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
if (_connection is not null)
@@ -206,8 +229,8 @@ public sealed class ConfigReceiverService : BackgroundService
private void ApplySetting(string key, string value)
{
// Camera assignments are applied live: the capture pipeline resyncs
// on every store change (start new streams, stop removed ones).
// Remote camera keys are applied only through an authoritative versioned
// full snapshot. This branch remains for local callers.
if (key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase))
{
_cameraStore.ApplyCameraSetting(key, value);
@@ -311,7 +334,7 @@ public sealed class ConfigReceiverService : BackgroundService
http.DefaultRequestHeaders.Add("X-API-Key", _state.ApiKey);
var url = $"{_options.CentralUrl.TrimEnd('/')}/api/settings/agent/{_state.AgentId}";
var response = await http.GetAsync(url, ct);
using var response = await http.GetAsync(url, ct);
if (!response.IsSuccessStatusCode)
{
@@ -326,6 +349,20 @@ public sealed class ConfigReceiverService : BackgroundService
return;
}
var version = response.Headers.TryGetValues("X-Camera-Config-Version", out var values)
? values.SingleOrDefault()
: null;
if (string.IsNullOrWhiteSpace(version))
{
_logger.LogWarning("Full camera configuration has no version header");
return;
}
// Validate and publish all camera fields together before applying
// independent agent settings. An invalid camera snapshot leaves the
// previously active assignments intact.
_cameraStore.ReplaceCentral(config, version);
_logger.LogInformation("Full configuration fetched successfully ({Count} setting(s))", config.Count);
// Apply every key through the same pipeline as live SettingChanged
@@ -333,11 +370,15 @@ public sealed class ConfigReceiverService : BackgroundService
// documentation, everything.
foreach (var kvp in config.Where(kvp => !kvp.Key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase)))
ApplySetting(kvp.Key, kvp.Value);
_cameraStore.ReplaceCentral(config);
// The Central camera list is authoritative once the full config
// arrives — even if it is empty, drop the local fallback.
_cameraStore.MarkCentralReceived();
using var ack = await http.PostAsJsonAsync(
$"{_options.CentralUrl.TrimEnd('/')}/api/settings/agent/{_state.AgentId}/camera-config-ack",
new { version }, ct).ConfigureAwait(false);
if (!ack.IsSuccessStatusCode)
_logger.LogWarning("Camera configuration ACK was rejected: {StatusCode}", ack.StatusCode);
}
catch (Exception ex)
{