using System.Text.Json; using Heimdall.Application.DTOs; using Heimdall.Application.Metrics; namespace Heimdall.Agent.Services; /// /// Holds the camera assignments the agent must capture. The Central is the /// source of truth: cameras are shipped as flat camera.<id>.name|rtsp|sub_rtsp|enabled /// keys through the settings pipeline as one complete, versioned snapshot. /// A local list from AgentOptions.Cameras serves as a fallback until /// the first Central config is received. /// public sealed class CameraConfigStore { private sealed record CameraSnapshot(IReadOnlyDictionary Cameras, string Version); private CameraSnapshot? _central; private int _centralConfigurationReceived; private readonly object _updateGate = new(); private IReadOnlyList _localFallback = []; /// Raised whenever the effective camera list may have changed. public event EventHandler? Changed; /// Sets the local fallback list (used until Central config arrives). public void SetLocalFallback(IReadOnlyList cameras) { _localFallback = cameras; RaiseChanged(); } /// /// Legacy single-key setter for local callers. Remote updates must use ReplaceCentral. /// public void ApplyCameraSetting(string key, string value) { // camera.. var parts = key.Split('.', 3); if (!key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase)) return; if (parts.Length != 3 || !Guid.TryParse(parts[1], out var cameraId)) return; lock (_updateGate) { var previous = _central?.Cameras ?? new Dictionary(); var next = new Dictionary(previous); next[cameraId] = ApplyField(next.GetValueOrDefault(cameraId) ?? new AgentCameraConfig(cameraId, string.Empty, string.Empty, null, true), parts[2], value); Volatile.Write(ref _central, new CameraSnapshot(next, string.Empty)); } RaiseChanged(); } /// /// Marks the Central config as received; the local fallback is no longer /// used, even if the Central list is empty. /// public void MarkCentralReceived() { var wasUninitialized = Interlocked.CompareExchange(ref _central, new CameraSnapshot(new Dictionary(), string.Empty), null) is null; Volatile.Write(ref _centralConfigurationReceived, 1); HeimdallMetrics.SetCentralConfigurationReceived(true); if (wasUninitialized) RaiseChanged(); } /// Atomically replace the authoritative snapshot, including removals. public void ReplaceCentral(IReadOnlyDictionary settings, string? expectedVersion = null) { var version = CameraConfigVersion.Compute(settings); if (expectedVersion is not null && !string.Equals(expectedVersion, version, StringComparison.OrdinalIgnoreCase)) throw new ArgumentException("Camera configuration version mismatch", nameof(expectedVersion)); var replacement = new Dictionary(); foreach (var setting in settings.Where(s => s.Key.StartsWith("camera.", StringComparison.OrdinalIgnoreCase))) { var parts = setting.Key.Split('.', 3); if (parts.Length != 3 || !Guid.TryParse(parts[1], out var id)) throw new ArgumentException("Invalid camera setting key", nameof(settings)); replacement[id] = ApplyField(replacement.GetValueOrDefault(id) ?? new AgentCameraConfig(id, string.Empty, string.Empty, null, true), parts[2], setting.Value); } lock (_updateGate) Volatile.Write(ref _central, new CameraSnapshot(replacement, version)); Volatile.Write(ref _centralConfigurationReceived, 1); HeimdallMetrics.SetCentralConfigurationReceived(true); RaiseChanged(); } /// Effective camera assignments: Central list, or local fallback before that. public IReadOnlyList Cameras => Volatile.Read(ref _central)?.Cameras.Values.ToArray() ?? _localFallback; /// Whether a valid full snapshot has been accepted from Central. public bool HasCentralConfiguration => Volatile.Read(ref _centralConfigurationReceived) != 0; public string? CurrentVersion => Volatile.Read(ref _central)?.Version; private static AgentCameraConfig ApplyField(AgentCameraConfig existing, string field, string value) => field switch { "name" => existing with { Name = value }, "rtsp" => existing with { RtspUrl = value }, "sub_rtsp" => existing with { SubRtspUrl = value }, "enabled" => existing with { Enabled = ParseBool(value) }, "recording_enabled" => existing with { RecordingEnabled = ParseBool(value) }, "event_recording_enabled" => existing with { EventRecordingEnabled = ParseBool(value) }, "profile" => existing with { DetectionProfile = ParseProfile(value) }, _ => throw new ArgumentException($"Unknown camera configuration field: {field}", nameof(field)) }; private static DetectionProfileDto ParseProfile(string value) { var profile = JsonSerializer.Deserialize(value) ?? throw new ArgumentException("Empty detection profile"); profile.Validate(); return profile; } private static bool ParseBool(string value) => value switch { "1" => true, "0" => false, _ when bool.TryParse(value, out var parsed) => parsed, _ => throw new ArgumentException("Invalid camera enabled value", nameof(value)) }; private void RaiseChanged() => Changed?.Invoke(this, EventArgs.Empty); }