feat(broker): RabbitMQ + MassTransit job broker pour l'analyse inter-sites

feat(broker): add RabbitMQ + MassTransit job broker for cross-site analysis

Mutualise les ressources IA/GPU entre sites via un broker de jobs durable.
RabbitMQ + MassTransit avec connexion AMQP sortante (pas de port entrant).

- Heimdall.Contracts: contrats de messages partagés
- RabbitMQ: conteneur docker + credentials via env vars
- MassTransit Central: publication de jobs d'analyse
- MassTransit Agent: consommateur avec backpressure GPU

Fixes #72
This commit is contained in:
Arnaud Dartois authored and Arnaud Dartois committed 2026-08-28 01:11:12 +02:00
1 parent b97d3bec11
commit bf2ccad537
14 files changed
+437

No files matched your search

+1
View File
@@ -2,6 +2,7 @@
<Folder Name="/src/">
<Project Path="src/Heimdall.Agent/Heimdall.Agent.csproj" />
<Project Path="src/Heimdall.Application/Heimdall.Application.csproj" />
<Project Path="src/Heimdall.Contracts/Heimdall.Contracts.csproj" />
<Project Path="src/Heimdall.Domain.Primitives/Heimdall.Domain.Primitives.csproj" />
<Project Path="src/Heimdall.Domain/Heimdall.Domain.csproj" />
<Project Path="src/Heimdall.Infrastructure/Heimdall.Infrastructure.csproj" />
+35
View File
@@ -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:
+34
View File
@@ -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:
+125
View File
@@ -0,0 +1,125 @@
using System.Diagnostics;
using Heimdall.Contracts;
using Heimdall.Agent.Services;
using MassTransit;
using Microsoft.Extensions.Logging;
namespace Heimdall.Agent;
/// <summary>
/// MassTransit consumer that processes <see cref="AnalysisJobRequested"/> 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.
/// </summary>
public sealed class AnalysisJobConsumer : IConsumer<AnalysisJobRequested>
{
private readonly FrameAnalyzerService _frameAnalyzer;
private readonly AgentState _state;
private readonly ILogger<AnalysisJobConsumer> _logger;
public AnalysisJobConsumer(
FrameAnalyzerService frameAnalyzer,
AgentState state,
ILogger<AnalysisJobConsumer> logger)
{
_frameAnalyzer = frameAnalyzer;
_state = state;
_logger = logger;
}
public async Task Consume(ConsumeContext<AnalysisJobRequested> 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,
};
}
+3
View File
@@ -13,6 +13,7 @@
<ItemGroup>
<ProjectReference Include="..\Heimdall.Application\Heimdall.Application.csproj" />
<ProjectReference Include="..\Heimdall.Contracts\Heimdall.Contracts.csproj" />
</ItemGroup>
<ItemGroup>
@@ -27,6 +28,8 @@
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.17.0" />
<PackageReference Include="Sentry.AspNetCore" Version="6.8.0" />
<PackageReference Include="Magick.NET-Q16-AnyCPU" Version="14.16.0" />
<PackageReference Include="MassTransit" Version="8.3.6" />
<PackageReference Include="MassTransit.RabbitMQ" Version="8.3.6" />
<PackageReference Include="SixLabors.ImageSharp" Version="3.0.3" />
</ItemGroup>
</Project>
@@ -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;
/// <summary>
/// Configures MassTransit with RabbitMQ transport for the Agent (consumer).
/// The Agent consumes <see cref="AnalysisJobRequested"/> messages dispatched by
/// the Central, runs the local AI pipeline, and publishes
/// <see cref="AnalysisJobCompleted"/> or <see cref="AnalysisJobFailed"/>.
/// </summary>
public static class MassTransitConfiguration
{
/// <summary>
/// Configuration section name for RabbitMQ settings.
/// </summary>
private const string SectionName = "RabbitMQ";
/// <summary>
/// Adds MassTransit with RabbitMQ transport for the Agent (consumer + publisher).
/// Registers <see cref="AnalysisJobConsumer"/> to process incoming analysis requests.
/// Concurrency is limited to 1 message at a time to avoid overloading GPU/CPU.
/// </summary>
public static IServiceCollection AddHeimdallAgentMassTransit(
this IServiceCollection services,
IConfiguration configuration)
{
var host = configuration[$"{SectionName}:Host"]
?? Environment.GetEnvironmentVariable("RABBITMQ__HOST")
?? "localhost";
var port = configuration.GetValue<int>($"{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<AnalysisJobConsumer>(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;
}
}
+3
View File
@@ -154,6 +154,9 @@ builder.Services.AddHealthChecks()
.AddCheck<AgentHealthCheck>("agent_health", tags: ["ready"])
.AddCheck<LiveHealthCheck>("live", tags: ["live"]);
// MassTransit + RabbitMQ — consume AnalysisJobRequested, publish results
builder.Services.AddHeimdallAgentMassTransit(builder.Configuration);
// ── OpenTelemetry metrics (spec 13.1) ──────────────────────────────
builder.Services.AddOpenTelemetry()
.WithMetrics(metrics =>
@@ -0,0 +1,26 @@
namespace Heimdall.Contracts;
/// <summary>
/// Message published by an agent after a successful analysis.
/// The Central consumes this message to persist detections and update camera state.
/// </summary>
public sealed record AnalysisJobCompleted
{
/// <summary>Identifier of the job that completed (matches <see cref="AnalysisJobRequested.Id"/>).</summary>
public required Guid JobId { get; init; }
/// <summary>Number of objects detected in the frame.</summary>
public int Detections { get; init; }
/// <summary>Average confidence of detections (0.0 – 1.0).</summary>
public double Confidence { get; init; }
/// <summary>Duration of the analysis in milliseconds.</summary>
public long DurationMs { get; init; }
/// <summary>Optional serialised detection details (labels, bounding boxes).</summary>
public string? DetectionDetails { get; init; }
/// <summary>Timestamp when the analysis completed (UTC).</summary>
public DateTime CompletedAtUtc { get; init; } = DateTime.UtcNow;
}
@@ -0,0 +1,20 @@
namespace Heimdall.Contracts;
/// <summary>
/// Message published by an agent when an analysis job fails.
/// The Central consumes this message for logging and retry decisions.
/// </summary>
public sealed record AnalysisJobFailed
{
/// <summary>Identifier of the job that failed (matches <see cref="AnalysisJobRequested.Id"/>).</summary>
public required Guid JobId { get; init; }
/// <summary>Human-readable description of the failure reason.</summary>
public required string Reason { get; init; }
/// <summary>Whether the failure is transient and the job may be retried.</summary>
public bool IsTransient { get; init; }
/// <summary>Timestamp when the failure occurred (UTC).</summary>
public DateTime FailedAtUtc { get; init; } = DateTime.UtcNow;
}
@@ -0,0 +1,35 @@
namespace Heimdall.Contracts;
/// <summary>
/// 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 <see cref="AnalysisJobCompleted"/> or
/// <see cref="AnalysisJobFailed"/>.
/// </summary>
public sealed record AnalysisJobRequested
{
/// <summary>Unique identifier for this analysis job.</summary>
public Guid Id { get; init; } = Guid.NewGuid();
/// <summary>Identifier of the camera whose frame is to be analysed.</summary>
public required Guid CameraId { get; init; }
/// <summary>Identifier of the site the camera belongs to.</summary>
public required Guid SiteId { get; init; }
/// <summary>Identifier of the target agent that should run the analysis.</summary>
public required Guid AgentId { get; init; }
/// <summary>
/// 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.
/// </summary>
public required string FrameData { get; init; }
/// <summary>Optional metadata (model override, confidence threshold, etc.).</summary>
public Dictionary<string, string>? Metadata { get; init; }
/// <summary>Timestamp when the job was created (UTC).</summary>
public DateTime RequestedAtUtc { get; init; } = DateTime.UtcNow;
}
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
+3
View File
@@ -16,6 +16,7 @@
<ItemGroup>
<ProjectReference Include="..\Heimdall.Application\Heimdall.Application.csproj" />
<ProjectReference Include="..\Heimdall.Contracts\Heimdall.Contracts.csproj" />
<ProjectReference Include="..\Heimdall.Infrastructure\Heimdall.Infrastructure.csproj" />
</ItemGroup>
@@ -28,6 +29,8 @@
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.17.0" />
<PackageReference Include="Scalar.AspNetCore" Version="2.0.2" />
<PackageReference Include="Hangfire.PostgreSql" Version="1.21.1" />
<PackageReference Include="MassTransit" Version="8.3.6" />
<PackageReference Include="MassTransit.RabbitMQ" Version="8.3.6" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.11" />
<PackageReference Include="MudBlazor" Version="9.8.0" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="10.0.8" />
@@ -0,0 +1,62 @@
using System.Globalization;
using Heimdall.Contracts;
using MassTransit;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Heimdall.Web;
/// <summary>
/// Configures MassTransit with RabbitMQ for the Central (Web) service.
/// The Central publishes <see cref="AnalysisJobRequested"/> messages to dispatch
/// work to remote agents, and consumes <see cref="AnalysisJobCompleted"/> and
/// <see cref="AnalysisJobFailed"/> messages to track job lifecycle.
/// </summary>
public static class MassTransitConfiguration
{
/// <summary>
/// Configuration section name for RabbitMQ settings (RabbitMQ:Host, RabbitMQ:Port, etc.).
/// </summary>
private const string SectionName = "RabbitMQ";
/// <summary>
/// Adds MassTransit with RabbitMQ transport for the Central (publisher).
/// Exposes <see cref="IPublishEndpoint"/> via DI for dispatching analysis jobs.
/// </summary>
public static IServiceCollection AddHeimdallMassTransit(
this IServiceCollection services,
IConfiguration configuration)
{
var host = configuration[$"{SectionName}:Host"]
?? Environment.GetEnvironmentVariable("RABBITMQ__HOST")
?? "localhost";
var port = configuration.GetValue<int>($"{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;
}
}
+12
View File
@@ -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<AuthState>();
}
@@ -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();