diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml
index 8a16920..2435dda 100644
--- a/docker/docker-compose.yml
+++ b/docker/docker-compose.yml
@@ -61,5 +61,4 @@ volumes:
networks:
heimdall-net:
- name: heimdall-net
driver: bridge
diff --git a/skills/video-recording/SKILL.md b/skills/video-recording/SKILL.md
new file mode 100644
index 0000000..f8a5ad5
--- /dev/null
+++ b/skills/video-recording/SKILL.md
@@ -0,0 +1,18 @@
+---
+name: video-recording
+description: Implement and validate Heimdall Agent video segments, central recording storage, access checks, ranges, and retention.
+---
+
+# Heimdall video recording
+
+Recording is opt-in per camera (`RecordingEnabled`, default false). Agent capture is a separate FFmpeg process and only runs while the assigned camera's RTSP stream is already active. Keep RTSP values out of logs, command strings printed to logs, and failure responses.
+
+- Bound segment duration, size, and Agent spool usage through validated `AgentOptions`; preserve incomplete uploads for retry and make completed segment identifiers stable across retries.
+- Upload only MP4 content from the Agent API-key boundary. Validate camera assignment at the API and application boundaries. Persist metadata through `IApplicationDbContext` and use `IRecordingStorage` as the Application port.
+- Capture storage destination at upload time. Downloads must check camera access before opening the stored object. Implement byte ranges in the storage adapter rather than downloading whole objects for partial playback.
+- The CameraDetail recording list/player uses the authorized API client for metadata and same-origin `/api/recordings/{id}/content` URLs for browser Range requests. Keep the export link on that authorized endpoint and never render an arbitrary storage URL.
+- Preserve the existing recording retention policy and storage-final orphan sweep. Ensure recording rows are removed only after object deletion succeeds; do not guess destinations for legacy rows without provenance.
+- Add PostgreSQL tests for migration, metadata/idempotency, camera access, range translation, and retention semantics when touching those paths. Agent tests should cover bounded argument construction, defaults, and spool/config behavior.
+- For acceptance, build Central from this changed source in a unique disposable Compose project. Register an isolated Agent and synthetic RTSP source, enable recording, prove at least one segment reaches Central, verify scoped list/range download and unauthorized denial, then remove only that Compose project and confirm its containers/volumes/network are gone.
+
+Current product gaps are audio/event-trigger capture, an explicit Central storage quota, and validation against real cameras/codecs. Keep FEAT-02 open until these are addressed and validated.
diff --git a/src/Heimdall.Agent/AgentOptions.cs b/src/Heimdall.Agent/AgentOptions.cs
index eda76cf..98eab52 100644
--- a/src/Heimdall.Agent/AgentOptions.cs
+++ b/src/Heimdall.Agent/AgentOptions.cs
@@ -51,6 +51,17 @@ public sealed class AgentOptions
/// Directory for persisting agent identity state. Defaults to /var/lib/heimdall on Linux.
public string? StateDirectory { get; init; }
+ /// Length of completed MP4 segments created for recording-enabled cameras.
+ [Range(5, 300)]
+ public int RecordingSegmentSeconds { get; init; } = 60;
+
+ /// Upper bound for queued completed recordings kept locally while Central is unavailable.
+ [Range(typeof(long), "16777216", "107374182400")]
+ public long RecordingSpoolMaxBytes { get; init; } = 1_073_741_824;
+
+ /// FFmpeg executable used for opt-in segment recording.
+ public string RecordingFfmpegPath { get; init; } = "ffmpeg";
+
/// Max retries for agent registration (default: 5).
[Range(1, 20)]
public int RegistrationMaxRetries { get; init; } = 5;
diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs
index 61c6d94..1ceb708 100644
--- a/src/Heimdall.Agent/Program.cs
+++ b/src/Heimdall.Agent/Program.cs
@@ -171,6 +171,7 @@ builder.Services.AddSingleton(sp => new SnapshotPipelineService(new SnapshotPipe
sp.GetRequiredService(),
sp.GetRequiredService())));
builder.Services.AddHostedService(sp => sp.GetRequiredService());
+builder.Services.AddHostedService();
// Log capture & upload to Central (ticket #50)
builder.Services.AddSingleton();
diff --git a/src/Heimdall.Agent/Services/AgentCameraConfig.cs b/src/Heimdall.Agent/Services/AgentCameraConfig.cs
index e2fb29b..0603193 100644
--- a/src/Heimdall.Agent/Services/AgentCameraConfig.cs
+++ b/src/Heimdall.Agent/Services/AgentCameraConfig.cs
@@ -11,7 +11,8 @@ public sealed record AgentCameraConfig(
string RtspUrl,
string? SubRtspUrl,
bool Enabled,
- Heimdall.Application.DTOs.DetectionProfileDto? DetectionProfile = null)
+ Heimdall.Application.DTOs.DetectionProfileDto? DetectionProfile = null,
+ bool RecordingEnabled = false)
{
///
/// URL used for AI capture: the low-res sub-stream when available,
diff --git a/src/Heimdall.Agent/Services/AgentRecordingService.cs b/src/Heimdall.Agent/Services/AgentRecordingService.cs
new file mode 100644
index 0000000..647c910
--- /dev/null
+++ b/src/Heimdall.Agent/Services/AgentRecordingService.cs
@@ -0,0 +1,315 @@
+using System.Diagnostics;
+using System.Globalization;
+using System.Security.Cryptography;
+using System.Text;
+using Heimdall.Agent.Services;
+using Microsoft.Extensions.Options;
+
+namespace Heimdall.Agent;
+
+///
+/// Starts an opt-in FFmpeg segment process for enabled cameras, persists completed
+/// segments under the Agent state volume, and retries uploads until Central acknowledges them.
+///
+public sealed class AgentRecordingService : BackgroundService
+{
+ private const long MaxSegmentBytes = 100 * 1024 * 1024;
+ private static readonly TimeSpan LoopDelay = TimeSpan.FromSeconds(5);
+ private readonly CameraConfigStore _cameras;
+ private readonly CameraStreamService _streams;
+ private readonly AgentState _state;
+ private readonly AgentOptions _options;
+ private readonly IHttpClientFactory _clients;
+ private readonly ILogger _logger;
+ private readonly Dictionary _sessions = [];
+ private readonly SemaphoreSlim _lifecycle = new(1, 1);
+ private string _spoolRoot = string.Empty;
+
+ public AgentRecordingService(CameraConfigStore cameras, CameraStreamService streams, AgentState state,
+ IOptions options, IHttpClientFactory clients, ILogger logger)
+ {
+ _cameras = cameras;
+ _streams = streams;
+ _state = state;
+ _options = options.Value;
+ _clients = clients;
+ _logger = logger;
+ }
+
+ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
+ {
+ var stateDirectory = _options.StateDirectory ??
+ (OperatingSystem.IsLinux() ? "/var/lib/heimdall" : Directory.GetCurrentDirectory());
+ _spoolRoot = Path.GetFullPath(Path.Combine(stateDirectory, "recordings"));
+ Directory.CreateDirectory(_spoolRoot);
+ if (OperatingSystem.IsLinux())
+ File.SetUnixFileMode(_spoolRoot, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
+
+ try
+ {
+ while (!stoppingToken.IsCancellationRequested)
+ {
+ try
+ {
+ await ReconcileAsync(stoppingToken).ConfigureAwait(false);
+ await UploadCompletedSegmentsAsync(stoppingToken).ConfigureAwait(false);
+ await TrimSpoolAsync(stoppingToken).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; }
+ catch (Exception ex)
+ {
+ _logger.LogWarning("Recording loop failed (error type {ErrorType})", ex.GetType().Name);
+ }
+ await Task.Delay(LoopDelay, stoppingToken).ConfigureAwait(false);
+ }
+ }
+ catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { }
+ finally
+ {
+ foreach (var cameraId in _sessions.Keys.ToArray())
+ await StopSessionAsync(cameraId, CancellationToken.None).ConfigureAwait(false);
+ }
+ }
+
+ private async Task ReconcileAsync(CancellationToken ct)
+ {
+ await _lifecycle.WaitAsync(ct).ConfigureAwait(false);
+ try
+ {
+ var configured = _cameras.Cameras.ToDictionary(c => c.CameraId);
+ foreach (var (cameraId, session) in _sessions.ToArray())
+ {
+ if (!configured.TryGetValue(cameraId, out var camera) || !camera.Enabled || !camera.RecordingEnabled ||
+ camera.RtspUrl != session.RtspUrl || !_streams.IsStreamActive(cameraId) || session.Process.HasExited)
+ await StopSessionCoreAsync(cameraId, session, ct).ConfigureAwait(false);
+ }
+
+ foreach (var camera in configured.Values.Where(c => c.Enabled && c.RecordingEnabled &&
+ !string.IsNullOrWhiteSpace(c.RtspUrl)))
+ {
+ if (_streams.IsStreamActive(camera.CameraId) && !_sessions.ContainsKey(camera.CameraId))
+ StartSession(camera);
+ }
+ }
+ finally { _lifecycle.Release(); }
+ }
+
+ private void StartSession(AgentCameraConfig camera)
+ {
+ var cameraRoot = Path.Combine(_spoolRoot, camera.CameraId.ToString("N"));
+ var sessionDirectory = Path.Combine(cameraRoot, Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(sessionDirectory);
+ if (OperatingSystem.IsLinux())
+ File.SetUnixFileMode(sessionDirectory, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
+ var startedAt = DateTime.UtcNow;
+ File.WriteAllText(Path.Combine(sessionDirectory, "started-at.txt"), startedAt.ToString("O", CultureInfo.InvariantCulture));
+ var startInfo = CreateStartInfo(_options.RecordingFfmpegPath, camera.RtspUrl!, sessionDirectory,
+ _options.RecordingSegmentSeconds);
+ Process? process = null;
+ try
+ {
+ process = new Process { StartInfo = startInfo, EnableRaisingEvents = true };
+ if (!process.Start()) throw new InvalidOperationException("FFmpeg did not start");
+ var session = new RecordingSession(camera.CameraId, camera.RtspUrl!, sessionDirectory, startedAt, process);
+ _sessions[camera.CameraId] = session;
+ session.ErrorDrain = DrainStandardErrorAsync(process);
+ _logger.LogInformation("Video recording started for camera {CameraId}", camera.CameraId);
+ }
+ catch (Exception ex)
+ {
+ process?.Dispose();
+ _logger.LogWarning("Video recording could not start for camera {CameraId} (error type {ErrorType})",
+ camera.CameraId, ex.GetType().Name);
+ }
+ }
+
+ internal static ProcessStartInfo CreateStartInfo(string ffmpegPath, string rtspUrl, string sessionDirectory,
+ int segmentSeconds)
+ {
+ var info = new ProcessStartInfo
+ {
+ FileName = ffmpegPath,
+ RedirectStandardInput = true,
+ RedirectStandardError = true,
+ UseShellExecute = false,
+ CreateNoWindow = true,
+ };
+ foreach (var argument in new[]
+ {
+ "-hide_banner", "-loglevel", "error", "-rtsp_transport", "tcp", "-i", rtspUrl,
+ "-map", "0:v:0", "-c:v", "copy", "-f", "segment", "-segment_time",
+ segmentSeconds.ToString(CultureInfo.InvariantCulture), "-segment_format", "mp4",
+ "-reset_timestamps", "1", "-segment_list", Path.Combine(sessionDirectory, "segments.csv"),
+ "-segment_list_type", "csv", "-segment_list_size", "10000",
+ Path.Combine(sessionDirectory, "segment-%06d.mp4")
+ }) info.ArgumentList.Add(argument);
+ return info;
+ }
+
+ private static async Task DrainStandardErrorAsync(Process process)
+ {
+ try
+ {
+ while (await process.StandardError.ReadLineAsync().ConfigureAwait(false) is not null) { }
+ }
+ catch (IOException) { }
+ catch (ObjectDisposedException) { }
+ }
+
+ private async Task StopSessionAsync(Guid cameraId, CancellationToken ct)
+ {
+ await _lifecycle.WaitAsync(ct).ConfigureAwait(false);
+ try
+ {
+ if (_sessions.TryGetValue(cameraId, out var session))
+ await StopSessionCoreAsync(cameraId, session, ct).ConfigureAwait(false);
+ }
+ finally { _lifecycle.Release(); }
+ }
+
+ private async Task StopSessionCoreAsync(Guid cameraId, RecordingSession session, CancellationToken ct)
+ {
+ _sessions.Remove(cameraId);
+ try
+ {
+ if (!session.Process.HasExited)
+ {
+ try { await session.Process.StandardInput.WriteLineAsync("q").ConfigureAwait(false); }
+ catch (IOException) { }
+ try { await session.Process.WaitForExitAsync(ct).WaitAsync(TimeSpan.FromSeconds(5), ct).ConfigureAwait(false); }
+ catch (TimeoutException) { session.Process.Kill(entireProcessTree: true); }
+ catch (InvalidOperationException) { }
+ }
+ if (session.ErrorDrain is not null) await session.ErrorDrain.ConfigureAwait(false);
+ _logger.LogInformation("Video recording stopped for camera {CameraId}", cameraId);
+ }
+ catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; }
+ catch (Exception ex)
+ {
+ _logger.LogDebug("FFmpeg cleanup failed for camera {CameraId} (error type {ErrorType})", cameraId, ex.GetType().Name);
+ }
+ finally { session.Process.Dispose(); }
+ }
+
+ private async Task UploadCompletedSegmentsAsync(CancellationToken ct)
+ {
+ if (!Directory.Exists(_spoolRoot)) return;
+ foreach (var manifest in Directory.EnumerateFiles(_spoolRoot, "segments.csv", SearchOption.AllDirectories))
+ {
+ ct.ThrowIfCancellationRequested();
+ if (!Guid.TryParseExact(Directory.GetParent(Directory.GetParent(manifest)!.FullName)!.Name, "N", out var cameraId))
+ continue;
+ DateTime startedAt;
+ try
+ {
+ startedAt = DateTime.Parse(File.ReadAllText(Path.Combine(Path.GetDirectoryName(manifest)!, "started-at.txt")),
+ CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind).ToUniversalTime();
+ }
+ catch (IOException) { continue; }
+ catch (FormatException) { continue; }
+ string[] rows;
+ try { rows = await File.ReadAllLinesAsync(manifest, ct).ConfigureAwait(false); }
+ catch (IOException) { continue; }
+ foreach (var row in rows)
+ {
+ var fields = row.Split(',');
+ if (fields.Length < 3) continue;
+ var fileName = Path.GetFileName(fields[0]);
+ if (!fileName.StartsWith("segment-", StringComparison.Ordinal) || !fileName.EndsWith(".mp4", StringComparison.Ordinal) ||
+ !double.TryParse(fields[1], CultureInfo.InvariantCulture, out var startSeconds) ||
+ !double.TryParse(fields[2], CultureInfo.InvariantCulture, out var endSeconds)) continue;
+ var duration = endSeconds - startSeconds;
+ if (duration is < 1 or > 300 || !double.IsFinite(duration) || !double.IsFinite(startSeconds)) continue;
+ var path = Path.Combine(Path.GetDirectoryName(manifest)!, fileName);
+ if (!File.Exists(path)) continue;
+ var info = new FileInfo(path);
+ if (info.Length > MaxSegmentBytes)
+ {
+ _logger.LogWarning("Dropping oversized video segment for camera {CameraId} ({SizeBytes} bytes)", cameraId, info.Length);
+ info.Delete();
+ continue;
+ }
+ await UploadSegmentAsync(cameraId, path, startedAt.AddSeconds(startSeconds), duration, ct).ConfigureAwait(false);
+ }
+ }
+ }
+
+ private async Task UploadSegmentAsync(Guid cameraId, string path, DateTime timestamp, double duration, CancellationToken ct)
+ {
+ var relativePath = Path.GetRelativePath(_spoolRoot, path).Replace(Path.DirectorySeparatorChar, '/');
+ var hash = SHA256.HashData(Encoding.UTF8.GetBytes(relativePath));
+ var recordingId = new Guid(hash.AsSpan(0, 16));
+ var url = $"api/cameras/{cameraId:D}/recordings/{recordingId:D}/content?timestamp={Uri.EscapeDataString(timestamp.ToString("O", CultureInfo.InvariantCulture))}&durationSeconds={duration.ToString(CultureInfo.InvariantCulture)}";
+ try
+ {
+ using var request = new HttpRequestMessage(HttpMethod.Put, url);
+ request.Headers.Add("X-API-Key", _state.ApiKey);
+ await using var input = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,
+ 128 * 1024, FileOptions.Asynchronous | FileOptions.SequentialScan);
+ request.Content = new StreamContent(input);
+ request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("video/mp4");
+ request.Content.Headers.ContentLength = input.Length;
+ using var response = await _clients.CreateClient("Central").SendAsync(request,
+ HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false);
+ if (!response.IsSuccessStatusCode)
+ {
+ _logger.LogWarning("Video segment upload returned HTTP {StatusCode} for camera {CameraId}",
+ (int)response.StatusCode, cameraId);
+ return;
+ }
+ input.Close();
+ File.Delete(path);
+ }
+ catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; }
+ catch (HttpRequestException ex)
+ {
+ _logger.LogWarning("Video segment upload failed for camera {CameraId} (error type {ErrorType})",
+ cameraId, ex.GetType().Name);
+ }
+ catch (IOException ex)
+ {
+ _logger.LogWarning("Video segment could not be read or removed for camera {CameraId} (error type {ErrorType})",
+ cameraId, ex.GetType().Name);
+ }
+ }
+
+ private async Task TrimSpoolAsync(CancellationToken ct)
+ {
+ var ready = new List();
+ foreach (var manifest in Directory.EnumerateFiles(_spoolRoot, "segments.csv", SearchOption.AllDirectories))
+ {
+ string[] rows;
+ try { rows = await File.ReadAllLinesAsync(manifest, ct).ConfigureAwait(false); }
+ catch (IOException) { continue; }
+ foreach (var row in rows)
+ {
+ var fileName = Path.GetFileName(row.Split(',')[0]);
+ if (!fileName.StartsWith("segment-", StringComparison.Ordinal) || !fileName.EndsWith(".mp4", StringComparison.Ordinal)) continue;
+ var path = Path.Combine(Path.GetDirectoryName(manifest)!, fileName);
+ if (File.Exists(path)) ready.Add(new FileInfo(path));
+ }
+ }
+ var total = ready.Sum(file => file.Length);
+ foreach (var file in ready.OrderBy(file => file.LastWriteTimeUtc))
+ {
+ if (total <= _options.RecordingSpoolMaxBytes) break;
+ ct.ThrowIfCancellationRequested();
+ var size = file.Length;
+ try
+ {
+ file.Delete();
+ total -= size;
+ _logger.LogWarning("Dropping oldest queued video segment for camera {CameraId}; local recording spool reached its configured limit",
+ Path.GetFileName(Path.GetDirectoryName(Path.GetDirectoryName(file.FullName))));
+ }
+ catch (IOException) { }
+ catch (UnauthorizedAccessException) { }
+ }
+ }
+
+ private sealed record RecordingSession(Guid CameraId, string RtspUrl, string Directory,
+ DateTime StartedAt, Process Process)
+ {
+ public Task? ErrorDrain { get; set; }
+ }
+}
diff --git a/src/Heimdall.Agent/Services/CameraConfigStore.cs b/src/Heimdall.Agent/Services/CameraConfigStore.cs
index 3913e87..fb94add 100644
--- a/src/Heimdall.Agent/Services/CameraConfigStore.cs
+++ b/src/Heimdall.Agent/Services/CameraConfigStore.cs
@@ -102,6 +102,7 @@ public sealed class CameraConfigStore
"rtsp" => existing with { RtspUrl = value },
"sub_rtsp" => existing with { SubRtspUrl = value },
"enabled" => existing with { Enabled = ParseBool(value) },
+ "recording_enabled" => existing with { RecordingEnabled = ParseBool(value) },
"profile" => existing with { DetectionProfile = ParseProfile(value) },
_ => throw new ArgumentException($"Unknown camera configuration field: {field}", nameof(field))
};
diff --git a/src/Heimdall.Application/Cameras/Commands/CreateCamera/CreateCameraCommand.cs b/src/Heimdall.Application/Cameras/Commands/CreateCamera/CreateCameraCommand.cs
index e0779d5..30f1abc 100644
--- a/src/Heimdall.Application/Cameras/Commands/CreateCamera/CreateCameraCommand.cs
+++ b/src/Heimdall.Application/Cameras/Commands/CreateCamera/CreateCameraCommand.cs
@@ -53,5 +53,5 @@ public class CreateCameraCommandHandler : IRequestHandler>;
+ Guid? ActorId = null,
+ bool? RecordingEnabled = null) : IRequest>;
public class UpdateCameraCommandHandler : IRequestHandler>
{
@@ -48,11 +49,14 @@ public class UpdateCameraCommandHandler : IRequestHandlerStorage operations for recording media, bound to the captured destination.
+public interface IRecordingStorage
+{
+ StorageLocation CaptureCurrentLocation();
+ Task UploadAsync(string key, Stream content, string contentType, StorageLocation location, CancellationToken ct = default);
+ Task DownloadAsync(string key, StorageLocation location, CancellationToken ct = default);
+ Task DownloadRangeAsync(string key, StorageLocation location, long start, long endInclusive,
+ CancellationToken ct = default);
+}
diff --git a/src/Heimdall.Application/Common/IStorageProvider.cs b/src/Heimdall.Application/Common/IStorageProvider.cs
index b413c94..b13b8fc 100644
--- a/src/Heimdall.Application/Common/IStorageProvider.cs
+++ b/src/Heimdall.Application/Common/IStorageProvider.cs
@@ -20,6 +20,9 @@ public interface IStorageProvider
/// Open a stream for reading a stored object. Null when missing.
Task DownloadAsync(string key, CancellationToken ct = default);
+ /// Open a single inclusive byte range without downloading the rest of the object.
+ Task DownloadRangeAsync(string key, long start, long endInclusive, CancellationToken ct = default);
+
/// Delete a single object. No-op when missing.
Task DeleteAsync(string key, CancellationToken ct = default);
diff --git a/src/Heimdall.Application/DTOs/CameraDto.cs b/src/Heimdall.Application/DTOs/CameraDto.cs
index 46bbc52..9e980a0 100644
--- a/src/Heimdall.Application/DTOs/CameraDto.cs
+++ b/src/Heimdall.Application/DTOs/CameraDto.cs
@@ -15,7 +15,8 @@ public record UpdateCameraRequest(
CameraStatus? Status,
string? Manufacturer = null,
string? Model = null,
- DetectionProfileDto? DetectionProfile = null);
+ DetectionProfileDto? DetectionProfile = null,
+ bool? RecordingEnabled = null);
/// Camera response including all discovery and stream test metadata.
public record CameraResponse(
@@ -45,4 +46,5 @@ public record CameraResponse(
bool HasPtz,
bool HasAudio,
bool HasMotionDetection,
- DateTime CreatedAt);
+ DateTime CreatedAt,
+ bool RecordingEnabled = false);
diff --git a/src/Heimdall.Application/Groups/Queries/GetCamerasByGroup/GetCamerasByGroupQuery.cs b/src/Heimdall.Application/Groups/Queries/GetCamerasByGroup/GetCamerasByGroupQuery.cs
index 754b47e..92f12bd 100644
--- a/src/Heimdall.Application/Groups/Queries/GetCamerasByGroup/GetCamerasByGroupQuery.cs
+++ b/src/Heimdall.Application/Groups/Queries/GetCamerasByGroup/GetCamerasByGroupQuery.cs
@@ -45,10 +45,10 @@ public class GetCamerasByGroupHandler : IRequestHandler>.Success(
new PagedResult(items, total, request.Page, request.PageSize));
}
-}
\ No newline at end of file
+}
diff --git a/src/Heimdall.Application/Recordings/Commands/UploadRecording/UploadRecordingCommand.cs b/src/Heimdall.Application/Recordings/Commands/UploadRecording/UploadRecordingCommand.cs
new file mode 100644
index 0000000..afc8fc5
--- /dev/null
+++ b/src/Heimdall.Application/Recordings/Commands/UploadRecording/UploadRecordingCommand.cs
@@ -0,0 +1,69 @@
+using Heimdall.Application.Common;
+using Heimdall.Application.Recordings;
+using Heimdall.Domain.Entities;
+using Heimdall.Domain.Enums;
+using MediatR;
+using Microsoft.EntityFrameworkCore;
+
+namespace Heimdall.Application.Recordings.Commands.UploadRecording;
+
+public sealed record UploadRecordingCommand(
+ Guid AgentId,
+ Guid CameraId,
+ Guid RecordingId,
+ DateTime Timestamp,
+ double DurationSeconds,
+ long SizeBytes,
+ Stream Content) : IRequest>;
+
+public sealed class UploadRecordingHandler(
+ IApplicationDbContext db,
+ IRecordingStorage storage) : IRequestHandler>
+{
+ public async Task> Handle(UploadRecordingCommand request, CancellationToken ct)
+ {
+ if (request.AgentId == Guid.Empty || request.CameraId == Guid.Empty || request.RecordingId == Guid.Empty ||
+ request.DurationSeconds is < 1 or > 300 || !double.IsFinite(request.DurationSeconds) ||
+ request.SizeBytes is < 12 or > 100 * 1024 * 1024 || request.Content.CanSeek && request.Content.Length != request.SizeBytes)
+ return ServiceResult.Failure("Invalid recording segment metadata", 400);
+
+ var camera = await db.Cameras.AsNoTracking()
+ .Where(c => c.Id == request.CameraId && !c.IsDeleted)
+ .Select(c => new { c.Id, c.AgentId, c.StoragePolicyId })
+ .SingleOrDefaultAsync(ct).ConfigureAwait(false);
+ if (camera?.AgentId != request.AgentId)
+ return ServiceResult.NotFound("Camera not found");
+
+ var existing = await db.Recordings.AsNoTracking()
+ .Where(r => r.Id == request.RecordingId)
+ .Select(r => new { r.Id, r.CameraId, r.Timestamp, r.DurationSeconds, r.SizeBytes })
+ .SingleOrDefaultAsync(ct).ConfigureAwait(false);
+ if (existing is not null)
+ return existing.CameraId == request.CameraId
+ ? ServiceResult.Success(Map(existing.Id, existing.CameraId, existing.Timestamp, existing.DurationSeconds, existing.SizeBytes))
+ : ServiceResult.Conflict("Recording identifier already belongs to another camera");
+
+ var timestamp = CameraEvent.NormalizeOccurredAt(request.Timestamp);
+ var location = storage.CaptureCurrentLocation();
+ var key = $"recordings/{request.CameraId:D}/{request.RecordingId:D}.mp4";
+ if (request.Content.CanSeek) request.Content.Position = 0;
+ await storage.UploadAsync(key, request.Content, "video/mp4", location, ct).ConfigureAwait(false);
+
+ var recording = new Recording(request.CameraId, timestamp, request.DurationSeconds,
+ key, request.SizeBytes, location.Provider, location, camera.StoragePolicyId, request.RecordingId);
+ db.Recordings.Add(recording);
+ await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
+
+ var end = timestamp.AddSeconds(request.DurationSeconds);
+ await db.CameraEvents
+ .Where(e => e.CameraId == request.CameraId && e.RecordingId == null && e.OccurredAt >= timestamp && e.OccurredAt < end)
+ .ExecuteUpdateAsync(setters => setters.SetProperty(e => e.RecordingId, recording.Id), ct)
+ .ConfigureAwait(false);
+
+ return ServiceResult.Success(Map(recording.Id, recording.CameraId,
+ recording.Timestamp, recording.DurationSeconds, recording.SizeBytes));
+ }
+
+ private static RecordingDto Map(Guid id, Guid cameraId, DateTime timestamp, double duration, long size) =>
+ new(id, cameraId, timestamp, duration, size, $"/api/recordings/{id:D}/content");
+}
diff --git a/src/Heimdall.Application/Recordings/Queries/GetCameraRecordings/GetCameraRecordingsQuery.cs b/src/Heimdall.Application/Recordings/Queries/GetCameraRecordings/GetCameraRecordingsQuery.cs
new file mode 100644
index 0000000..20a4c74
--- /dev/null
+++ b/src/Heimdall.Application/Recordings/Queries/GetCameraRecordings/GetCameraRecordingsQuery.cs
@@ -0,0 +1,37 @@
+using Heimdall.Application.Common;
+using Heimdall.Application.DTOs;
+using Heimdall.Application.Recordings;
+using Heimdall.Application.Services;
+using MediatR;
+using Microsoft.EntityFrameworkCore;
+
+namespace Heimdall.Application.Recordings.Queries.GetCameraRecordings;
+
+public sealed record GetCameraRecordingsQuery(Guid CameraId, Guid UserId, DateTime? From, DateTime? To, int Page, int PageSize)
+ : IRequest>>;
+
+public sealed class GetCameraRecordingsHandler(
+ IApplicationDbContext db,
+ ICameraAccessService access) : IRequestHandler>>
+{
+ public async Task>> Handle(GetCameraRecordingsQuery request, CancellationToken ct)
+ {
+ if (request.Page < 1 || request.PageSize is < 1 or > 100 ||
+ request.From.HasValue && request.To.HasValue && request.From >= request.To)
+ return ServiceResult>.Failure("Invalid recording page or time range", 400);
+ if (!await access.HasCameraAccessAsync(request.UserId, request.CameraId, ct).ConfigureAwait(false))
+ return ServiceResult>.NotFound("Camera not found");
+
+ var query = db.Recordings.AsNoTracking().Where(r => r.CameraId == request.CameraId);
+ if (request.From is DateTime from) query = query.Where(r => r.Timestamp >= from);
+ if (request.To is DateTime to) query = query.Where(r => r.Timestamp < to);
+ var total = await query.CountAsync(ct).ConfigureAwait(false);
+ var rows = await query.OrderByDescending(r => r.Timestamp)
+ .Skip((request.Page - 1) * request.PageSize).Take(request.PageSize)
+ .Select(r => new { r.Id, r.CameraId, r.Timestamp, r.DurationSeconds, r.SizeBytes })
+ .ToListAsync(ct).ConfigureAwait(false);
+ var items = rows.Select(r => new RecordingDto(r.Id, r.CameraId, r.Timestamp,
+ r.DurationSeconds, r.SizeBytes, $"/api/recordings/{r.Id:D}/content")).ToArray();
+ return ServiceResult>.Success(new(items, total, request.Page, request.PageSize));
+ }
+}
diff --git a/src/Heimdall.Application/Recordings/Queries/GetRecordingContent/GetRecordingContentQuery.cs b/src/Heimdall.Application/Recordings/Queries/GetRecordingContent/GetRecordingContentQuery.cs
new file mode 100644
index 0000000..fd557b8
--- /dev/null
+++ b/src/Heimdall.Application/Recordings/Queries/GetRecordingContent/GetRecordingContentQuery.cs
@@ -0,0 +1,64 @@
+using Heimdall.Application.Common;
+using Heimdall.Application.Recordings;
+using Heimdall.Application.Services;
+using MediatR;
+using Microsoft.EntityFrameworkCore;
+
+namespace Heimdall.Application.Recordings.Queries.GetRecordingContent;
+
+public sealed record GetRecordingContentQuery(Guid RecordingId, Guid UserId,
+ long? RangeStart = null, long? RangeEnd = null, long? SuffixLength = null)
+ : IRequest>;
+
+public sealed class GetRecordingContentHandler(
+ IApplicationDbContext db,
+ ICameraAccessService access,
+ IRecordingStorage storage) : IRequestHandler>
+{
+ public async Task> Handle(GetRecordingContentQuery request, CancellationToken ct)
+ {
+ var recording = await db.Recordings.AsNoTracking()
+ .Where(r => r.Id == request.RecordingId)
+ .Select(r => new
+ {
+ r.CameraId, r.StoragePath, r.SizeBytes, r.StorageProvider,
+ r.StorageRoot, r.StorageEndpoint, r.StorageBucket, r.StorageLocationCaptured
+ })
+ .SingleOrDefaultAsync(ct).ConfigureAwait(false);
+ if (recording is null || !recording.StorageLocationCaptured ||
+ !await access.HasCameraAccessAsync(request.UserId, recording.CameraId, ct).ConfigureAwait(false))
+ return ServiceResult.NotFound("Recording not found");
+
+ var location = new Heimdall.Domain.Entities.StorageLocation(recording.StorageProvider,
+ recording.StorageRoot, recording.StorageEndpoint, recording.StorageBucket);
+ if (!location.IsComplete)
+ return ServiceResult.NotFound("Recording not found");
+ if (request.SuffixLength is <= 0 || request.RangeStart is < 0 || request.RangeEnd is < 0 ||
+ request.RangeStart.HasValue && request.SuffixLength.HasValue)
+ return ServiceResult.Failure("Invalid byte range", 416);
+
+ var isPartial = request.RangeStart.HasValue || request.SuffixLength.HasValue;
+ var start = request.SuffixLength is long suffix
+ ? Math.Max(0, recording.SizeBytes - suffix)
+ : request.RangeStart ?? 0;
+ var end = Math.Min(request.RangeEnd ?? recording.SizeBytes - 1, recording.SizeBytes - 1);
+ if (isPartial && (start >= recording.SizeBytes || end < start))
+ return ServiceResult.Failure("Byte range is not satisfiable", 416);
+
+ Stream? stream;
+ try
+ {
+ stream = isPartial
+ ? await storage.DownloadRangeAsync(recording.StoragePath, location, start, end, ct).ConfigureAwait(false)
+ : await storage.DownloadAsync(recording.StoragePath, location, ct).ConfigureAwait(false);
+ }
+ catch (ArgumentOutOfRangeException)
+ {
+ return ServiceResult.Failure("Byte range is not satisfiable", 416);
+ }
+ return stream is null
+ ? ServiceResult.NotFound("Recording content not found")
+ : ServiceResult.Success(new(stream, recording.SizeBytes, start,
+ isPartial ? end - start + 1 : recording.SizeBytes, isPartial, "video/mp4"));
+ }
+}
diff --git a/src/Heimdall.Application/Recordings/RecordingDtos.cs b/src/Heimdall.Application/Recordings/RecordingDtos.cs
new file mode 100644
index 0000000..fd61d7c
--- /dev/null
+++ b/src/Heimdall.Application/Recordings/RecordingDtos.cs
@@ -0,0 +1,12 @@
+namespace Heimdall.Application.Recordings;
+
+public sealed record RecordingDto(
+ Guid Id,
+ Guid CameraId,
+ DateTime Timestamp,
+ double DurationSeconds,
+ long SizeBytes,
+ string ContentUrl);
+
+public sealed record RecordingContent(Stream Stream, long SizeBytes, long Offset, long ContentLength,
+ bool IsPartial, string ContentType);
diff --git a/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs b/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs
index db7e3fb..5b97fd2 100644
--- a/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs
+++ b/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs
@@ -121,6 +121,7 @@ public class GetEffectiveAgentConfigQueryHandler
if (!string.IsNullOrWhiteSpace(camera.SubRtspUrl))
config[$"{prefix}.sub_rtsp"] = camera.SubRtspUrl;
config[$"{prefix}.enabled"] = camera.Status != CameraStatus.Disabled ? "true" : "false";
+ config[$"{prefix}.recording_enabled"] = camera.RecordingEnabled ? "true" : "false";
}
return ServiceResult>.Success(config);
diff --git a/src/Heimdall.Domain/Entities/Camera.cs b/src/Heimdall.Domain/Entities/Camera.cs
index 2dce07c..fac65dd 100644
--- a/src/Heimdall.Domain/Entities/Camera.cs
+++ b/src/Heimdall.Domain/Entities/Camera.cs
@@ -13,6 +13,8 @@ public class Camera : Entity, IAuditableEntity, ISoftDeletable
public string? Model { get; private set; }
public string? RtspUrl { get; private set; }
public CameraStatus Status { get; private set; } = CameraStatus.Disabled;
+ /// Whether the assigned Agent stores bounded video segments for this camera.
+ public bool RecordingEnabled { get; private set; }
// ── Discovery ───────────────────────────────────────────────────
/// How this camera was discovered (manual, ONVIF, mDNS, etc.).
@@ -111,6 +113,7 @@ public class Camera : Entity, IAuditableEntity, ISoftDeletable
}
public void SetStatus(CameraStatus status) => Status = status;
+ public void SetRecordingEnabled(bool enabled) => RecordingEnabled = enabled;
public void SetCapabilities(bool ptz, bool audio, bool motion)
{
diff --git a/src/Heimdall.Domain/Entities/Recording.cs b/src/Heimdall.Domain/Entities/Recording.cs
index e6bc01d..fe7aff9 100644
--- a/src/Heimdall.Domain/Entities/Recording.cs
+++ b/src/Heimdall.Domain/Entities/Recording.cs
@@ -37,8 +37,9 @@ public class Recording : Entity, IAuditableEntity
long sizeBytes,
StorageProvider storageProvider,
StorageLocation storageLocation,
- Guid? storagePolicyId = null)
- : base(Guid.NewGuid())
+ Guid? storagePolicyId = null,
+ Guid? id = null)
+ : base(id ?? Guid.NewGuid())
{
CameraId = cameraId;
Timestamp = timestamp;
diff --git a/src/Heimdall.Infrastructure/Data/Configurations/CameraConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/CameraConfiguration.cs
index 7ac1afe..9648181 100644
--- a/src/Heimdall.Infrastructure/Data/Configurations/CameraConfiguration.cs
+++ b/src/Heimdall.Infrastructure/Data/Configurations/CameraConfiguration.cs
@@ -35,6 +35,10 @@ public class CameraConfiguration : IEntityTypeConfiguration
.IsRequired()
.IsUnicode(false);
+ builder.Property(c => c.RecordingEnabled)
+ .HasDefaultValue(false)
+ .IsRequired();
+
// ── Discovery ───────────────────────────────────────────────
builder.Property(c => c.DiscoveryMethod)
.HasConversion()
diff --git a/src/Heimdall.Infrastructure/DependencyInjection.cs b/src/Heimdall.Infrastructure/DependencyInjection.cs
index 64f5af7..6973e32 100644
--- a/src/Heimdall.Infrastructure/DependencyInjection.cs
+++ b/src/Heimdall.Infrastructure/DependencyInjection.cs
@@ -52,6 +52,7 @@ public static class DependencyInjection
services.AddSingleton();
services.AddScoped(sp => sp.GetRequiredService());
services.AddScoped(sp => sp.GetRequiredService());
+ services.AddScoped();
// Health checks (spec 13.2) — PostgreSQL + dépendances optionnelles.
services.AddHealthChecks()
diff --git a/src/Heimdall.Infrastructure/Migrations/20261104202743_AddCameraRecordingEnabled.Designer.cs b/src/Heimdall.Infrastructure/Migrations/20261104202743_AddCameraRecordingEnabled.Designer.cs
new file mode 100644
index 0000000..8fae6a1
--- /dev/null
+++ b/src/Heimdall.Infrastructure/Migrations/20261104202743_AddCameraRecordingEnabled.Designer.cs
@@ -0,0 +1,2892 @@
+//
+using System;
+using Heimdall.Infrastructure.Data;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
+
+#nullable disable
+
+namespace Heimdall.Infrastructure.Migrations
+{
+ [DbContext(typeof(AppDbContext))]
+ [Migration("20261104202743_AddCameraRecordingEnabled")]
+ partial class AddCameraRecordingEnabled
+ {
+ ///
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasAnnotation("ProductVersion", "10.0.13")
+ .HasAnnotation("Relational:MaxIdentifierLength", 63);
+
+ NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("ApiKeyHash")
+ .HasMaxLength(128)
+ .IsUnicode(false)
+ .HasColumnType("character varying(128)");
+
+ b.Property("ApiKeyPrefix")
+ .HasMaxLength(8)
+ .IsUnicode(false)
+ .HasColumnType("character varying(8)");
+
+ b.Property("Arch")
+ .HasColumnType("text");
+
+ b.Property("ContainerCpuLimit")
+ .HasColumnType("bigint");
+
+ b.Property("ContainerId")
+ .HasColumnType("text");
+
+ b.Property("ContainerImage")
+ .HasColumnType("text");
+
+ b.Property("ContainerMemoryLimitBytes")
+ .HasColumnType("bigint");
+
+ b.Property("CpuArchitecture")
+ .HasColumnType("text");
+
+ b.Property("CpuCacheBytes")
+ .HasColumnType("bigint");
+
+ b.Property("CpuCores")
+ .HasColumnType("integer");
+
+ b.Property("CpuFlags")
+ .HasColumnType("text");
+
+ b.Property("CpuFrequencyMhz")
+ .HasColumnType("double precision");
+
+ b.Property("CpuModel")
+ .HasColumnType("text");
+
+ b.Property("CpuUsagePercent")
+ .HasColumnType("double precision");
+
+ b.Property("CpuVendor")
+ .HasColumnType("text");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.Property("DeletedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("DiskInventoryJson")
+ .HasColumnType("text");
+
+ b.Property("DiskUsagePercent")
+ .HasColumnType("double precision");
+
+ b.Property("GpuInventoryJson")
+ .HasColumnType("text");
+
+ b.Property("GpuLoadPercent")
+ .HasColumnType("double precision");
+
+ b.Property("GpuName")
+ .HasMaxLength(200)
+ .IsUnicode(false)
+ .HasColumnType("character varying(200)");
+
+ b.Property("GpuType")
+ .IsRequired()
+ .HasMaxLength(20)
+ .IsUnicode(false)
+ .HasColumnType("character varying(20)");
+
+ b.Property("HasGpu")
+ .HasColumnType("boolean");
+
+ b.Property("Hostname")
+ .IsRequired()
+ .HasMaxLength(255)
+ .IsUnicode(false)
+ .HasColumnType("character varying(255)");
+
+ b.Property("InventoryObservedAtUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("IsDeleted")
+ .HasColumnType("boolean");
+
+ b.Property("KernelVersion")
+ .HasColumnType("text");
+
+ b.Property("LastAppliedCameraConfigAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("LastAppliedCameraConfigVersion")
+ .HasMaxLength(64)
+ .IsUnicode(false)
+ .HasColumnType("character varying(64)");
+
+ b.Property("LastHeartbeat")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("LogicalCores")
+ .HasColumnType("integer");
+
+ b.Property("MemAvailableBytes")
+ .HasColumnType("bigint");
+
+ b.Property("MemTotalBytes")
+ .HasColumnType("bigint");
+
+ b.Property("MemoryMb")
+ .HasColumnType("bigint");
+
+ b.Property("MemoryUsageBytes")
+ .HasColumnType("bigint");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(200)
+ .IsUnicode(false)
+ .HasColumnType("character varying(200)");
+
+ b.Property("NetworkInterfacesJson")
+ .HasColumnType("text");
+
+ b.Property("OsName")
+ .HasColumnType("text");
+
+ b.Property("PhysicalCores")
+ .HasColumnType("integer");
+
+ b.Property("PublicIp")
+ .HasMaxLength(45)
+ .IsUnicode(false)
+ .HasColumnType("character varying(45)");
+
+ b.Property("SiteId")
+ .HasColumnType("uuid");
+
+ b.Property("Status")
+ .IsRequired()
+ .HasMaxLength(20)
+ .IsUnicode(false)
+ .HasColumnType("character varying(20)");
+
+ b.Property("SwapFreeBytes")
+ .HasColumnType("bigint");
+
+ b.Property("SwapTotalBytes")
+ .HasColumnType("bigint");
+
+ b.Property("TemperatureJson")
+ .HasColumnType("text");
+
+ b.Property("ThreadsPerCore")
+ .HasColumnType("integer");
+
+ b.Property("UpdatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.Property("UptimeMachineSeconds")
+ .HasColumnType("bigint");
+
+ b.Property("UptimeSeconds")
+ .HasColumnType("bigint");
+
+ b.Property("Version")
+ .IsRequired()
+ .HasMaxLength(50)
+ .IsUnicode(false)
+ .HasColumnType("character varying(50)");
+
+ b.Property("VramMb")
+ .HasColumnType("bigint");
+
+ b.Property("VramUsageBytes")
+ .HasColumnType("bigint");
+
+ b.HasKey("Id");
+
+ b.HasIndex("LastHeartbeat")
+ .HasFilter("\"Status\" = 'Online'");
+
+ b.HasIndex("SiteId");
+
+ b.ToTable("agents", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.AgentLogEntry", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("AgentId")
+ .HasColumnType("uuid");
+
+ b.Property("Exception")
+ .HasMaxLength(4000)
+ .HasColumnType("character varying(4000)");
+
+ b.Property("Level")
+ .IsRequired()
+ .HasMaxLength(20)
+ .IsUnicode(false)
+ .HasColumnType("character varying(20)");
+
+ b.Property("Message")
+ .IsRequired()
+ .HasMaxLength(2000)
+ .HasColumnType("character varying(2000)");
+
+ b.Property("Source")
+ .HasMaxLength(200)
+ .IsUnicode(false)
+ .HasColumnType("character varying(200)");
+
+ b.Property("TimestampUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AgentId", "TimestampUtc");
+
+ b.ToTable("agent_log_entries", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.AgentMetricSample", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid")
+ .HasDefaultValueSql("gen_random_uuid()");
+
+ b.Property("AgentId")
+ .HasColumnType("uuid");
+
+ b.Property("CapturedAtUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("CpuUsagePercent")
+ .HasColumnType("double precision");
+
+ b.Property("DiskUsagePercent")
+ .HasColumnType("double precision");
+
+ b.Property("GpuTemperatureCelsius")
+ .HasColumnType("double precision");
+
+ b.Property("GpuUtilizationPercent")
+ .HasColumnType("double precision");
+
+ b.Property("InventoryObservedAtUtc")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("LogicalCores")
+ .HasColumnType("integer");
+
+ b.Property("MemAvailableBytes")
+ .HasColumnType("bigint");
+
+ b.Property("MemTotalBytes")
+ .HasColumnType("bigint");
+
+ b.Property("MemoryUsageBytes")
+ .HasColumnType("bigint");
+
+ b.Property("SiteId")
+ .HasColumnType("uuid");
+
+ b.Property("TemperatureJson")
+ .HasColumnType("text");
+
+ b.HasKey("Id");
+
+ b.HasIndex("CapturedAtUtc");
+
+ b.HasIndex("AgentId", "CapturedAtUtc")
+ .IsUnique();
+
+ b.HasIndex("SiteId", "CapturedAtUtc");
+
+ b.ToTable("agent_metric_samples", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("AgentId")
+ .HasColumnType("uuid")
+ .HasColumnName("agent_id");
+
+ b.Property("CreatedAt")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("created_at");
+
+ b.Property("Key")
+ .IsRequired()
+ .HasMaxLength(200)
+ .HasColumnType("character varying(200)")
+ .HasColumnName("key");
+
+ b.Property("UpdatedAt")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("updated_at");
+
+ b.Property("Value")
+ .IsRequired()
+ .HasColumnType("text")
+ .HasColumnName("value");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AgentId", "Key")
+ .IsUnique();
+
+ b.ToTable("agent_settings", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.AnalysisJob", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("AssignedAgentId")
+ .HasColumnType("uuid");
+
+ b.Property("AttemptId")
+ .HasColumnType("uuid");
+
+ b.Property("CameraId")
+ .HasColumnType("uuid");
+
+ b.Property("CompletedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("CreatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("DispatchedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("ErrorMessage")
+ .HasMaxLength(2000)
+ .HasColumnType("character varying(2000)");
+
+ b.Property("JobType")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)");
+
+ b.Property("MaxExecutionTime")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint")
+ .HasDefaultValue(3000000000L);
+
+ b.Property("MaxRetries")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("integer")
+ .HasDefaultValue(3);
+
+ b.Property("ParametersJson")
+ .HasColumnType("jsonb");
+
+ b.Property("Priority")
+ .HasColumnType("integer");
+
+ b.Property("RequiredCpuCores")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("integer")
+ .HasDefaultValue(0);
+
+ b.Property("RequiredMemoryMb")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint")
+ .HasDefaultValue(0L);
+
+ b.Property("RequiresGpu")
+ .HasColumnType("boolean");
+
+ b.Property("ResultJson")
+ .HasColumnType("jsonb");
+
+ b.Property("RetryCount")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("integer")
+ .HasDefaultValue(0);
+
+ b.Property("SiteId")
+ .HasColumnType("uuid");
+
+ b.Property("StartedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("Status")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("character varying(30)");
+
+ b.Property("UpdatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.HasKey("Id");
+
+ b.HasIndex("CameraId")
+ .HasDatabaseName("ix_analysis_jobs_camera");
+
+ b.HasIndex("AssignedAgentId", "Status")
+ .HasDatabaseName("ix_analysis_jobs_agent_workload")
+ .HasFilter("\"AssignedAgentId\" IS NOT NULL");
+
+ b.HasIndex("Status", "DispatchedAt")
+ .HasDatabaseName("ix_analysis_jobs_timeout");
+
+ b.HasIndex("Status", "Priority", "CreatedAt")
+ .HasDatabaseName("ix_analysis_jobs_pending");
+
+ b.ToTable("analysis_jobs", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.Property("CreatedByUserId")
+ .HasColumnType("uuid");
+
+ b.Property("Enabled")
+ .HasColumnType("boolean");
+
+ b.Property("ExpiresAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("KeyHash")
+ .IsRequired()
+ .HasMaxLength(128)
+ .IsUnicode(false)
+ .HasColumnType("character varying(128)");
+
+ b.Property("KeyPrefix")
+ .IsRequired()
+ .HasMaxLength(8)
+ .IsUnicode(false)
+ .HasColumnType("character varying(8)");
+
+ b.Property("LastUsedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("SiteId")
+ .HasColumnType("uuid");
+
+ b.HasKey("Id");
+
+ b.HasIndex("KeyHash");
+
+ b.HasIndex("KeyPrefix");
+
+ b.HasIndex("SiteId");
+
+ b.ToTable("api_keys", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.AppSetting", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("AgentScoped")
+ .HasColumnType("boolean");
+
+ b.Property("AllowedValues")
+ .HasMaxLength(2000)
+ .HasColumnType("character varying(2000)")
+ .HasColumnName("allowed_values");
+
+ b.Property("Category")
+ .IsRequired()
+ .HasMaxLength(100)
+ .HasColumnType("character varying(100)")
+ .HasColumnName("category");
+
+ b.Property("CreatedAt")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("created_at");
+
+ b.Property("Description")
+ .HasMaxLength(500)
+ .HasColumnType("character varying(500)")
+ .HasColumnName("description");
+
+ b.Property("Key")
+ .IsRequired()
+ .HasMaxLength(200)
+ .HasColumnType("character varying(200)")
+ .HasColumnName("key");
+
+ b.Property("UpdatedAt")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("updated_at");
+
+ b.Property("Value")
+ .IsRequired()
+ .HasColumnType("text")
+ .HasColumnName("value");
+
+ b.Property("ValueType")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)")
+ .HasColumnName("value_type");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Key")
+ .IsUnique();
+
+ b.ToTable("app_settings", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.AuditLog", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("Action")
+ .IsRequired()
+ .HasMaxLength(100)
+ .IsUnicode(false)
+ .HasColumnType("character varying(100)");
+
+ b.Property("IpAddress")
+ .HasMaxLength(45)
+ .IsUnicode(false)
+ .HasColumnType("character varying(45)");
+
+ b.Property("NewValue")
+ .HasColumnType("text");
+
+ b.Property("OldValue")
+ .HasColumnType("text");
+
+ b.Property("ResourceId")
+ .HasMaxLength(100)
+ .IsUnicode(false)
+ .HasColumnType("character varying(100)");
+
+ b.Property("ResourceType")
+ .IsRequired()
+ .HasMaxLength(100)
+ .IsUnicode(false)
+ .HasColumnType("character varying(100)");
+
+ b.Property("Timestamp")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.Property("UserId")
+ .HasColumnType("uuid");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Timestamp")
+ .IsDescending();
+
+ b.HasIndex("UserId");
+
+ b.HasIndex("ResourceType", "ResourceId", "Timestamp")
+ .IsDescending(false, false, true);
+
+ b.ToTable("audit_logs", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("AgentId")
+ .HasColumnType("uuid");
+
+ b.Property("Capabilities")
+ .IsRequired()
+ .HasMaxLength(64)
+ .IsUnicode(false)
+ .HasColumnType("character varying(64)");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.Property("DeletedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("DetectedType")
+ .IsRequired()
+ .HasMaxLength(20)
+ .IsUnicode(false)
+ .HasColumnType("character varying(20)");
+
+ b.Property("DiscoveryMethod")
+ .IsRequired()
+ .HasMaxLength(20)
+ .IsUnicode(false)
+ .HasColumnType("character varying(20)");
+
+ b.Property("HasAudio")
+ .HasColumnType("boolean");
+
+ b.Property("HasMotionDetection")
+ .HasColumnType("boolean");
+
+ b.Property("HasPtz")
+ .HasColumnType("boolean");
+
+ b.Property("HttpPort")
+ .HasColumnType("integer");
+
+ b.Property("IpAddress")
+ .HasMaxLength(45)
+ .HasColumnType("character varying(45)");
+
+ b.Property("IsDeleted")
+ .HasColumnType("boolean");
+
+ b.Property("LastDiscoveredAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("LastStreamTestAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("LastTestedCodecs")
+ .HasMaxLength(200)
+ .IsUnicode(false)
+ .HasColumnType("character varying(200)");
+
+ b.Property("LastTestedHeight")
+ .HasColumnType("integer");
+
+ b.Property("LastTestedLatencyMs")
+ .HasColumnType("bigint");
+
+ b.Property("LastTestedWidth")
+ .HasColumnType("integer");
+
+ b.Property("MacAddress")
+ .HasMaxLength(17)
+ .HasColumnType("character varying(17)");
+
+ b.Property("Manufacturer")
+ .HasMaxLength(100)
+ .HasColumnType("character varying(100)");
+
+ b.Property("Model")
+ .HasMaxLength(100)
+ .HasColumnType("character varying(100)");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(200)
+ .IsUnicode(false)
+ .HasColumnType("character varying(200)");
+
+ b.Property("OnvifPort")
+ .HasColumnType("integer");
+
+ b.Property("RecordingEnabled")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("boolean")
+ .HasDefaultValue(false);
+
+ b.Property("RtspPort")
+ .HasColumnType("integer");
+
+ b.Property("RtspUrl")
+ .HasMaxLength(1000)
+ .IsUnicode(false)
+ .HasColumnType("character varying(1000)");
+
+ b.Property("SiteId")
+ .HasColumnType("uuid");
+
+ b.Property("Status")
+ .IsRequired()
+ .HasMaxLength(20)
+ .IsUnicode(false)
+ .HasColumnType("character varying(20)");
+
+ b.Property("StoragePolicyId")
+ .HasColumnType("uuid");
+
+ b.Property("SubRtspUrl")
+ .HasMaxLength(1000)
+ .IsUnicode(false)
+ .HasColumnType("character varying(1000)");
+
+ b.Property("UpdatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AgentId");
+
+ b.HasIndex("IpAddress");
+
+ b.HasIndex("MacAddress");
+
+ b.HasIndex("SiteId");
+
+ b.HasIndex("StoragePolicyId");
+
+ b.ToTable("cameras", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.CameraAssignment", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("AgentId")
+ .HasColumnType("uuid");
+
+ b.Property("AssignedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("CameraId")
+ .HasColumnType("uuid");
+
+ b.Property("Reason")
+ .IsRequired()
+ .HasMaxLength(50)
+ .IsUnicode(false)
+ .HasColumnType("character varying(50)");
+
+ b.Property("ReleasedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AssignedAt");
+
+ b.HasIndex("AgentId", "ReleasedAt")
+ .HasFilter("\"ReleasedAt\" IS NULL");
+
+ b.HasIndex("CameraId", "ReleasedAt")
+ .IsUnique()
+ .HasFilter("\"ReleasedAt\" IS NULL");
+
+ b.ToTable("camera_assignments", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.CameraCredentials", b =>
+ {
+ b.Property("CameraId")
+ .HasColumnType("uuid");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.Property("OnvifPassword")
+ .IsRequired()
+ .HasMaxLength(500)
+ .IsUnicode(false)
+ .HasColumnType("character varying(500)");
+
+ b.Property("OnvifUsername")
+ .IsRequired()
+ .ValueGeneratedOnAdd()
+ .HasMaxLength(100)
+ .IsUnicode(false)
+ .HasColumnType("character varying(100)")
+ .HasDefaultValue("admin");
+
+ b.Property("RtspPassword")
+ .IsRequired()
+ .HasMaxLength(500)
+ .IsUnicode(false)
+ .HasColumnType("character varying(500)");
+
+ b.Property("RtspUsername")
+ .IsRequired()
+ .HasMaxLength(100)
+ .IsUnicode(false)
+ .HasColumnType("character varying(100)");
+
+ b.Property("UpdatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.HasKey("CameraId");
+
+ b.ToTable("camera_credentials", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b =>
+ {
+ b.Property("CameraId")
+ .HasColumnType("uuid");
+
+ b.Property("ActiveIntervalMs")
+ .HasColumnType("integer");
+
+ b.Property("AnimalCooldownSec")
+ .HasColumnType("integer");
+
+ b.Property("DetectAnimal")
+ .HasColumnType("boolean");
+
+ b.Property("DetectMotion")
+ .HasColumnType("boolean");
+
+ b.Property("DetectPackage")
+ .HasColumnType("boolean");
+
+ b.Property("DetectPerson")
+ .HasColumnType("boolean");
+
+ b.Property("DetectVehicle")
+ .HasColumnType("boolean");
+
+ b.Property("ExecutionProfileJson")
+ .HasColumnType("text");
+
+ b.Property("FaceRecognition")
+ .HasColumnType("boolean");
+
+ b.Property("IdleIntervalMs")
+ .HasColumnType("integer");
+
+ b.Property("IoUThreshold")
+ .HasColumnType("double precision");
+
+ b.Property("LicensePlateRecognition")
+ .HasColumnType("boolean");
+
+ b.Property("MaxEventsPerMinute")
+ .HasColumnType("integer");
+
+ b.Property("MinConfidence")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("double precision")
+ .HasDefaultValue(0.40000000000000002);
+
+ b.Property("MotionIntervalMs")
+ .HasColumnType("integer");
+
+ b.Property("MotionThreshold")
+ .HasColumnType("double precision");
+
+ b.Property("PersonCooldownSec")
+ .HasColumnType("integer");
+
+ b.Property("RequireMotionForAI")
+ .HasColumnType("boolean");
+
+ b.Property("VehicleCooldownSec")
+ .HasColumnType("integer");
+
+ b.Property("YoloModel")
+ .IsRequired()
+ .ValueGeneratedOnAdd()
+ .HasMaxLength(50)
+ .IsUnicode(false)
+ .HasColumnType("character varying(50)")
+ .HasDefaultValue("yolov8n");
+
+ b.HasKey("CameraId");
+
+ b.ToTable("camera_detection_profiles", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("DetectedType")
+ .IsRequired()
+ .HasMaxLength(20)
+ .IsUnicode(false)
+ .HasColumnType("character varying(20)");
+
+ b.Property("DiscoveryMethod")
+ .IsRequired()
+ .HasMaxLength(20)
+ .IsUnicode(false)
+ .HasColumnType("character varying(20)");
+
+ b.Property("HomeKitCategory")
+ .HasColumnType("integer");
+
+ b.Property("HomeKitDeviceId")
+ .HasMaxLength(50)
+ .IsUnicode(false)
+ .HasColumnType("character varying(50)");
+
+ b.Property("HomeKitIsPaired")
+ .HasColumnType("boolean");
+
+ b.Property("HomeKitModel")
+ .HasMaxLength(200)
+ .IsUnicode(false)
+ .HasColumnType("character varying(200)");
+
+ b.Property("HomeKitName")
+ .HasMaxLength(200)
+ .IsUnicode(false)
+ .HasColumnType("character varying(200)");
+
+ b.Property("HomeKitPort")
+ .HasColumnType("integer");
+
+ b.Property("Hostname")
+ .HasMaxLength(255)
+ .IsUnicode(false)
+ .HasColumnType("character varying(255)");
+
+ b.Property