diff --git a/Heimdall.slnx b/Heimdall.slnx index bef2c7d..4601088 100644 --- a/Heimdall.slnx +++ b/Heimdall.slnx @@ -2,6 +2,7 @@ + diff --git a/docker/docker-compose.prod.yml b/docker/docker-compose.prod.yml index 843e031..d89a888 100644 --- a/docker/docker-compose.prod.yml +++ b/docker/docker-compose.prod.yml @@ -90,6 +90,11 @@ services: heimdall: image: eltruncho/heimdall:latest environment: + # MassTransit / RabbitMQ + RABBITMQ__HOST: rabbitmq + RABBITMQ__PORT: "5672" + RABBITMQ__USER: ${RABBITMQ_USER:-heimdall} + RABBITMQ__PASSWORD_FILE: /run/secrets/rabbitmq_password # Database (password from secret, rest from env) DATABASE_URL: ${DATABASE_URL:?DATABASE_URL is required} # JWT (keys from secrets) @@ -167,6 +172,11 @@ services: Agent__AgentName: ${HEIMDALL_AGENT_NAME:-agent-01} Agent__HeartbeatIntervalSeconds: ${HEIMDALL_HEARTBEAT_INTERVAL:-30} Agent__StateDirectory: /var/lib/heimdall + # MassTransit / RabbitMQ — host network can't resolve Docker DNS + RABBITMQ__HOST: ${RABBITMQ_HOST:-localhost} + RABBITMQ__PORT: ${RABBITMQ_PORT:-5672} + RABBITMQ__USER: ${RABBITMQ_USER:-heimdall} + RABBITMQ__PASSWORD: ${RABBITMQ_PASSWORD:-heimdall123} healthcheck: test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8081/healthz"] interval: 30s @@ -181,6 +191,27 @@ services: logging: *default-logging # no networks: host networking + rabbitmq: + image: rabbitmq:3-management + hostname: rabbitmq + environment: + RABBITMQ_DEFAULT_USER: ${RABBITMQ_USER:-heimdall} + RABBITMQ_DEFAULT_PASS_FILE: /run/secrets/rabbitmq_password + secrets: + - rabbitmq_password + volumes: + - rabbitmq_data:/var/lib/rabbitmq + healthcheck: + test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"] + interval: 15s + timeout: 5s + retries: 5 + start_period: 30s + restart: unless-stopped + logging: *default-logging + networks: + - heimdall-net + # ── Optional services ────────────────────────────────────────── coturn: @@ -263,6 +294,8 @@ volumes: driver: local redis_data: driver: local + rabbitmq_data: + driver: local secrets: db_password: @@ -279,6 +312,8 @@ secrets: file: ./secrets/alarik_jwt smtp_password: file: ./secrets/smtp_password + rabbitmq_password: + file: ./secrets/rabbitmq_password networks: heimdall-net: diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index e6b3131..906d14a 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -75,6 +75,11 @@ services: dockerfile: docker/Dockerfile image: heimdall:latest environment: + # MassTransit / RabbitMQ + RABBITMQ__HOST: rabbitmq + RABBITMQ__PORT: "5672" + RABBITMQ__USER: ${RABBITMQ_USER:-heimdall} + RABBITMQ__PASSWORD: ${RABBITMQ_PASSWORD:-heimdall123} # Database DATABASE_URL: ${DATABASE_URL:-Host=postgresql;Port=5432;Database=heimdall;Username=heimdall;Password=heimdall} # JWT @@ -145,6 +150,11 @@ services: Agent__HeartbeatIntervalSeconds: ${HEIMDALL_HEARTBEAT_INTERVAL:-30} Agent__StateDirectory: /var/lib/heimdall Agent__RegistrationMaxRetries: ${HEIMDALL_REGISTRATION_RETRIES:-5} + # MassTransit / RabbitMQ — host network can't resolve Docker DNS + RABBITMQ__HOST: ${RABBITMQ_HOST:-localhost} + RABBITMQ__PORT: ${RABBITMQ_PORT:-5672} + RABBITMQ__USER: ${RABBITMQ_USER:-heimdall} + RABBITMQ__PASSWORD: ${RABBITMQ_PASSWORD:-heimdall123} volumes: - agent_state:/var/lib/heimdall healthcheck: @@ -159,6 +169,28 @@ services: logging: *default-logging # no networks: host networking + rabbitmq: + image: rabbitmq:3-management + hostname: rabbitmq + environment: + RABBITMQ_DEFAULT_USER: ${RABBITMQ_USER:-heimdall} + RABBITMQ_DEFAULT_PASS: ${RABBITMQ_PASSWORD:-heimdall123} + ports: + - "${RABBITMQ_PORT:-5672}:5672" + - "${RABBITMQ_MGMT_PORT:-15672}:15672" + volumes: + - rabbitmq_data:/var/lib/rabbitmq + healthcheck: + test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"] + interval: 15s + timeout: 5s + retries: 5 + start_period: 30s + restart: unless-stopped + logging: *default-logging + networks: + - heimdall-net + # ── Optional services (dev) ──────────────────────────────────── coturn: @@ -225,6 +257,8 @@ volumes: driver: local redis_data: driver: local + rabbitmq_data: + driver: local networks: heimdall-net: diff --git a/src/Heimdall.Agent/AnalysisJobConsumer.cs b/src/Heimdall.Agent/AnalysisJobConsumer.cs new file mode 100644 index 0000000..e5b331e --- /dev/null +++ b/src/Heimdall.Agent/AnalysisJobConsumer.cs @@ -0,0 +1,125 @@ +using System.Diagnostics; +using Heimdall.Contracts; +using Heimdall.Agent.Services; +using MassTransit; +using Microsoft.Extensions.Logging; + +namespace Heimdall.Agent; + +/// +/// MassTransit consumer that processes messages. +/// When the Central dispatches an analysis job via RabbitMQ, this consumer runs the +/// local AI pipeline (YOLO/ONNX) on the provided frame and publishes a completion +/// or failure message back to the Central. +/// +/// Configuration: PrefetchCount=1, ConcurrentMessageLimit=1 (one job at a time) +/// to avoid overloading the agent's GPU/CPU resources. +/// +public sealed class AnalysisJobConsumer : IConsumer +{ + private readonly FrameAnalyzerService _frameAnalyzer; + private readonly AgentState _state; + private readonly ILogger _logger; + + public AnalysisJobConsumer( + FrameAnalyzerService frameAnalyzer, + AgentState state, + ILogger logger) + { + _frameAnalyzer = frameAnalyzer; + _state = state; + _logger = logger; + } + + public async Task Consume(ConsumeContext context) + { + var job = context.Message; + var agentId = _state.AgentId; + + if (agentId == Guid.Empty) + { + _logger.LogWarning( + "Ignoring analysis job {JobId}: agent not registered yet", + job.Id); + await context.Publish(new AnalysisJobFailed + { + JobId = job.Id, + Reason = "Agent not registered", + IsTransient = true, + }); + return; + } + + if (agentId != job.AgentId) + { + _logger.LogDebug( + "Ignoring analysis job {JobId}: assigned to agent {TargetAgentId}, not {LocalAgentId}", + job.Id, job.AgentId, agentId); + return; + } + + _logger.LogInformation( + "Processing analysis job {JobId} for camera {CameraId} (site {SiteId})", + job.Id, job.CameraId, job.SiteId); + + var stopwatch = Stopwatch.StartNew(); + + try + { + // Decode the Base64 frame data + var frameData = Convert.FromBase64String(job.FrameData); + + // Run the local AI analysis pipeline + var result = await _frameAnalyzer.AnalyzeFrameAsync( + frameData, ct: context.CancellationToken); + + stopwatch.Stop(); + + var detections = result?.Detections; + var detectionCount = detections?.Count ?? 0; + var averageConfidence = detectionCount > 0 + ? detections!.Average(d => d.Confidence) + : 0.0; + + _logger.LogInformation( + "Job {JobId} completed: {DetectionCount} detections, {Confidence:P0} confidence, {Duration}ms", + job.Id, detectionCount, averageConfidence, stopwatch.ElapsedMilliseconds); + + // Publish completion back to the Central + await context.Publish(new AnalysisJobCompleted + { + JobId = job.Id, + Detections = detectionCount, + Confidence = averageConfidence, + DurationMs = stopwatch.ElapsedMilliseconds, + DetectionDetails = detectionCount > 0 + ? System.Text.Json.JsonSerializer.Serialize(detections) + : null, + }); + } + catch (Exception ex) + { + stopwatch.Stop(); + + _logger.LogError(ex, + "Job {JobId} failed after {Duration}ms: {Reason}", + job.Id, stopwatch.ElapsedMilliseconds, ex.Message); + + await context.Publish(new AnalysisJobFailed + { + JobId = job.Id, + Reason = ex.Message, + IsTransient = IsTransientException(ex), + }); + } + } + + private static bool IsTransientException(Exception ex) => ex switch + { + TimeoutException => true, + OperationCanceledException => true, + System.Net.Http.HttpRequestException => true, + System.IO.IOException => true, + _ => false, + }; +} diff --git a/src/Heimdall.Agent/Heimdall.Agent.csproj b/src/Heimdall.Agent/Heimdall.Agent.csproj index c15aafc..2b34551 100644 --- a/src/Heimdall.Agent/Heimdall.Agent.csproj +++ b/src/Heimdall.Agent/Heimdall.Agent.csproj @@ -13,6 +13,7 @@ + @@ -27,6 +28,8 @@ + + diff --git a/src/Heimdall.Agent/MassTransitConfiguration.cs b/src/Heimdall.Agent/MassTransitConfiguration.cs new file mode 100644 index 0000000..66127ea --- /dev/null +++ b/src/Heimdall.Agent/MassTransitConfiguration.cs @@ -0,0 +1,69 @@ +using System.Globalization; +using Heimdall.Agent.Services; +using Heimdall.Contracts; +using MassTransit; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +namespace Heimdall.Agent; + +/// +/// Configures MassTransit with RabbitMQ transport for the Agent (consumer). +/// The Agent consumes messages dispatched by +/// the Central, runs the local AI pipeline, and publishes +/// or . +/// +public static class MassTransitConfiguration +{ + /// + /// Configuration section name for RabbitMQ settings. + /// + private const string SectionName = "RabbitMQ"; + + /// + /// Adds MassTransit with RabbitMQ transport for the Agent (consumer + publisher). + /// Registers to process incoming analysis requests. + /// Concurrency is limited to 1 message at a time to avoid overloading GPU/CPU. + /// + public static IServiceCollection AddHeimdallAgentMassTransit( + this IServiceCollection services, + IConfiguration configuration) + { + var host = configuration[$"{SectionName}:Host"] + ?? Environment.GetEnvironmentVariable("RABBITMQ__HOST") + ?? "localhost"; + var port = configuration.GetValue($"{SectionName}:Port", + int.Parse( + Environment.GetEnvironmentVariable("RABBITMQ__PORT") ?? "5672", + CultureInfo.InvariantCulture)); + var user = configuration[$"{SectionName}:User"] + ?? Environment.GetEnvironmentVariable("RABBITMQ__USER") + ?? "heimdall"; + var password = configuration[$"{SectionName}:Password"] + ?? Environment.GetEnvironmentVariable("RABBITMQ__PASSWORD") + ?? "heimdall123"; + + services.AddMassTransit(x => + { + x.AddConsumer(cfg => + { + cfg.ConcurrentMessageLimit = 1; + }); + + x.UsingRabbitMq((context, cfg) => + { + cfg.Host(host, (ushort)port, "/", h => + { + h.Username(user); + h.Password(password); + }); + + cfg.ConfigureEndpoints(context); + }); + }); + + Console.WriteLine($"[DIAG] MassTransit Agent RabbitMQ: host={host}:{port}, user={user}"); + + return services; + } +} diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs index cabb0af..eb7ae90 100644 --- a/src/Heimdall.Agent/Program.cs +++ b/src/Heimdall.Agent/Program.cs @@ -154,6 +154,9 @@ builder.Services.AddHealthChecks() .AddCheck("agent_health", tags: ["ready"]) .AddCheck("live", tags: ["live"]); +// MassTransit + RabbitMQ — consume AnalysisJobRequested, publish results +builder.Services.AddHeimdallAgentMassTransit(builder.Configuration); + // ── OpenTelemetry metrics (spec 13.1) ────────────────────────────── builder.Services.AddOpenTelemetry() .WithMetrics(metrics => diff --git a/src/Heimdall.Contracts/AnalysisJobCompleted.cs b/src/Heimdall.Contracts/AnalysisJobCompleted.cs new file mode 100644 index 0000000..2852f81 --- /dev/null +++ b/src/Heimdall.Contracts/AnalysisJobCompleted.cs @@ -0,0 +1,26 @@ +namespace Heimdall.Contracts; + +/// +/// Message published by an agent after a successful analysis. +/// The Central consumes this message to persist detections and update camera state. +/// +public sealed record AnalysisJobCompleted +{ + /// Identifier of the job that completed (matches ). + public required Guid JobId { get; init; } + + /// Number of objects detected in the frame. + public int Detections { get; init; } + + /// Average confidence of detections (0.0 – 1.0). + public double Confidence { get; init; } + + /// Duration of the analysis in milliseconds. + public long DurationMs { get; init; } + + /// Optional serialised detection details (labels, bounding boxes). + public string? DetectionDetails { get; init; } + + /// Timestamp when the analysis completed (UTC). + public DateTime CompletedAtUtc { get; init; } = DateTime.UtcNow; +} diff --git a/src/Heimdall.Contracts/AnalysisJobFailed.cs b/src/Heimdall.Contracts/AnalysisJobFailed.cs new file mode 100644 index 0000000..6bb7fc6 --- /dev/null +++ b/src/Heimdall.Contracts/AnalysisJobFailed.cs @@ -0,0 +1,20 @@ +namespace Heimdall.Contracts; + +/// +/// Message published by an agent when an analysis job fails. +/// The Central consumes this message for logging and retry decisions. +/// +public sealed record AnalysisJobFailed +{ + /// Identifier of the job that failed (matches ). + public required Guid JobId { get; init; } + + /// Human-readable description of the failure reason. + public required string Reason { get; init; } + + /// Whether the failure is transient and the job may be retried. + public bool IsTransient { get; init; } + + /// Timestamp when the failure occurred (UTC). + public DateTime FailedAtUtc { get; init; } = DateTime.UtcNow; +} diff --git a/src/Heimdall.Contracts/AnalysisJobRequested.cs b/src/Heimdall.Contracts/AnalysisJobRequested.cs new file mode 100644 index 0000000..6c9b312 --- /dev/null +++ b/src/Heimdall.Contracts/AnalysisJobRequested.cs @@ -0,0 +1,35 @@ +namespace Heimdall.Contracts; + +/// +/// Message published by the Central to request an analysis job from an agent. +/// The agent consumes this message and runs the AI pipeline (YOLO/ONNX) on the +/// provided frame data, then publishes or +/// . +/// +public sealed record AnalysisJobRequested +{ + /// Unique identifier for this analysis job. + public Guid Id { get; init; } = Guid.NewGuid(); + + /// Identifier of the camera whose frame is to be analysed. + public required Guid CameraId { get; init; } + + /// Identifier of the site the camera belongs to. + public required Guid SiteId { get; init; } + + /// Identifier of the target agent that should run the analysis. + public required Guid AgentId { get; init; } + + /// + /// Base64-encoded JPEG frame data to analyse. + /// Agents behind NAT receive the frame through AMQP rather than pulling it + /// via HTTPS — avoids requiring inbound connectivity to the Central. + /// + public required string FrameData { get; init; } + + /// Optional metadata (model override, confidence threshold, etc.). + public Dictionary? Metadata { get; init; } + + /// Timestamp when the job was created (UTC). + public DateTime RequestedAtUtc { get; init; } = DateTime.UtcNow; +} diff --git a/src/Heimdall.Contracts/Heimdall.Contracts.csproj b/src/Heimdall.Contracts/Heimdall.Contracts.csproj new file mode 100644 index 0000000..9ed914b --- /dev/null +++ b/src/Heimdall.Contracts/Heimdall.Contracts.csproj @@ -0,0 +1,9 @@ + + + + net10.0 + enable + enable + + + diff --git a/src/Heimdall.Web/Heimdall.Web.csproj b/src/Heimdall.Web/Heimdall.Web.csproj index 50a769a..3d132da 100644 --- a/src/Heimdall.Web/Heimdall.Web.csproj +++ b/src/Heimdall.Web/Heimdall.Web.csproj @@ -16,6 +16,7 @@ + @@ -28,6 +29,8 @@ + + diff --git a/src/Heimdall.Web/MassTransitConfiguration.cs b/src/Heimdall.Web/MassTransitConfiguration.cs new file mode 100644 index 0000000..cfcd759 --- /dev/null +++ b/src/Heimdall.Web/MassTransitConfiguration.cs @@ -0,0 +1,62 @@ +using System.Globalization; +using Heimdall.Contracts; +using MassTransit; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +namespace Heimdall.Web; + +/// +/// Configures MassTransit with RabbitMQ for the Central (Web) service. +/// The Central publishes messages to dispatch +/// work to remote agents, and consumes and +/// messages to track job lifecycle. +/// +public static class MassTransitConfiguration +{ + /// + /// Configuration section name for RabbitMQ settings (RabbitMQ:Host, RabbitMQ:Port, etc.). + /// + private const string SectionName = "RabbitMQ"; + + /// + /// Adds MassTransit with RabbitMQ transport for the Central (publisher). + /// Exposes via DI for dispatching analysis jobs. + /// + public static IServiceCollection AddHeimdallMassTransit( + this IServiceCollection services, + IConfiguration configuration) + { + var host = configuration[$"{SectionName}:Host"] + ?? Environment.GetEnvironmentVariable("RABBITMQ__HOST") + ?? "localhost"; + var port = configuration.GetValue($"{SectionName}:Port", + int.Parse( + Environment.GetEnvironmentVariable("RABBITMQ__PORT") ?? "5672", + CultureInfo.InvariantCulture)); + var user = configuration[$"{SectionName}:User"] + ?? Environment.GetEnvironmentVariable("RABBITMQ__USER") + ?? "heimdall"; + var password = configuration[$"{SectionName}:Password"] + ?? Environment.GetEnvironmentVariable("RABBITMQ__PASSWORD") + ?? "heimdall123"; + + services.AddMassTransit(x => + { + x.UsingRabbitMq((context, cfg) => + { + cfg.Host(host, (ushort)port, "/", h => + { + h.Username(user); + h.Password(password); + }); + + cfg.ConfigureEndpoints(context); + }); + }); + + Console.WriteLine($"[DIAG] MassTransit RabbitMQ: host={host}:{port}, user={user}"); + + return services; + } +} diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs index d097276..398ad75 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -15,7 +15,9 @@ using Heimdall.Web.Components; using Heimdall.Api.Hubs; using Heimdall.Api; using Heimdall.Web.Services; +using Heimdall.Web; using Hangfire; +using MassTransit; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.JwtBearer; @@ -426,6 +428,7 @@ public partial class Program ConfigureAuthScheme(builder); ConfigureBackgroundJobs(builder); ConfigureHttpClients(builder); + ConfigureMassTransit(builder); builder.Services.AddScoped(); } @@ -532,6 +535,15 @@ public partial class Program builder.Services.AddBackgroundJobs(builder.Configuration); } + private static void ConfigureMassTransit(WebApplicationBuilder builder) + { + var isTesting = builder.Environment.IsEnvironment(TestingEnvironment); + if (!isTesting) + { + builder.Services.AddHeimdallMassTransit(builder.Configuration); + } + } + private static void ConfigureHttpClients(WebApplicationBuilder builder) { builder.Services.AddHttpContextAccessor();