Heimdall Gitea / Detect CI scope (push) Successful in 6s
Heimdall Gitea / Build and tests (push) Successful in 19m19s
Heimdall Gitea / Publish versioned release (push) Skipped
Heimdall Gitea / Build and scan server image (push) Successful in 6m13s
Heimdall Gitea / Build and scan agent image (push) Successful in 14m44s
Heimdall Gitea / Publish Docker Hub latest tags (push) Successful in 1m48s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 19m9s
Heimdall Gitea / CI policy (push) Successful in 10s
Merge pull request #138 Co-authored-by: Arnaud Dartois <admin@tordais.cc>
118 lines
5.0 KiB
C#
118 lines
5.0 KiB
C#
using Heimdall.Infrastructure.Data;
|
|
using Heimdall.Application.Common;
|
|
using Heimdall.Domain.Entities;
|
|
using Heimdall.Domain.Enums;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace Heimdall.Infrastructure.Jobs;
|
|
|
|
/// <summary>
|
|
/// Purges unassigned OCR observations and old plate-detection events after 30 days.
|
|
/// Event snapshots are removed from their recorded destination before deleting rows.
|
|
/// </summary>
|
|
public class CleanupLicensePlatesJob
|
|
{
|
|
private readonly IDbContextFactory<AppDbContext> _dbFactory;
|
|
private readonly ILogger<CleanupLicensePlatesJob> _logger;
|
|
private readonly IStorageObjectDeletion? _storage;
|
|
|
|
private const int BatchSize = 250;
|
|
|
|
public CleanupLicensePlatesJob(IDbContextFactory<AppDbContext> dbFactory,
|
|
ILogger<CleanupLicensePlatesJob> logger, IStorageObjectDeletion? storage = null)
|
|
{
|
|
_dbFactory = dbFactory;
|
|
_logger = logger;
|
|
_storage = storage;
|
|
}
|
|
|
|
public async Task ExecuteAsync(CancellationToken ct)
|
|
{
|
|
await using var db = await _dbFactory.CreateDbContextAsync(ct);
|
|
|
|
var cutoff = DateTime.UtcNow.AddDays(-30);
|
|
|
|
var deleted = await db.LicensePlates
|
|
.Where(p => p.VehicleId == null && p.PersonId == null && p.CreatedAt < cutoff)
|
|
.ExecuteDeleteAsync(ct)
|
|
.ConfigureAwait(false);
|
|
|
|
if (deleted > 0)
|
|
_logger.LogInformation("License plates cleanup: purged {Count} unassigned plate(s) older than 30 days", deleted);
|
|
|
|
var deletedEvents = 0;
|
|
DateTime? cursorOccurredAt = null;
|
|
var cursorId = Guid.Empty;
|
|
while (true)
|
|
{
|
|
var events = await db.CameraEvents.IgnoreQueryFilters().AsNoTracking()
|
|
.Where(e => e.Type == EventType.LicensePlateDetected && e.OccurredAt < cutoff &&
|
|
(cursorOccurredAt == null || e.OccurredAt > cursorOccurredAt.Value ||
|
|
(e.OccurredAt == cursorOccurredAt.Value && e.Id.CompareTo(cursorId) > 0)))
|
|
.OrderBy(e => e.OccurredAt).ThenBy(e => e.Id)
|
|
.Take(BatchSize)
|
|
.Select(e => new
|
|
{
|
|
e.Id, e.OccurredAt, e.SnapshotObjectKey, e.SnapshotThumbObjectKey,
|
|
e.SnapshotStorageProvider, e.SnapshotStorageRoot,
|
|
e.SnapshotStorageEndpoint, e.SnapshotStorageBucket
|
|
})
|
|
.ToListAsync(ct).ConfigureAwait(false);
|
|
if (events.Count == 0) break;
|
|
cursorOccurredAt = events[^1].OccurredAt;
|
|
cursorId = events[^1].Id;
|
|
|
|
var deletableIds = new List<Guid>(events.Count);
|
|
var objectsByLocation = new Dictionary<StorageLocation, List<string>>();
|
|
foreach (var item in events)
|
|
{
|
|
if (item.SnapshotObjectKey is null && item.SnapshotThumbObjectKey is null)
|
|
{
|
|
deletableIds.Add(item.Id);
|
|
continue;
|
|
}
|
|
|
|
if (item.SnapshotStorageProvider is null)
|
|
{
|
|
_logger.LogWarning("Retaining expired plate event {EventId}: snapshot destination is not recorded", item.Id);
|
|
continue;
|
|
}
|
|
|
|
var location = new StorageLocation(item.SnapshotStorageProvider.Value,
|
|
item.SnapshotStorageRoot, item.SnapshotStorageEndpoint, item.SnapshotStorageBucket);
|
|
if (!location.IsComplete)
|
|
{
|
|
_logger.LogWarning("Retaining expired plate event {EventId}: snapshot destination is incomplete", item.Id);
|
|
continue;
|
|
}
|
|
|
|
if (_storage is null)
|
|
{
|
|
_logger.LogWarning("Retaining expired plate event {EventId}: snapshot deletion service is unavailable", item.Id);
|
|
continue;
|
|
}
|
|
|
|
if (!objectsByLocation.TryGetValue(location, out var keys))
|
|
objectsByLocation[location] = keys = [];
|
|
if (item.SnapshotObjectKey is { } snapshot) keys.Add(snapshot);
|
|
if (item.SnapshotThumbObjectKey is { } thumbnail) keys.Add(thumbnail);
|
|
deletableIds.Add(item.Id);
|
|
}
|
|
|
|
// Deleting a row before its exact stored objects succeed can orphan sensitive imagery.
|
|
foreach (var (location, keys) in objectsByLocation)
|
|
await _storage!.DeleteBatchAsync(keys, location, ct).ConfigureAwait(false);
|
|
|
|
if (deletableIds.Count == 0) continue;
|
|
deletedEvents += await db.CameraEvents.IgnoreQueryFilters()
|
|
.Where(e => deletableIds.Contains(e.Id) && e.Type == EventType.LicensePlateDetected &&
|
|
e.OccurredAt < cutoff)
|
|
.ExecuteDeleteAsync(ct).ConfigureAwait(false);
|
|
}
|
|
|
|
if (deletedEvents > 0)
|
|
_logger.LogInformation("License plate event cleanup: purged {Count} event(s) older than 30 days", deletedEvents);
|
|
}
|
|
}
|