From 0136bf33ec046f697cc6bd810b94f22f27679726 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Tue, 11 Aug 2026 18:51:52 +0200 Subject: [PATCH] =?UTF-8?q?feat(logs):=20remont=C3=A9e=20des=20logs=20agen?= =?UTF-8?q?ts=20vers=20le=20central=20=E2=80=94=20buffer,=20API,=20UI=20(F?= =?UTF-8?q?ixes=20#50=20#51=20#52)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Agent : LogBufferService (ring buffer borné, drop-oldest), AgentLoggingProvider (capture ILogger non-bloquante), LogSanitizer (masque password/token/secret/bearer), LogUploadService (batch POST /api/agents/{id}/logs, retry, drop si 400) - Central : entité AgentLogEntry + migration AddAgentLogEntries (index AgentId+TimestampUtc), SubmitAgentLogsCommand (batch <= 200, entrées invalides ignorées), GetAgentLogsQuery (pagination, filtres niveau/période/recherche), endpoints POST + GET /api/agents/{id}/logs - UI : onglet Logs dans AgentDetail (filtres, pagination, auto-refresh toggle) - Logs agent enrichis : heartbeat succès (Debug), résolution IP (Debug) - Tests : LogBufferServiceTests (6), AgentDetailLogsTests (4), handlers AgentLogs (8) --- .../Logging/AgentLoggingProvider.cs | 69 + .../Logging/LogBufferService.cs | 83 + src/Heimdall.Agent/Logging/LogSanitizer.cs | 26 + src/Heimdall.Agent/Program.cs | 8 + .../Services/AgentRegistrationService.cs | 15 +- .../Services/LogUploadService.cs | 117 + .../SubmitAgentLogs/SubmitAgentLogsCommand.cs | 9 + .../SubmitAgentLogs/SubmitAgentLogsHandler.cs | 68 + .../SubmitAgentLogsValidator.cs | 39 + .../GetAgentLogs/GetAgentLogsHandler.cs | 60 + .../Queries/GetAgentLogs/GetAgentLogsQuery.cs | 14 + .../Common/IApplicationDbContext.cs | 1 + src/Heimdall.Application/DTOs/AgentLogDto.cs | 23 + src/Heimdall.Domain/Entities/AgentLogEntry.cs | 39 + src/Heimdall.Domain/Enums/AgentLogLevel.cs | 14 + .../Data/AppDbContext.cs | 1 + .../AgentLogEntryConfiguration.cs | 44 + ...60811163117_AddAgentLogEntries.Designer.cs | 1881 +++++++++++++++++ .../20260811163117_AddAgentLogEntries.cs | 50 + .../Migrations/AppDbContextModelSnapshot.cs | 50 + .../Components/Pages/AgentDetail.razor | 208 +- .../Controllers/AgentsController.cs | 40 + .../Services/HeimdallApiClient.cs | 21 + .../AgentRegistrationServiceTests.cs | 1 + .../LogBufferServiceTests.cs | 91 + .../AgentLogs/GetAgentLogsHandlerTests.cs | 81 + .../AgentLogs/SubmitAgentLogsHandlerTests.cs | 84 + .../Components/Pages/AgentDetailLogsTests.cs | 127 ++ 28 files changed, 3261 insertions(+), 3 deletions(-) create mode 100644 src/Heimdall.Agent/Logging/AgentLoggingProvider.cs create mode 100644 src/Heimdall.Agent/Logging/LogBufferService.cs create mode 100644 src/Heimdall.Agent/Logging/LogSanitizer.cs create mode 100644 src/Heimdall.Agent/Services/LogUploadService.cs create mode 100644 src/Heimdall.Application/AgentLogs/Commands/SubmitAgentLogs/SubmitAgentLogsCommand.cs create mode 100644 src/Heimdall.Application/AgentLogs/Commands/SubmitAgentLogs/SubmitAgentLogsHandler.cs create mode 100644 src/Heimdall.Application/AgentLogs/Commands/SubmitAgentLogs/SubmitAgentLogsValidator.cs create mode 100644 src/Heimdall.Application/AgentLogs/Queries/GetAgentLogs/GetAgentLogsHandler.cs create mode 100644 src/Heimdall.Application/AgentLogs/Queries/GetAgentLogs/GetAgentLogsQuery.cs create mode 100644 src/Heimdall.Application/DTOs/AgentLogDto.cs create mode 100644 src/Heimdall.Domain/Entities/AgentLogEntry.cs create mode 100644 src/Heimdall.Domain/Enums/AgentLogLevel.cs create mode 100644 src/Heimdall.Infrastructure/Data/Configurations/AgentLogEntryConfiguration.cs create mode 100644 src/Heimdall.Infrastructure/Migrations/20260811163117_AddAgentLogEntries.Designer.cs create mode 100644 src/Heimdall.Infrastructure/Migrations/20260811163117_AddAgentLogEntries.cs create mode 100644 tests/Heimdall.Agent.Tests/LogBufferServiceTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/AgentLogs/GetAgentLogsHandlerTests.cs create mode 100644 tests/Heimdall.Application.Tests/Handlers/AgentLogs/SubmitAgentLogsHandlerTests.cs create mode 100644 tests/Heimdall.Web.Tests/Components/Pages/AgentDetailLogsTests.cs diff --git a/src/Heimdall.Agent/Logging/AgentLoggingProvider.cs b/src/Heimdall.Agent/Logging/AgentLoggingProvider.cs new file mode 100644 index 0000000..c20ac94 --- /dev/null +++ b/src/Heimdall.Agent/Logging/AgentLoggingProvider.cs @@ -0,0 +1,69 @@ +using Microsoft.Extensions.Logging; + +namespace Heimdall.Agent.Logging; + +/// +/// Additional that captures every log entry +/// passing the process-wide filter (RuntimeLogLevel) into the +/// for upload to the Central. +/// This is a sink only: it never writes to console or files, so the +/// existing stdout/Docker output is untouched. +/// +public sealed class AgentLoggingProvider : ILoggerProvider +{ + private readonly LogBufferService _buffer; + + public AgentLoggingProvider(LogBufferService buffer) => _buffer = buffer; + + public ILogger CreateLogger(string categoryName) => new BufferLogger(_buffer, categoryName); + + public void Dispose() { } + + private sealed class BufferLogger : ILogger + { + private readonly LogBufferService _buffer; + private readonly string _category; + + public BufferLogger(LogBufferService buffer, string category) + { + _buffer = buffer; + _category = category; + } + + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log( + LogLevel logLevel, + EventId eventId, + TState state, + Exception? exception, + Func formatter) + { + try + { + var message = LogSanitizer.Sanitize(formatter(state, exception)); + if (string.IsNullOrWhiteSpace(message)) + return; + + _buffer.Enqueue(new BufferedLogEntry( + DateTime.UtcNow, + logLevel, + message, + LogSanitizer.Sanitize(exception?.ToString()), + ShortCategory(_category))); + } + catch (Exception) + { + // Logging must never crash the caller (FFmpeg/YOLO hot path). + } + } + + private static string ShortCategory(string category) + { + var dot = category.LastIndexOf('.'); + return dot >= 0 ? category[(dot + 1)..] : category; + } + } +} diff --git a/src/Heimdall.Agent/Logging/LogBufferService.cs b/src/Heimdall.Agent/Logging/LogBufferService.cs new file mode 100644 index 0000000..4f675dc --- /dev/null +++ b/src/Heimdall.Agent/Logging/LogBufferService.cs @@ -0,0 +1,83 @@ +using System.Collections.Concurrent; +using Microsoft.Extensions.Logging; + +namespace Heimdall.Agent.Logging; + +/// +/// Captured log entry waiting to be uploaded to the Central. +/// +public readonly record struct BufferedLogEntry( + DateTime TimestampUtc, + LogLevel Level, + string Message, + string? Exception, + string? Source); + +/// +/// Bounded, thread-safe in-memory buffer of log entries produced by the +/// agent and destined for the Central's POST /api/agents/{id}/logs. +/// +/// +/// Full-buffer policy: drop oldest. The most recent entries are the +/// most useful for diagnosing the agent's current state (a fresh Error must +/// never be dropped because a burst of older Warnings filled the buffer). +/// Dropped entries are counted so the operator can see the agent is logging +/// faster than it uploads. Logging never blocks the caller. +/// +public sealed class LogBufferService +{ + private readonly ConcurrentQueue _queue = new(); + private readonly int _capacity; + private int _droppedCount; + + public LogBufferService(int capacity = 500) + { + _capacity = capacity > 0 ? capacity : 500; + } + + public int Capacity => _capacity; + + /// Number of entries dropped because the buffer was full. + public int DroppedCount => Volatile.Read(ref _droppedCount); + + /// Current number of buffered entries. + public int Count => _queue.Count; + + /// + /// Adds an entry, dropping the oldest one when the buffer is full. + /// Never throws and never blocks the logging hot path. + /// + public void Enqueue(BufferedLogEntry entry) + { + _queue.Enqueue(entry); + + while (_queue.Count > _capacity) + { + if (_queue.TryDequeue(out _)) + Interlocked.Increment(ref _droppedCount); + else + break; + } + } + + /// + /// Atomically removes and returns all buffered entries (oldest first). + /// + public IReadOnlyList TakeAll() + { + if (_queue.IsEmpty) + return []; + + var entries = new List(_queue.Count); + while (_queue.TryDequeue(out var entry)) + entries.Add(entry); + return entries; + } + + /// Re-queues entries that failed to upload (drops oldest if needed). + public void Requeue(IEnumerable entries) + { + foreach (var entry in entries) + Enqueue(entry); + } +} diff --git a/src/Heimdall.Agent/Logging/LogSanitizer.cs b/src/Heimdall.Agent/Logging/LogSanitizer.cs new file mode 100644 index 0000000..3c62ff0 --- /dev/null +++ b/src/Heimdall.Agent/Logging/LogSanitizer.cs @@ -0,0 +1,26 @@ +using System.Text.RegularExpressions; + +namespace Heimdall.Agent.Logging; + +/// +/// Masks secrets in log messages before they leave the agent (spec P1: +/// "Secrets dans logs — sanitized : password, token, secret, snapshotUrl"). +/// Applied to both message and exception text at capture time. +/// +public static partial class LogSanitizer +{ + // Matches "key=value", "key: value", "key= 'value'" or JSON "key":"value" + // for well-known secret keys. Also handles "Authorization: Bearer ". + [GeneratedRegex( + @"(?i)(?password|passwd|pwd|token|secret|apikey|api_key|authorization|snapshoturl|credential|private[_-]?key)(['""]?\s*[:=]\s*)(?['""]?)(?:(?:bearer|basic)\s+)?(?[^'""\s,;&]+)", + RegexOptions.Compiled)] + private static partial Regex SecretValueRegex(); + + public static string Sanitize(string? text) + { + if (string.IsNullOrEmpty(text)) + return string.Empty; + + return SecretValueRegex().Replace(text, "${key}${2}${3}***"); + } +} diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs index 3a829e0..6361d7c 100644 --- a/src/Heimdall.Agent/Program.cs +++ b/src/Heimdall.Agent/Program.cs @@ -1,9 +1,11 @@ using Sentry.AspNetCore; using Heimdall.Agent; +using Heimdall.Agent.Logging; using Heimdall.Agent.Services; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; var builder = WebApplication.CreateSlimBuilder(args); @@ -69,6 +71,12 @@ builder.Services.AddHostedService(); builder.Services.AddHostedService(); builder.Services.AddHostedService(); +// Log capture & upload to Central (ticket #50) +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(sp => sp.GetRequiredService()); +builder.Services.AddHostedService(); + // Health checks — used by Docker HEALTHCHECK builder.Services.AddHealthChecks() .AddCheck("agent_health", tags: ["ready"]); diff --git a/src/Heimdall.Agent/Services/AgentRegistrationService.cs b/src/Heimdall.Agent/Services/AgentRegistrationService.cs index f966e79..aca1d7e 100644 --- a/src/Heimdall.Agent/Services/AgentRegistrationService.cs +++ b/src/Heimdall.Agent/Services/AgentRegistrationService.cs @@ -15,6 +15,7 @@ public class AgentRegistrationService : BackgroundService private readonly AgentState _state; private readonly AgentOptions _options; private readonly SystemMetricsProvider _metrics; + private readonly Logging.LogBufferService _buffer; private HttpClient? _client; public AgentRegistrationService( @@ -22,12 +23,14 @@ public class AgentRegistrationService : BackgroundService AgentState state, IOptions options, SystemMetricsProvider metrics, + Logging.LogBufferService buffer, ILogger logger) { _httpClientFactory = httpClientFactory; _state = state; _options = options.Value; _metrics = metrics; + _buffer = buffer; _logger = logger; } @@ -165,6 +168,11 @@ public class AgentRegistrationService : BackgroundService { _logger.LogWarning("Heartbeat failed: {StatusCode}", heartbeatResponse.StatusCode); } + else + { + _logger.LogDebug("Heartbeat OK — agent online, {Buffered} log(s) buffered", + _buffer.Count); + } } catch (Exception ex) when (ex is not OperationCanceledException) { @@ -187,10 +195,13 @@ public class AgentRegistrationService : BackgroundService var http = _httpClientFactory.CreateClient("IpResolver"); http.Timeout = TimeSpan.FromSeconds(5); var ip = await http.GetStringAsync("https://api.ipify.org", ct); - return ip?.Trim(); + ip = ip?.Trim(); + _logger.LogDebug("Public IP resolved: {Ip}", ip); + return ip; } - catch + catch (Exception ex) { + _logger.LogDebug("Public IP resolution failed ({Error}); reporting null", ex.Message); return null; } } diff --git a/src/Heimdall.Agent/Services/LogUploadService.cs b/src/Heimdall.Agent/Services/LogUploadService.cs new file mode 100644 index 0000000..b35d6a4 --- /dev/null +++ b/src/Heimdall.Agent/Services/LogUploadService.cs @@ -0,0 +1,117 @@ +using System.Net.Http.Json; +using System.Text.Json.Serialization; +using Heimdall.Agent.Logging; +using Heimdall.Agent.Services; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace Heimdall.Agent.Services; + +/// +/// Periodically flushes the agent's to the +/// Central via POST /api/agents/{id}/logs (API Key auth). +/// Non-blocking by design: if the Central is unreachable the entries are +/// re-queued and retried on the next tick; a 400 (validation) drops the +/// batch to avoid an infinite retry loop. +/// +public class LogUploadService : BackgroundService +{ + private readonly IHttpClientFactory _httpClientFactory; + private readonly LogBufferService _buffer; + private readonly AgentState _state; + private readonly ILogger _logger; + + public LogUploadService( + IHttpClientFactory httpClientFactory, + LogBufferService buffer, + AgentState state, + ILogger logger) + { + _httpClientFactory = httpClientFactory; + _buffer = buffer; + _state = state; + _logger = logger; + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + using var timer = new PeriodicTimer(TimeSpan.FromSeconds(30)); + + while (await timer.WaitForNextTickAsync(stoppingToken).ConfigureAwait(false)) + { + try + { + await UploadOnceAsync(stoppingToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + break; + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Log upload tick failed (non-fatal)"); + } + } + } + + internal async Task UploadOnceAsync(CancellationToken ct) + { + // No registered identity yet → nothing to attach logs to. + if (_state.AgentId == Guid.Empty || string.IsNullOrEmpty(_state.ApiKey)) + return; + + var entries = _buffer.TakeAll(); + if (entries.Count == 0) + return; + + var client = _httpClientFactory.CreateClient("Central"); + client.DefaultRequestHeaders.Remove("X-API-Key"); + client.DefaultRequestHeaders.Add("X-API-Key", _state.ApiKey); + + var payload = new + { + entries = entries.Select(e => new + { + timestampUtc = e.TimestampUtc, + level = e.Level.ToString(), + message = e.Message, + exception = e.Exception, + source = e.Source + }).ToList() + }; + + try + { + using var response = await client.PostAsJsonAsync( + $"api/agents/{_state.AgentId}/logs", payload, ct).ConfigureAwait(false); + + if (response.IsSuccessStatusCode) + { + if (_buffer.DroppedCount > 0) + _logger.LogWarning( + "Log upload OK; {Count} entries uploaded, {Dropped} dropped (buffer full)", + entries.Count, _buffer.DroppedCount); + return; + } + + if ((int)response.StatusCode == 400) + { + // Validation error — re-sending the same batch will never succeed. + _logger.LogWarning( + "Central rejected log batch ({Status}): dropping {Count} entries", + (int)response.StatusCode, entries.Count); + return; + } + + _logger.LogWarning( + "Log upload failed ({Status}); {Count} entries re-queued", + (int)response.StatusCode, entries.Count); + _buffer.Requeue(entries); + } + catch (Exception ex) + { + _logger.LogDebug("Log upload failed (network): {Error}; {Count} entries re-queued", ex.Message, entries.Count); + _buffer.Requeue(entries); + } + } +} diff --git a/src/Heimdall.Application/AgentLogs/Commands/SubmitAgentLogs/SubmitAgentLogsCommand.cs b/src/Heimdall.Application/AgentLogs/Commands/SubmitAgentLogs/SubmitAgentLogsCommand.cs new file mode 100644 index 0000000..decdcff --- /dev/null +++ b/src/Heimdall.Application/AgentLogs/Commands/SubmitAgentLogs/SubmitAgentLogsCommand.cs @@ -0,0 +1,9 @@ +using Heimdall.Application.Common; +using Heimdall.Application.DTOs; +using MediatR; + +namespace Heimdall.Application.AgentLogs.Commands.SubmitAgentLogs; + +public record SubmitAgentLogsCommand( + Guid AgentId, + IReadOnlyList Entries) : IRequest; diff --git a/src/Heimdall.Application/AgentLogs/Commands/SubmitAgentLogs/SubmitAgentLogsHandler.cs b/src/Heimdall.Application/AgentLogs/Commands/SubmitAgentLogs/SubmitAgentLogsHandler.cs new file mode 100644 index 0000000..2cc25a2 --- /dev/null +++ b/src/Heimdall.Application/AgentLogs/Commands/SubmitAgentLogs/SubmitAgentLogsHandler.cs @@ -0,0 +1,68 @@ +using Heimdall.Application.Common; +using Heimdall.Application.DTOs; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using MediatR; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Application.AgentLogs.Commands.SubmitAgentLogs; + +public class SubmitAgentLogsHandler : IRequestHandler +{ + private readonly IApplicationDbContext _db; + + public SubmitAgentLogsHandler(IApplicationDbContext db) => _db = db; + + public async Task Handle(SubmitAgentLogsCommand request, CancellationToken ct) + { + var agentExists = await _db.Agents + .AnyAsync(a => a.Id == request.AgentId, ct) + .ConfigureAwait(false); + if (!agentExists) + return ServiceResult.NotFound("Agent not found"); + + var nowUtc = DateTime.UtcNow; + var entries = new List(request.Entries.Count); + + foreach (var entry in request.Entries) + { + // Skip malformed entries instead of failing the whole batch: + // an agent misconfiguration must not block log collection. + if (!Enum.TryParse(entry.Level, true, out var level)) + continue; + if (string.IsNullOrWhiteSpace(entry.Message)) + continue; + + var timestamp = entry.TimestampUtc.Kind == DateTimeKind.Unspecified + ? DateTime.SpecifyKind(entry.TimestampUtc, DateTimeKind.Utc) + : entry.TimestampUtc.ToUniversalTime(); + + // Clamp absurdly old timestamps (agent buffered through a long outage); + // entries in the future are dropped by the validator. + if (timestamp < nowUtc.AddDays(-30)) + continue; + + entries.Add(new AgentLogEntry( + request.AgentId, + timestamp, + level, + entry.Message.Trim(), + Normalize(entry.Exception), + Normalize(entry.Source))); + } + + if (entries.Count == 0) + return ServiceResult.Failure("No valid log entries in batch", 400); + + foreach (var entry in entries) + _db.AgentLogEntries.Add(entry); + await _db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false); + return ServiceResult.Success(); + } + + private static string? Normalize(string? value) + { + var trimmed = value?.Trim(); + return string.IsNullOrWhiteSpace(trimmed) ? null : trimmed; + } +} diff --git a/src/Heimdall.Application/AgentLogs/Commands/SubmitAgentLogs/SubmitAgentLogsValidator.cs b/src/Heimdall.Application/AgentLogs/Commands/SubmitAgentLogs/SubmitAgentLogsValidator.cs new file mode 100644 index 0000000..56efd4f --- /dev/null +++ b/src/Heimdall.Application/AgentLogs/Commands/SubmitAgentLogs/SubmitAgentLogsValidator.cs @@ -0,0 +1,39 @@ +using Heimdall.Application.AgentLogs.Commands.SubmitAgentLogs; +using FluentValidation; + +namespace Heimdall.Application.AgentLogs.Commands.SubmitAgentLogs; + +public class SubmitAgentLogsValidator : AbstractValidator +{ + public const int MaxBatchSize = 200; + public const int MaxMessageLength = 2000; + + public SubmitAgentLogsValidator() + { + RuleFor(x => x.AgentId) + .NotEmpty(); + + RuleFor(x => x.Entries) + .NotNull() + .NotEmpty() + .WithMessage("Log entries are required.") + .Must(e => e.Count <= MaxBatchSize) + .WithMessage($"Batch size exceeds the maximum of {MaxBatchSize} entries."); + + RuleForEach(x => x.Entries) + .ChildRules(entry => + { + entry.RuleFor(e => e.Message) + .NotEmpty() + .WithMessage("Log message is required.") + .MaximumLength(MaxMessageLength) + .WithMessage($"Log message exceeds {MaxMessageLength} characters."); + + entry.RuleFor(e => e.TimestampUtc) + .Must(ts => ts.Kind == DateTimeKind.Utc || ts.Kind == DateTimeKind.Unspecified) + .WithMessage("TimestampUtc must be UTC.") + .Must(ts => ts <= DateTime.UtcNow.AddMinutes(5)) + .WithMessage("TimestampUtc is in the future (clock skew > 5 min)."); + }); + } +} diff --git a/src/Heimdall.Application/AgentLogs/Queries/GetAgentLogs/GetAgentLogsHandler.cs b/src/Heimdall.Application/AgentLogs/Queries/GetAgentLogs/GetAgentLogsHandler.cs new file mode 100644 index 0000000..0f3339f --- /dev/null +++ b/src/Heimdall.Application/AgentLogs/Queries/GetAgentLogs/GetAgentLogsHandler.cs @@ -0,0 +1,60 @@ +using Heimdall.Application.AgentLogs.Queries.GetAgentLogs; +using Heimdall.Application.Common; +using Heimdall.Application.DTOs; +using Heimdall.Domain.Enums; +using MediatR; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Application.AgentLogs.Queries.GetAgentLogs; + +public class GetAgentLogsHandler : IRequestHandler>> +{ + private readonly IApplicationDbContext _db; + + public GetAgentLogsHandler(IApplicationDbContext db) => _db = db; + + public async Task>> Handle(GetAgentLogsQuery request, CancellationToken ct) + { + var query = _db.AgentLogEntries.Where(e => e.AgentId == request.AgentId); + + if (!string.IsNullOrWhiteSpace(request.Level) + && Enum.TryParse(request.Level, true, out var level)) + { + query = query.Where(e => e.Level == level); + } + + if (request.From.HasValue) + query = query.Where(e => e.TimestampUtc >= request.From.Value.ToUniversalTime()); + + if (request.To.HasValue) + query = query.Where(e => e.TimestampUtc <= request.To.Value.ToUniversalTime()); + + if (!string.IsNullOrWhiteSpace(request.Search)) + { + var search = request.Search.Trim(); + query = query.Where(e => + e.Message.Contains(search, StringComparison.OrdinalIgnoreCase) + || (e.Source != null && e.Source.Contains(search, StringComparison.OrdinalIgnoreCase))); + } + + var total = await query.CountAsync(ct).ConfigureAwait(false); + + var items = await query + .OrderByDescending(e => e.TimestampUtc) + .Skip((request.Page - 1) * request.PageSize) + .Take(request.PageSize) + .Select(e => new AgentLogEntryDto( + e.Id, + e.AgentId, + e.TimestampUtc, + e.Level.ToString(), + e.Message, + e.Exception, + e.Source)) + .ToListAsync(ct) + .ConfigureAwait(false); + + return ServiceResult>.Success( + new PagedResult(items, total, request.Page, request.PageSize)); + } +} diff --git a/src/Heimdall.Application/AgentLogs/Queries/GetAgentLogs/GetAgentLogsQuery.cs b/src/Heimdall.Application/AgentLogs/Queries/GetAgentLogs/GetAgentLogsQuery.cs new file mode 100644 index 0000000..078bf83 --- /dev/null +++ b/src/Heimdall.Application/AgentLogs/Queries/GetAgentLogs/GetAgentLogsQuery.cs @@ -0,0 +1,14 @@ +using Heimdall.Application.Common; +using Heimdall.Application.DTOs; +using MediatR; + +namespace Heimdall.Application.AgentLogs.Queries.GetAgentLogs; + +public record GetAgentLogsQuery( + Guid AgentId, + int Page = 1, + int PageSize = 50, + string? Level = null, + DateTime? From = null, + DateTime? To = null, + string? Search = null) : IRequest>>; diff --git a/src/Heimdall.Application/Common/IApplicationDbContext.cs b/src/Heimdall.Application/Common/IApplicationDbContext.cs index 27ab50f..02b9d7d 100644 --- a/src/Heimdall.Application/Common/IApplicationDbContext.cs +++ b/src/Heimdall.Application/Common/IApplicationDbContext.cs @@ -6,6 +6,7 @@ namespace Heimdall.Application.Common; public interface IApplicationDbContext { DbSet Agents { get; } + DbSet AgentLogEntries { get; } DbSet AgentSettings { get; } DbSet ApiKeys { get; } DbSet AppSettings { get; } diff --git a/src/Heimdall.Application/DTOs/AgentLogDto.cs b/src/Heimdall.Application/DTOs/AgentLogDto.cs new file mode 100644 index 0000000..f2902b4 --- /dev/null +++ b/src/Heimdall.Application/DTOs/AgentLogDto.cs @@ -0,0 +1,23 @@ +namespace Heimdall.Application.DTOs; + +/// Single log entry as submitted by an agent. +public record AgentLogEntryRequest( + DateTime TimestampUtc, + string Level, + string Message, + string? Exception = null, + string? Source = null); + +/// Batch of log entries submitted by an agent. +public record SubmitAgentLogsRequest( + IReadOnlyList Entries); + +/// Log entry as returned to the admin UI. +public record AgentLogEntryDto( + Guid Id, + Guid AgentId, + DateTime TimestampUtc, + string Level, + string Message, + string? Exception, + string? Source); diff --git a/src/Heimdall.Domain/Entities/AgentLogEntry.cs b/src/Heimdall.Domain/Entities/AgentLogEntry.cs new file mode 100644 index 0000000..3e4171b --- /dev/null +++ b/src/Heimdall.Domain/Entities/AgentLogEntry.cs @@ -0,0 +1,39 @@ +using Heimdall.Domain.Enums; + +namespace Heimdall.Domain.Entities; + +/// +/// Append-only log entry reported by an agent (FFmpeg, YOLO, RTSP, lifecycle…). +/// Purged periodically by the AgentLogCleanupJob (retention policy). +/// +public class AgentLogEntry +{ + public Guid Id { get; private set; } = Guid.NewGuid(); + public Guid AgentId { get; private set; } + public DateTime TimestampUtc { get; private set; } + public AgentLogLevel Level { get; private set; } + public string Message { get; private set; } = string.Empty; + public string? Exception { get; private set; } + public string? Source { get; private set; } + + // Navigation + public Agent Agent { get; private set; } = null!; + + private AgentLogEntry() { } // EF Core + + public AgentLogEntry( + Guid agentId, + DateTime timestampUtc, + AgentLogLevel level, + string message, + string? exception = null, + string? source = null) + { + AgentId = agentId; + TimestampUtc = timestampUtc; + Level = level; + Message = message; + Exception = exception; + Source = source; + } +} diff --git a/src/Heimdall.Domain/Enums/AgentLogLevel.cs b/src/Heimdall.Domain/Enums/AgentLogLevel.cs new file mode 100644 index 0000000..35e5af8 --- /dev/null +++ b/src/Heimdall.Domain/Enums/AgentLogLevel.cs @@ -0,0 +1,14 @@ +namespace Heimdall.Domain.Enums; + +/// +/// Severity level of an agent log entry, mirroring Microsoft.Extensions.Logging levels. +/// +public enum AgentLogLevel +{ + Trace = 0, + Debug = 1, + Information = 2, + Warning = 3, + Error = 4, + Critical = 5 +} diff --git a/src/Heimdall.Infrastructure/Data/AppDbContext.cs b/src/Heimdall.Infrastructure/Data/AppDbContext.cs index 7ec75e4..9386679 100644 --- a/src/Heimdall.Infrastructure/Data/AppDbContext.cs +++ b/src/Heimdall.Infrastructure/Data/AppDbContext.cs @@ -23,6 +23,7 @@ public class AppDbContext : IdentityDbContext, IApplicat public DbSet Sites => Set(); public DbSet SiteCredentials => Set(); public DbSet Agents => Set(); + public DbSet AgentLogEntries => Set(); public DbSet Cameras => Set(); public DbSet CameraCredentials => Set(); public DbSet CameraDetectionProfiles => Set(); diff --git a/src/Heimdall.Infrastructure/Data/Configurations/AgentLogEntryConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/AgentLogEntryConfiguration.cs new file mode 100644 index 0000000..1e24d4c --- /dev/null +++ b/src/Heimdall.Infrastructure/Data/Configurations/AgentLogEntryConfiguration.cs @@ -0,0 +1,44 @@ +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Heimdall.Infrastructure.Data.Configurations; + +public class AgentLogEntryConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("agent_log_entries"); + + builder.HasKey(e => e.Id); + + builder.Property(e => e.TimestampUtc) + .IsRequired(); + + builder.Property(e => e.Level) + .HasConversion() + .HasMaxLength(20) + .IsRequired() + .IsUnicode(false); + + builder.Property(e => e.Message) + .HasMaxLength(2000) + .IsRequired(); + + builder.Property(e => e.Exception) + .HasMaxLength(4000); + + builder.Property(e => e.Source) + .HasMaxLength(200) + .IsUnicode(false); + + // Composite index: reads per agent (logs page) + purge by age. + builder.HasIndex(e => new { e.AgentId, e.TimestampUtc }); + + builder.HasOne(e => e.Agent) + .WithMany() + .HasForeignKey(e => e.AgentId) + .OnDelete(DeleteBehavior.Cascade); + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/20260811163117_AddAgentLogEntries.Designer.cs b/src/Heimdall.Infrastructure/Migrations/20260811163117_AddAgentLogEntries.Designer.cs new file mode 100644 index 0000000..26ab59e --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20260811163117_AddAgentLogEntries.Designer.cs @@ -0,0 +1,1881 @@ +// +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("20260811163117_AddAgentLogEntries")] + partial class AddAgentLogEntries + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.8") + .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("CpuCores") + .HasColumnType("integer"); + + b.Property("CpuUsagePercent") + .HasColumnType("double precision"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DiskUsagePercent") + .HasColumnType("double precision"); + + 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("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastHeartbeat") + .HasColumnType("timestamp with time zone"); + + b.Property("MemoryMb") + .HasColumnType("bigint"); + + b.Property("MemoryUsageBytes") + .HasColumnType("bigint"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + 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("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UptimeSeconds") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + 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.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.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.AppRole", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("roles", (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.AppUser", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .IsUnicode(false) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("MustChangePassword") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("Theme") + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)") + .HasDefaultValue("Auto"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("users", (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("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("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.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("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("HomeKitDeviceId") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("HomeKitModel") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("HomeKitName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("Hostname") + .HasMaxLength(255) + .IsUnicode(false) + .HasColumnType("character varying(255)"); + + b.Property("HttpPort") + .HasColumnType("integer"); + + b.Property("HttpServerHeader") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("HttpStatusCode") + .HasColumnType("integer"); + + b.Property("IpAddress") + .IsRequired() + .HasMaxLength(45) + .IsUnicode(false) + .HasColumnType("character varying(45)"); + + b.Property("IsHomeKitCamera") + .HasColumnType("boolean"); + + b.Property("IsProcessed") + .HasColumnType("boolean"); + + b.Property("IsReachable") + .HasColumnType("boolean"); + + b.Property("MacAddress") + .HasMaxLength(17) + .IsUnicode(false) + .HasColumnType("character varying(17)"); + + b.Property("OnvifDeviceServiceUrl") + .HasMaxLength(500) + .IsUnicode(false) + .HasColumnType("character varying(500)"); + + b.Property("OnvifHardware") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifPort") + .HasColumnType("integer"); + + b.PrimitiveCollection("OpenPorts") + .IsRequired() + .IsUnicode(false) + .HasColumnType("integer[]"); + + b.Property("ProbedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Vendor") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.HasKey("Id"); + + b.HasIndex("IpAddress"); + + b.HasIndex("IsProcessed"); + + b.HasIndex("SiteId"); + + b.ToTable("camera_discovery_results", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraEvent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("Confidence") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.0); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("Label") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("MetadataJson") + .HasColumnType("jsonb"); + + b.Property("OccurredAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SnapshotThumbUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("Type") + .HasColumnType("integer"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("OccurredAt"); + + b.HasIndex("CameraId", "OccurredAt") + .IsDescending(false, true); + + b.HasIndex("CameraId", "Type"); + + b.ToTable("camera_events", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.DiscoveredStreamUrl", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.PrimitiveCollection("Codecs") + .IsRequired() + .IsUnicode(false) + .HasColumnType("text[]"); + + b.Property("DiscoveryResultId") + .HasColumnType("uuid"); + + b.Property("Height") + .HasColumnType("integer"); + + b.Property("IsAlive") + .HasColumnType("boolean"); + + b.Property("IsMainStream") + .HasColumnType("boolean"); + + b.Property("LatencyMs") + .HasColumnType("bigint"); + + b.Property("Protocol") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Url") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("Width") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("DiscoveryResultId"); + + b.HasIndex("IsAlive"); + + b.HasIndex("IsMainStream"); + + b.ToTable("discovered_streams", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Group", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("IsDeleted") + .HasFilter("\"IsDeleted\" = false"); + + b.HasIndex("Name"); + + b.ToTable("groups", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.KnownFace", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Embedding") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("SourceEventId") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("ThumbnailUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("PersonId"); + + b.ToTable("known_faces", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Notification", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("EventType") + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("IsRead") + .HasColumnType("boolean"); + + b.Property("Link") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("ReadAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("SnapshotUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("CreatedAt"); + + b.HasIndex("UserId"); + + b.HasIndex("UserId", "IsRead"); + + b.ToTable("notifications", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.NotificationTemplate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("BodyMarkdown") + .IsRequired() + .HasColumnType("text"); + + b.Property("Channel") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("EventType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("IsDefault") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("Subject") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("EventType", "Channel", "Language") + .IsUnique(); + + b.ToTable("notification_templates", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Person", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Category") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("IsWatchlisted") + .HasColumnType("boolean"); + + b.Property("Notes") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("PhotoUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Category"); + + b.HasIndex("DisplayName"); + + b.HasIndex("IsWatchlisted"); + + b.ToTable("persons", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.RevokedRefreshToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("RevokedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("revoked_refresh_tokens", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Site", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Address") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("RegistrationTokenHash") + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("Timezone") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)") + .HasDefaultValue("UTC"); + + b.Property("TokenExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("IsDeleted") + .HasFilter("\"IsDeleted\" = false"); + + b.HasIndex("Name"); + + b.ToTable("sites", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.SiteCredential", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Password") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("SiteId"); + + b.ToTable("site_credentials", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserGroup", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "GroupId"); + + b.HasIndex("GroupId"); + + b.ToTable("user_groups", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserNotificationConfig", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DailyDigest") + .HasColumnType("boolean"); + + b.Property("EmailAddress") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("EmailEnabled") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("NtfyEnabled") + .HasColumnType("boolean"); + + b.Property("NtfyUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("SubscribedEventsJson") + .HasColumnType("jsonb") + .HasColumnName("subscribed_events"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("WeeklyDigest") + .HasColumnType("boolean"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("user_notification_configs", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "SiteId"); + + b.HasIndex("SiteId"); + + b.ToTable("user_sites", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("role_claims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("user_claims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("user_logins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("user_roles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("user_tokens", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Agents") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentLogEntry", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Agent"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Agent"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AuditLog", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany("Cameras") + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Cameras") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Agent"); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraAssignment", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Agent"); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraCredentials", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithOne("Credentials") + .HasForeignKey("Heimdall.Domain.Entities.CameraCredentials", "CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithOne("DetectionProfile") + .HasForeignKey("Heimdall.Domain.Entities.CameraDetectionProfile", "CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraEvent", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.DiscoveredStreamUrl", b => + { + b.HasOne("Heimdall.Domain.Entities.CameraDiscoveryResult", "DiscoveryResult") + .WithMany("DiscoveredStreams") + .HasForeignKey("DiscoveryResultId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("DiscoveryResult"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.KnownFace", b => + { + b.HasOne("Heimdall.Domain.Entities.Person", "Person") + .WithMany("Faces") + .HasForeignKey("PersonId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Person"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.SiteCredential", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Credentials") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserGroup", b => + { + b.HasOne("Heimdall.Domain.Entities.Group", "Group") + .WithMany("UserGroups") + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany("UserGroups") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany("UserSites") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Heimdall.Domain.Entities.AppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Heimdall.Domain.Entities.AppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.Navigation("Cameras"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppUser", b => + { + b.Navigation("UserGroups"); + + b.Navigation("UserSites"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.Navigation("Credentials"); + + b.Navigation("DetectionProfile"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.Navigation("DiscoveredStreams"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Group", b => + { + b.Navigation("UserGroups"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Person", b => + { + b.Navigation("Faces"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Site", b => + { + b.Navigation("Agents"); + + b.Navigation("Cameras"); + + b.Navigation("Credentials"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/20260811163117_AddAgentLogEntries.cs b/src/Heimdall.Infrastructure/Migrations/20260811163117_AddAgentLogEntries.cs new file mode 100644 index 0000000..baf31cf --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20260811163117_AddAgentLogEntries.cs @@ -0,0 +1,50 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations +{ + /// + public partial class AddAgentLogEntries : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "agent_log_entries", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + AgentId = table.Column(type: "uuid", nullable: false), + TimestampUtc = table.Column(type: "timestamp with time zone", nullable: false), + Level = table.Column(type: "character varying(20)", unicode: false, maxLength: 20, nullable: false), + Message = table.Column(type: "character varying(2000)", maxLength: 2000, nullable: false), + Exception = table.Column(type: "character varying(4000)", maxLength: 4000, nullable: true), + Source = table.Column(type: "character varying(200)", unicode: false, maxLength: 200, nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_agent_log_entries", x => x.Id); + table.ForeignKey( + name: "FK_agent_log_entries_agents_AgentId", + column: x => x.AgentId, + principalTable: "agents", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_agent_log_entries_AgentId_TimestampUtc", + table: "agent_log_entries", + columns: new[] { "AgentId", "TimestampUtc" }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "agent_log_entries"); + } + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs index a9f51e8..390ccf5 100644 --- a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -126,6 +126,45 @@ namespace Heimdall.Infrastructure.Migrations 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.AgentSetting", b => { b.Property("Id") @@ -1546,6 +1585,17 @@ namespace Heimdall.Infrastructure.Migrations b.Navigation("Site"); }); + modelBuilder.Entity("Heimdall.Domain.Entities.AgentLogEntry", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Agent"); + }); + modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b => { b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") diff --git a/src/Heimdall.Web/Components/Pages/AgentDetail.razor b/src/Heimdall.Web/Components/Pages/AgentDetail.razor index 50559ae..145706e 100644 --- a/src/Heimdall.Web/Components/Pages/AgentDetail.razor +++ b/src/Heimdall.Web/Components/Pages/AgentDetail.razor @@ -228,6 +228,124 @@ else } + @* ─── Agent Logs ─── *@ + + +
+ + Tous les niveaux + Critical + Error + Warning + Information + Debug + Trace + + + + Filtrer + +
+ + @if (_logsLoading) + { + + + + + + } + else if (_logsError) + { + + Erreur lors du chargement des logs. + + Réessayer + + + } + else + { + + + Date + Niveau + Source + Message + + + + + @context.TimestampUtc.ToLocalTime().ToString("g") + + + + + @context.Level + + + + @(context.Source ?? "-") + + + @if (!string.IsNullOrEmpty(context.Exception)) + { + + @context.Message + + } + else + { + @context.Message + } + + + + + + Aucun log + + L'agent n'a rien remonté pour ces filtres. + + + + + +
+ + Page @_logPage sur @_logTotalPages (@_logTotal entrées) + + + + ← Précédent + + + Suivant → + +
+ } +
+ + + + + + +
+
@@ -316,6 +434,19 @@ else private bool _confirmDeleteVisible; private string _deletingKey = string.Empty; private bool _deleting; + + // Logs + private IReadOnlyList? _logs; + private bool _logsLoading; + private bool _logsError; + private int _logPage = 1; + private int _logTotalPages = 1; + private int _logTotal; + private string? _logLevel; + private string? _logSearch; + private bool _autoRefresh; + private CancellationTokenSource? _refreshCts; + private bool _disposed; private readonly DialogOptions _dialogOptions = new() { MaxWidth = MaxWidth.Small, @@ -329,7 +460,10 @@ else { _agent = await Api.GetAgentAsync(Id); if (_agent is not null) + { await LoadSettingsAsync(); + await LoadLogsAsync(keepPage: false); + } } catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); } finally { _loading = false; } @@ -478,9 +612,81 @@ else finally { _deleting = false; } } + private async Task LoadLogsAsync(bool keepPage) + { + if (!keepPage) _logPage = 1; + _logsError = false; + _logsLoading = true; + try + { + var result = await Api.GetAgentLogsAsync(Id, _logLevel, _logSearch, _logPage); + if (result is not null) + { + _logs = result.Items; + _logTotal = result.TotalCount; + _logTotalPages = Math.Max(1, (int)Math.Ceiling(result.TotalCount / (double)result.PageSize)); + } + } + catch + { + _logsError = true; + _logs = []; + } + finally + { + _logsLoading = false; + if (!_disposed) await InvokeAsync(StateHasChanged); + } + } + + private async Task GoToLogPage(int page) + { + _logPage = page; + await LoadLogsAsync(keepPage: true); + } + + private async Task ToggleAutoRefresh(bool enabled) + { + _autoRefresh = enabled; + _refreshCts?.Cancel(); + _refreshCts?.Dispose(); + _refreshCts = null; + + if (enabled) + { + _refreshCts = new CancellationTokenSource(); + _ = AutoRefreshLoopAsync(_refreshCts.Token); + } + } + + private async Task AutoRefreshLoopAsync(CancellationToken ct) + { + try + { + while (!ct.IsCancellationRequested) + { + await Task.Delay(TimeSpan.FromSeconds(10), ct); + if (!_disposed && _agent is not null) + await LoadLogsAsync(keepPage: true); + } + } + catch (OperationCanceledException) { /* arrêt volontaire */ } + } + + private static Color GetLogLevelColor(string level) => level switch + { + "Critical" or "Error" => Color.Error, + "Warning" => Color.Warning, + "Information" => Color.Info, + _ => Color.Default + }; + public void Dispose() { - // No unmanaged resources to dispose + _disposed = true; + _refreshCts?.Cancel(); + _refreshCts?.Dispose(); + _refreshCts = null; } private static Color GetStatusColor(string status) => status switch diff --git a/src/Heimdall.Web/Controllers/AgentsController.cs b/src/Heimdall.Web/Controllers/AgentsController.cs index c7b2ce3..f67e1bd 100644 --- a/src/Heimdall.Web/Controllers/AgentsController.cs +++ b/src/Heimdall.Web/Controllers/AgentsController.cs @@ -4,6 +4,8 @@ using Heimdall.Application.AgentDiscovery.Commands.SubmitAgentDiscovery; using Heimdall.Application.Agents.Queries.GetAgent; using Heimdall.Application.Agents.Queries.GetAgentsBySite; using Heimdall.Application.Agents.Queries.GetAllAgents; +using Heimdall.Application.AgentLogs.Commands.SubmitAgentLogs; +using Heimdall.Application.AgentLogs.Queries.GetAgentLogs; using Heimdall.Application.DTOs; using Heimdall.Domain.Enums; using Heimdall.Infrastructure.Security; @@ -117,6 +119,44 @@ public class AgentsController : ControllerBase return Ok(result.Data); } + /// Submit a batch of log entries from an agent (API Key auth). + [Authorize(AuthenticationSchemes = "ApiKey")] + [HttpPost("{id:guid}/logs")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task SubmitLogs( + Guid id, [FromBody] SubmitAgentLogsRequest request, CancellationToken ct) + { + var command = new SubmitAgentLogsCommand(id, request.Entries); + var result = await _mediator.Send(command, ct); + return result.IsSuccess + ? Ok() + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + + /// Get agent log entries (JWT auth). + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)] + [HttpGet("{id:guid}/logs")] + [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] + public async Task GetLogs( + Guid id, + [FromQuery] int page = 1, + [FromQuery] int pageSize = 50, + [FromQuery] string? level = null, + [FromQuery] DateTime? from = null, + [FromQuery] DateTime? to = null, + [FromQuery] string? search = null, + CancellationToken ct = default) + { + var result = await _mediator.Send( + new GetAgentLogsQuery(id, page, pageSize, level, from, to, search), ct); + if (!result.IsSuccess) + return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + return Ok(result.Data); + } + /// List all agents across all sites. [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)] [HttpGet] diff --git a/src/Heimdall.Web/Services/HeimdallApiClient.cs b/src/Heimdall.Web/Services/HeimdallApiClient.cs index c9f860e..d25b2b7 100644 --- a/src/Heimdall.Web/Services/HeimdallApiClient.cs +++ b/src/Heimdall.Web/Services/HeimdallApiClient.cs @@ -397,6 +397,16 @@ public class HeimdallApiClient return await client.GetFromJsonAsync>(query, Json); } + public async Task?> GetAgentLogsAsync( + Guid agentId, string? level = null, string? search = null, int page = 1, int pageSize = 50) + { + var client = CreateClient(); + var query = $"api/agents/{agentId}/logs?page={page}&pageSize={pageSize}"; + if (!string.IsNullOrEmpty(level)) query += $"&level={Uri.EscapeDataString(level)}"; + if (!string.IsNullOrEmpty(search)) query += $"&search={Uri.EscapeDataString(search)}"; + return await client.GetFromJsonAsync>(query, Json); + } + public async Task GetStatsAsync() { var client = CreateClient(); @@ -650,6 +660,17 @@ public class AgentItem public long? UptimeSeconds { get; set; } } +public class AgentLogItem +{ + public Guid Id { get; set; } + public Guid AgentId { get; set; } + public DateTime TimestampUtc { get; set; } + public string Level { get; set; } = ""; + public string Message { get; set; } = ""; + public string? Exception { get; set; } + public string? Source { get; set; } +} + // ─── Settings DTOs ──────────────────────────────────────────────── public record AppSettingItem( diff --git a/tests/Heimdall.Agent.Tests/AgentRegistrationServiceTests.cs b/tests/Heimdall.Agent.Tests/AgentRegistrationServiceTests.cs index 65d6a9a..4dd5152 100644 --- a/tests/Heimdall.Agent.Tests/AgentRegistrationServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/AgentRegistrationServiceTests.cs @@ -257,6 +257,7 @@ public class AgentRegistrationServiceTests : IDisposable state, Options.Create(_options), _metrics, + new Logging.LogBufferService(), NullLogger.Instance); } diff --git a/tests/Heimdall.Agent.Tests/LogBufferServiceTests.cs b/tests/Heimdall.Agent.Tests/LogBufferServiceTests.cs new file mode 100644 index 0000000..d2da723 --- /dev/null +++ b/tests/Heimdall.Agent.Tests/LogBufferServiceTests.cs @@ -0,0 +1,91 @@ +using Heimdall.Agent.Logging; +using Microsoft.Extensions.Logging; +using Shouldly; + +namespace Heimdall.Agent.Tests; + +public class LogBufferServiceTests +{ + private static BufferedLogEntry Entry(string message, LogLevel level = LogLevel.Information) + => new(DateTime.UtcNow, level, message, null, "TestService"); + + [Fact] + public void TakeAll_ReturnsEntriesInOrder() + { + var buffer = new LogBufferService(10); + buffer.Enqueue(Entry("first")); + buffer.Enqueue(Entry("second")); + buffer.Enqueue(Entry("third")); + + var entries = buffer.TakeAll(); + + entries.Count.ShouldBe(3); + entries[0].Message.ShouldBe("first"); + entries[1].Message.ShouldBe("second"); + entries[2].Message.ShouldBe("third"); + buffer.Count.ShouldBe(0); + } + + [Fact] + public void TakeAll_WhenEmpty_ReturnsEmptyList() + { + var buffer = new LogBufferService(10); + buffer.TakeAll().ShouldBeEmpty(); + } + + [Fact] + public void Enqueue_WhenFull_DropsOldestAndCounts() + { + var buffer = new LogBufferService(3); + buffer.Enqueue(Entry("a")); + buffer.Enqueue(Entry("b")); + buffer.Enqueue(Entry("c")); + + // Overflow: the newest entry must survive (fresh Error > old Warnings). + buffer.Enqueue(Entry("d")); + buffer.Enqueue(Entry("e")); + + var entries = buffer.TakeAll(); + entries.Select(e => e.Message).ShouldBe(["c", "d", "e"]); + buffer.DroppedCount.ShouldBe(2); + } + + [Fact] + public void Requeue_RestoresFailedUploadEntries() + { + var buffer = new LogBufferService(10); + buffer.Enqueue(Entry("a")); + var taken = buffer.TakeAll(); + + buffer.Requeue(taken); + + buffer.Count.ShouldBe(1); + buffer.TakeAll()[0].Message.ShouldBe("a"); + } + + [Fact] + public void Sanitize_MasksSecrets() + { + LogSanitizer.Sanitize("Connecting with password=hunter2 and token=abc123") + .ShouldNotContain("hunter2"); + LogSanitizer.Sanitize("Connecting with password=hunter2 and token=abc123") + .ShouldContain("***"); + + LogSanitizer.Sanitize("Authorization: Bearer eyJhbGciOiJIUzI1NiJ9") + .ShouldNotContain("eyJhbGciOiJIUzI1NiJ9"); + + LogSanitizer.Sanitize("{\"api_key\":\"super-secret-value\",\"user\":\"bob\"}") + .ShouldNotContain("super-secret-value"); + + LogSanitizer.Sanitize("snapshotUrl=https://cdn.example.com/snap/1.jpg") + .ShouldNotContain("cdn.example.com"); + } + + [Fact] + public void Sanitize_LeavesNormalMessagesIntact() + { + const string message = "Heartbeat OK — agent online"; + LogSanitizer.Sanitize(message).ShouldBe(message); + LogSanitizer.Sanitize(null).ShouldBeEmpty(); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/AgentLogs/GetAgentLogsHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/AgentLogs/GetAgentLogsHandlerTests.cs new file mode 100644 index 0000000..0a1e2fa --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/AgentLogs/GetAgentLogsHandlerTests.cs @@ -0,0 +1,81 @@ +using Heimdall.Application.AgentLogs.Queries.GetAgentLogs; +using Heimdall.Application.Common; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using NSubstitute; +using Shouldly; + +namespace Heimdall.Application.Tests.Handlers.AgentLogs; + +public class GetAgentLogsHandlerTests +{ + private readonly Agent _agent = new(Guid.NewGuid(), "agent-1", "agent-1", "1.0.0"); + private readonly Guid _otherAgent = Guid.NewGuid(); + + private static AgentLogEntry Entry(Guid agentId, AgentLogLevel level, string message, DateTime ts) + => new(agentId, ts, level, message, null, "TestService"); + + private IApplicationDbContext CreateContext() + { + var context = Substitute.For(); + context.Agents.Returns(MockDbSetHelper.CreateFor([_agent])); + context.AgentLogEntries.Returns(MockDbSetHelper.CreateFor( + [ + Entry(_agent.Id, AgentLogLevel.Warning, "first warning", DateTime.UtcNow.AddMinutes(-2)), + Entry(_agent.Id, AgentLogLevel.Error, "ffmpeg crash", DateTime.UtcNow.AddMinutes(-1)), + Entry(_agent.Id, AgentLogLevel.Information, "started", DateTime.UtcNow), + Entry(_otherAgent, AgentLogLevel.Error, "other agent", DateTime.UtcNow) + ])); + return context; + } + + [Fact] + public async Task Get_ReturnsOnlyThisAgentEntries_NewestFirst() + { + var handler = new GetAgentLogsHandler(CreateContext()); + + var result = await handler.Handle( + new GetAgentLogsQuery(_agent.Id, 1, 50), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data!.TotalCount.ShouldBe(3); + result.Data.Items.Select(i => i.Message).ShouldBe(["started", "ffmpeg crash", "first warning"]); + } + + [Fact] + public async Task Get_FiltersByLevel() + { + var handler = new GetAgentLogsHandler(CreateContext()); + + var result = await handler.Handle( + new GetAgentLogsQuery(_agent.Id, 1, 50, Level: "Error"), CancellationToken.None); + + result.Data!.TotalCount.ShouldBe(1); + result.Data.Items.Single().Level.ShouldBe("Error"); + } + + [Fact] + public async Task Get_SearchFiltersMessage() + { + var handler = new GetAgentLogsHandler(CreateContext()); + + var result = await handler.Handle( + new GetAgentLogsQuery(_agent.Id, 1, 50, Search: "ffmpeg"), CancellationToken.None); + + result.Data!.TotalCount.ShouldBe(1); + result.Data.Items.Single().Message.ShouldBe("ffmpeg crash"); + } + + [Fact] + public async Task Get_PaginationSlices() + { + var handler = new GetAgentLogsHandler(CreateContext()); + + var result = await handler.Handle( + new GetAgentLogsQuery(_agent.Id, 1, 2), CancellationToken.None); + + result.Data!.TotalCount.ShouldBe(3); + result.Data.Items.Count.ShouldBe(2); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/AgentLogs/SubmitAgentLogsHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/AgentLogs/SubmitAgentLogsHandlerTests.cs new file mode 100644 index 0000000..f0a4c07 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/AgentLogs/SubmitAgentLogsHandlerTests.cs @@ -0,0 +1,84 @@ +using Heimdall.Application.AgentLogs.Commands.SubmitAgentLogs; +using Heimdall.Application.Common; +using Heimdall.Application.DTOs; +using Heimdall.Application.Tests.Common; +using Heimdall.Domain.Entities; +using NSubstitute; +using Shouldly; + +namespace Heimdall.Application.Tests.Handlers.AgentLogs; + +public class SubmitAgentLogsHandlerTests +{ + private readonly Agent _agent = new(Guid.NewGuid(), "agent-1", "agent-1", "1.0.0"); + + private IApplicationDbContext CreateContext() + { + var context = Substitute.For(); + context.Agents.Returns(MockDbSetHelper.CreateFor([_agent])); + context.AgentLogEntries.Returns(MockDbSetHelper.CreateFor()); + return context; + } + + private static SubmitAgentLogsCommand Command( + Guid agentId, params AgentLogEntryRequest[] entries) => new(agentId, entries); + + [Fact] + public async Task Submit_ValidBatch_ReturnsSuccessAndPersists() + { + var context = CreateContext(); + var handler = new SubmitAgentLogsHandler(context); + var command = Command(_agent.Id, + new AgentLogEntryRequest(DateTime.UtcNow, "Warning", "Heartbeat failed"), + new AgentLogEntryRequest(DateTime.UtcNow, "Error", "FFmpeg crashed", "System.Exception: boom")); + + var result = await handler.Handle(command, CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + context.AgentLogEntries.Count().ShouldBe(2); + } + + [Fact] + public async Task Submit_NonexistentAgent_ReturnsNotFound() + { + var context = CreateContext(); + var handler = new SubmitAgentLogsHandler(context); + var command = Command(Guid.NewGuid(), + new AgentLogEntryRequest(DateTime.UtcNow, "Warning", "msg")); + + var result = await handler.Handle(command, CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(404); + } + + [Fact] + public async Task Submit_InvalidLevelEntries_AreSkipped() + { + var context = CreateContext(); + var handler = new SubmitAgentLogsHandler(context); + var command = Command(_agent.Id, + new AgentLogEntryRequest(DateTime.UtcNow, "Warning", "valid"), + new AgentLogEntryRequest(DateTime.UtcNow, "NotALevel", "invalid level")); + + var result = await handler.Handle(command, CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + context.AgentLogEntries.Count().ShouldBe(1); + context.AgentLogEntries.Single().Message.ShouldBe("valid"); + } + + [Fact] + public async Task Submit_AllEntriesInvalid_ReturnsBadRequest() + { + var context = CreateContext(); + var handler = new SubmitAgentLogsHandler(context); + var command = Command(_agent.Id, + new AgentLogEntryRequest(DateTime.UtcNow, "Bogus", "x")); + + var result = await handler.Handle(command, CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(400); + } +} diff --git a/tests/Heimdall.Web.Tests/Components/Pages/AgentDetailLogsTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/AgentDetailLogsTests.cs new file mode 100644 index 0000000..17a301a --- /dev/null +++ b/tests/Heimdall.Web.Tests/Components/Pages/AgentDetailLogsTests.cs @@ -0,0 +1,127 @@ +using Bunit; +using Heimdall.Web.Components.Pages; +using Heimdall.Web.Services; +using Shouldly; + +namespace Heimdall.Web.Tests.Components.Pages; + +public class AgentDetailLogsTests : PageTestBase +{ + private static readonly Guid AgentId = Guid.NewGuid(); + private static readonly Guid SiteId = Guid.NewGuid(); + + private static AgentItem Agent() => new() + { + Id = AgentId, + SiteId = SiteId, + SiteName = "Site Test", + Name = "Agent Caméras", + Hostname = "cam-01", + Version = "1.0.0", + Status = "Online", + CreatedAt = DateTime.UtcNow.AddDays(-5) + }; + + private static AgentLogItem Log( + string message, + string level = "Warning", + string? source = "AgentRegistrationService", + string? exception = null) => new() + { + Id = Guid.NewGuid(), + AgentId = AgentId, + TimestampUtc = DateTime.UtcNow.AddMinutes(-5), + Level = level, + Message = message, + Source = source, + Exception = exception + }; + + private void HandlerLogs(PagedData data) + => Handler.OnGet($"api/agents/{AgentId}/logs", data); + + private void HandlerBase() + { + // Order matters: RoutedHandler matches by substring, first route wins. + Handler.OnGet($"api/agents/{AgentId}/logs", new PagedData([], 0, 1, 50)); + Handler.OnGet("api/agents/", Agent()); + Handler.OnGet("api/settings/agent/", new List()); + Handler.OnGet("api/settings", new List()); + LoginAs(); + } + + [Fact] + public void AgentLogs_AfficheLesEntreesRemontees() + { + HandlerLogs(new PagedData( + [Log("Heartbeat failed: ServiceUnavailable", "Error", "AgentRegistrationService")], + 1, 1, 50)); + HandlerBase(); + + var cut = RenderPage(p => p.Add(x => x.Id, AgentId)); + + cut.WaitForAssertion(() => + { + cut.Markup.ShouldContain("Agent : Agent Caméras"); + cut.Markup.ShouldContain("Heartbeat failed: ServiceUnavailable"); + cut.Markup.ShouldContain("Error"); + cut.Markup.ShouldContain("AgentRegistrationService"); + cut.Markup.ShouldContain("1 entrée"); + }); + } + + [Fact] + public void AgentLogs_AfficheVide_QuandAucuneEntree() + { + HandlerBase(); + + var cut = RenderPage(p => p.Add(x => x.Id, AgentId)); + + cut.WaitForAssertion(() => + { + cut.Markup.ShouldContain("Aucun log"); + cut.Markup.ShouldContain("L'agent n'a rien remonté pour ces filtres."); + }); + } + + [Fact] + public void AgentLogs_RefreshManuel_RechargeLesLogs() + { + HandlerLogs(new PagedData( + [Log("First batch entry", "Warning")], 1, 1, 50)); + HandlerBase(); + + var cut = RenderPage(p => p.Add(x => x.Id, AgentId)); + + cut.WaitForAssertion(() => cut.Markup.ShouldContain("First batch entry")); + + var initialCount = Handler.Requests.Count(r => + r.RequestUri!.AbsolutePath.Contains($"/api/agents/{AgentId}/logs")); + + // Le bouton refresh (aria-label) recharge les logs. + cut.Find("button[aria-label='Actualiser les logs']").Click(); + + cut.WaitForAssertion(() => + { + var logRequests = Handler.Requests.Count(r => + r.RequestUri!.AbsolutePath.Contains($"/api/agents/{AgentId}/logs")); + logRequests.ShouldBeGreaterThan(initialCount); + }); + } + + [Fact] + public void AgentLogs_Pagination_AfficheLeCompteur() + { + HandlerLogs(new PagedData( + [Log("Warning one"), Log("Warning two")], 7, 1, 50)); + HandlerBase(); + + var cut = RenderPage(p => p.Add(x => x.Id, AgentId)); + + cut.WaitForAssertion(() => + { + cut.Markup.ShouldContain("Page 1 sur 1"); + cut.Markup.ShouldContain("7 entrées"); + }); + } +}