Files
Heimdall/docs/hangfire-usage.md
T
arnaud.dartois 021bdecab3
Heimdall Gitea / Detect CI scope (push) Successful in 4s
Heimdall Gitea / Build and tests (push) Skipped
Heimdall Gitea / Build and scan server image (push) Skipped
Heimdall Gitea / Build and scan agent image (push) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Skipped
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 1s
docs: align Hangfire dashboard guide with route (#370)
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-13 10:38:44 +01:00

16 KiB

Heimdall — Hangfire : Tous les jobs, Central & Agent

Stack :

  • Central : Hangfire.PostgreSql (persistance PostgreSQL)
  • Agent : Hangfire.InMemory (pas de config supplémentaire, les jobs Agent sont volatiles)
  • Dashboard : Intégré à l'UI Admin (authentifié)

1. Architecture Hangfire

┌─────────────────────────────────────────────────────────────┐
│                     SERVEUR CENTRAL                          │
│                                                              │
│  Hangfire Server                                             │
│  ├── Storage: PostgreSQL (Hangfire.PostgreSql)              │
│  ├── Dashboard: /hangfire (AdminJobs ou rôle Admin)           │
│  └── Jobs:                                                   │
│      ├── RetentionCheck         (Recurring, daily)           │
│      ├── S3Cleanup              (Recurring, daily)           │
│      ├── CleanupUnknownFaces    (Recurring, weekly)          │
│      ├── CleanupLicensePlates   (Recurring, weekly)          │
│      ├── DatabaseMaintenance    (Recurring, monthly)         │
│      ├── SendNotification       (Fire-and-forget, many)      │
│      └── DailyDigest / WeeklyDigest (Recurring)              │
│                                                              │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│                     HEIMDALL AGENT (site distant)            │
│                                                              │
│  Hangfire Server (léger)                                     │
│  ├── Storage: InMemory (volatile, pas de config SQLite)      │
│  ├── Pas de dashboard (pas exposé)                           │
│  └── Jobs:                                                   │
│      ├── CameraHealthCheck     (Recurring, 30s)              │
│      ├── HeartbeatSender       (Recurring, 30s)              │
│      ├── GpuWatchdog           (Recurring, 60s)              │
│      └── LocalRetentionCleanup (Recurring, hourly)           │
│                                                              │
│  IMPORTANT: Les jobs Agent sont VOLATILES — ils disparaissent │
│  au redémarrage de l'Agent. C'est voulu : l'Agent se          │
│  réenregistre et recrée ses jobs au démarrage.               │
└─────────────────────────────────────────────────────────────┘

2. Central — Jobs détaillés

2.1 RetentionCheck

[AutomaticRetry(Attempts = 2)]
public class RetentionCheckJob
{
    public async Task ExecuteAsync(CancellationToken ct)
    {
        var policies = await _db.StoragePolicies
            .Include(p => p.Camera)
            .ToListAsync(ct);

        foreach (var policy in policies)
        {
            var cutoff = DateTime.UtcNow.AddDays(-policy.RetentionDays);
            var storageProvider = _storageFactory.GetProvider(policy.Provider);

            // 1. Supprimer les enregistrements expirés en DB
            var expired = await _db.Recordings
                .Where(r => r.CameraId == policy.CameraId
                         && r.Timestamp < cutoff)
                .ToListAsync(ct);

            _db.Recordings.RemoveRange(expired);

            // 2. Supprimer les fichiers du storage (RustFS/S3)
            foreach (var recording in expired)
            {
                await storageProvider.DeleteAsync(recording.StoragePath, ct);
            }

            _logger.LogInformation(
                "Retention: supprimé {Count} enregistrements pour caméra {CameraId}",
                expired.Count, policy.CameraId);
        }

        await _db.SaveChangesAsync(ct);
    }
}

// Schedule
RecurringJob.AddOrUpdate<RetentionCheckJob>(
    "retention-check",
    j => j.ExecuteAsync(CancellationToken.None),
    Cron.Daily);

2.2 S3Cleanup

public class S3CleanupJob
{
    public async Task ExecuteAsync(CancellationToken ct)
    {
        // 1. Lister les fichiers dans RustFS (prefix recordings/)
        var allFiles = await _storage.ListAsync("recordings/", ct);

        // 2. Récupérer les chemins enregistrés en DB
        var knownPaths = await _db.Recordings
            .Select(r => r.StoragePath)
            .ToHashSetAsync(ct);

        // 3. Supprimer les fichiers orphelins (dans S3 mais pas en DB)
        var orphanCount = 0;
        foreach (var file in allFiles)
        {
            if (!knownPaths.Contains(file))
            {
                await _storage.DeleteAsync(file, ct);
                orphanCount++;
            }
        }

        _logger.LogInformation("S3Cleanup: supprimé {Count} fichiers orphelins", orphanCount);
    }
}

// Schedule
RecurringJob.AddOrUpdate<S3CleanupJob>(
    "s3-cleanup",
    j => j.ExecuteAsync(CancellationToken.None),
    Cron.Daily);

2.3 CleanupUnknownFaces

public class CleanupUnknownFacesJob
{
    public async Task ExecuteAsync(CancellationToken ct)
    {
        var cutoff = DateTime.UtcNow.AddDays(-30);
        var oldUnknowns = await _db.Persons
            .Where(p => p.IsUnknown && p.CreatedAt < cutoff)
            .ToListAsync(ct);

        _db.Persons.RemoveRange(oldUnknowns);
        await _db.SaveChangesAsync(ct);

        // Supprimer les snapshots associés
        foreach (var person in oldUnknowns)
        {
            await _storage.DeleteAsync($"snapshots/unknown/{person.Id}", ct);
        }

        _logger.LogInformation(
            "CleanupUnknownFaces: supprimé {Count} visages inconnus", oldUnknowns.Count);
    }
}

// Schedule
RecurringJob.AddOrUpdate<CleanupUnknownFacesJob>(
    "cleanup-unknown-faces",
    j => j.ExecuteAsync(CancellationToken.None),
    Cron.Weekly);

2.4 CleanupLicensePlates

public class CleanupLicensePlatesJob
{
    public async Task ExecuteAsync(CancellationToken ct)
    {
        var cutoff = DateTime.UtcNow.AddDays(-30);
        var unassociated = await _db.LicensePlates
            .Where(lp => lp.PersonId == null && lp.CreatedAt < cutoff)
            .ToListAsync(ct);

        _db.LicensePlates.RemoveRange(unassociated);
        await _db.SaveChangesAsync(ct);

        _logger.LogInformation(
            "CleanupLicensePlates: supprimé {Count} plaques non associées",
            unassociated.Count);
    }
}

// Schedule
RecurringJob.AddOrUpdate<CleanupLicensePlatesJob>(
    "cleanup-license-plates",
    j => j.ExecuteAsync(CancellationToken.None),
    Cron.Weekly);

2.5 DatabaseMaintenance

public class DatabaseMaintenanceJob
{
    public async Task ExecuteAsync(CancellationToken ct)
    {
        await _db.Database.ExecuteSqlRawAsync(
            "REINDEX DATABASE \"Heimdall\"", ct);
        await _db.Database.ExecuteSqlRawAsync(
            "VACUUM ANALYZE", ct);

        _logger.LogInformation("Database maintenance completed");
    }
}

// Schedule
RecurringJob.AddOrUpdate<DatabaseMaintenanceJob>(
    "database-maintenance",
    j => j.ExecuteAsync(CancellationToken.None),
    Cron.Monthly);

2.6 SendNotification (Fire-and-forget)

Voir docs/notifications.md §6.

2.7 DailyDigest / WeeklyDigest

Voir docs/notifications.md §8.


3. Agent — Jobs détaillés

3.1 Configuration Hangfire Agent

// Program.cs — Heimdall.Agent
builder.Services.AddHangfire(config =>
{
    // InMemory : pas de persistance, pas de config supplémentaire
    config.UseInMemoryStorage();
});

builder.Services.AddHangfireServer(options =>
{
    options.WorkerCount = 2;              // 2 workers max (agent léger)
    options.Queues = ["agent"];           // file dédiée
    options.ServerName = $"agent-{hostname}";
});

// Le dashboard Hangfire n'est PAS exposé sur l'Agent
// (pas de app.UseHangfireDashboard())

Pourquoi InMemory et pas SQLite ?

  • SQLite nécessite une lib native (e_sqlite3) ou un package (Hangfire.Sqlite)
  • InMemory = zéro config, zéro fichier, zéro permission disque
  • Les jobs Agent sont volatiles et recréés au démarrage — c'est voulu
  • L'Agent n'a pas besoin de persister ses jobs entre redémarrages

3.2 CameraHealthCheck

public class CameraHealthCheckJob
{
    public async Task ExecuteAsync(CancellationToken ct)
    {
        var cameras = await _localCameraRegistry.GetAllAsync(ct);

        foreach (var camera in cameras)
        {
            var wasOnline = camera.Status == CameraStatus.Online;
            var isOnline = await _rtspService.PingAsync(camera.RtspUrl, ct);

            if (wasOnline && !isOnline)
            {
                camera.Status = CameraStatus.Offline;
                _logger.LogWarning(
                    "Caméra {CameraName} est hors ligne", camera.Name);

                // Notifier le Central
                await _centralApi.UpdateCameraStatusAsync(
                    camera.Id, CameraStatus.Offline, ct);
            }
            else if (!wasOnline && isOnline)
            {
                camera.Status = CameraStatus.Online;
                _logger.LogInformation(
                    "Caméra {CameraName} est de nouveau en ligne", camera.Name);

                await _centralApi.UpdateCameraStatusAsync(
                    camera.Id, CameraStatus.Online, ct);
            }
        }
    }
}

// Schedule (démarré après registration)
RecurringJob.AddOrUpdate<CameraHealthCheckJob>(
    $"agent-{agentId}-camera-health",
    j => j.ExecuteAsync(CancellationToken.None),
    Cron.MinuteInterval(1));

3.3 HeartbeatSender

public class HeartbeatSenderJob
{
    public async Task ExecuteAsync(CancellationToken ct)
    {
        await _centralApi.SendHeartbeatAsync(_agentId, ct);

        _logger.LogTrace("Heartbeat envoyé au Central");
    }
}

// Schedule
RecurringJob.AddOrUpdate<HeartbeatSenderJob>(
    $"agent-{agentId}-heartbeat",
    j => j.ExecuteAsync(CancellationToken.None),
    Cron.MinuteInterval(1));

3.4 GpuWatchdog

public class GpuWatchdogJob
{
    public async Task ExecuteAsync(CancellationToken ct)
    {
        var gpu = _gpuDetector.Detect();
        _currentGpu = gpu;

        if (gpu == GpuAcceleration.None)
        {
            _logger.LogWarning(
                "Aucun GPU détecté — encodage CPU seulement");
        }

        // Reporter au Central
        await _centralApi.UpdateAgentCapabilitiesAsync(_agentId, new()
        {
            HasGpu = gpu != GpuAcceleration.None,
            GpuType = gpu.ToString(),
            CpuCores = Environment.ProcessorCount,
            FreeMemoryMb = GetFreeMemoryMb()
        }, ct);
    }
}

// Schedule
RecurringJob.AddOrUpdate<GpuWatchdogJob>(
    $"agent-{agentId}-gpu-watchdog",
    j => j.ExecuteAsync(CancellationToken.None),
    Cron.MinuteInterval(5));

3.5 LocalRetentionCleanup

Uniquement si le site utilise le stockage LOCAL (fallback bas-débit) :

public class LocalRetentionCleanupJob
{
    public async Task ExecuteAsync(CancellationToken ct)
    {
        var localPaths = await _localCameraRegistry.GetLocalRecordingPathsAsync(ct);

        foreach (var (cameraId, retentionDays, path) in localPaths)
        {
            var cutoff = DateTime.UtcNow.AddDays(-retentionDays);

            foreach (var file in Directory.GetFiles(path, "*.ts"))
            {
                var fileInfo = new FileInfo(file);
                if (fileInfo.CreationTimeUtc < cutoff)
                {
                    fileInfo.Delete();
                    _logger.LogInformation(
                        "LocalRetention: supprimé {File}", file);
                }
            }
        }
    }
}

// Schedule
RecurringJob.AddOrUpdate<LocalRetentionCleanupJob>(
    $"agent-{agentId}-local-retention",
    j => j.ExecuteAsync(CancellationToken.None),
    Cron.Hourly);

4. Initialisation des jobs au démarrage

Central

public static void InitializeHangfireJobs()
{
    // Jobs planifiés (Recurring)
    RecurringJob.AddOrUpdate<RetentionCheckJob>(
        "retention-check",
        j => j.ExecuteAsync(CancellationToken.None),
        Cron.Daily(3));  // 3h du matin

    RecurringJob.AddOrUpdate<S3CleanupJob>(
        "s3-cleanup",
        j => j.ExecuteAsync(CancellationToken.None),
        Cron.Daily(4));  // 4h du matin

    RecurringJob.AddOrUpdate<CleanupUnknownFacesJob>(
        "cleanup-unknown-faces",
        j => j.ExecuteAsync(CancellationToken.None),
        Cron.Weekly(DayOfWeek.Sunday, 5));  // Dimanche 5h

    RecurringJob.AddOrUpdate<CleanupLicensePlatesJob>(
        "cleanup-license-plates",
        j => j.ExecuteAsync(CancellationToken.None),
        Cron.Weekly(DayOfWeek.Sunday, 6));  // Dimanche 6h

    RecurringJob.AddOrUpdate<DatabaseMaintenanceJob>(
        "database-maintenance",
        j => j.ExecuteAsync(CancellationToken.None),
        Cron.Monthly(1, 7));  // 1er du mois à 7h

    RecurringJob.AddOrUpdate<DailyDigestJob>(
        "daily-digest",
        j => j.ExecuteAsync(CancellationToken.None),
        Cron.Daily(8));  // 8h
}

Agent

public class HangfireInitializer : IHostedService
{
    public Task StartAsync(CancellationToken ct)
    {
        var agentId = _stateManager.GetAgentId();

        RecurringJob.AddOrUpdate<CameraHealthCheckJob>(
            $"agent-{agentId}-camera-health",
            j => j.ExecuteAsync(CancellationToken.None),
            Cron.MinuteInterval(1));

        RecurringJob.AddOrUpdate<HeartbeatSenderJob>(
            $"agent-{agentId}-heartbeat",
            j => j.ExecuteAsync(CancellationToken.None),
            Cron.MinuteInterval(1));

        RecurringJob.AddOrUpdate<GpuWatchdogJob>(
            $"agent-{agentId}-gpu-watchdog",
            j => j.ExecuteAsync(CancellationToken.None),
            Cron.MinuteInterval(5));

        return Task.CompletedTask;
    }
}

5. Dashboard Hangfire (Central uniquement)

Intégré à l'UI Admin, authentifié, pas exposé publiquement :

La route Central est mappée par MapHangfireDashboard("/hangfire", ...) dans src/Heimdall.Web/Program.cs. HangfireAdminAuthorizationFilter autorise les requêtes authentifiées portant Admin.Jobs ou le rôle Admin. Le dashboard n'est pas mappé dans l'environnement Testing.

// Heimdall.Web/Program.cs
app.MapHangfireDashboard("/hangfire", new DashboardOptions
{
    Authorization =
    [
        new HangfireAdminAuthorizationFilter()
    ],
});

6. Librairies NuGet

Central (Heimdall.Api + Heimdall.Workers)

dotnet add package Hangfire                     # Core
dotnet add package Hangfire.PostgreSql           # Storage PostgreSQL
dotnet add package Hangfire.AspNetCore           # ASP.NET Core integration

Agent (Heimdall.Agent)

dotnet add package Hangfire                     # Core
dotnet add package Hangfire.InMemory             # Storage InMemory (aucune config)
dotnet add package Hangfire.AspNetCore           # ASP.NET Core integration (pour HostedService)

7. Tests

RetentionCheckJob deletes expired recordings
S3CleanupJob removes orphaned files
CleanupUnknownFacesJob removes old unknown persons
SendNotificationJob retries on failure (3 attempts)
Agent CameraHealthCheckJob detects offline camera
Agent HeartbeatSenderJob sends heartbeat to Central
Agent GpuWatchdogJob detects GPU changes
Agent LocalRetentionCleanupJob deletes old local files
DailyDigestJob sends digest to subscribed users
DatabaseMaintenanceJob runs without error
Hangfire dashboard is accessible only to Admin
Hangfire dashboard returns 403 for non-Admin
Agent jobs are recreated after agent restart
Agent InMemory storage does not persist across restarts