208 lines
8.9 KiB
C#
208 lines
8.9 KiB
C#
using System.Globalization;
|
|
using Heimdall.Application.Common;
|
|
using Heimdall.Domain.Entities;
|
|
using Heimdall.Infrastructure.Data;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace Heimdall.Infrastructure.Jobs;
|
|
|
|
/// <summary>
|
|
/// PartitionManagerJob — automatic monthly partition management for camera_events.
|
|
/// Creates partitions for the next 2 months and drops partitions older than
|
|
/// the retention period (default 12 months). Runs daily at 02:00.
|
|
/// </summary>
|
|
public class PartitionManagerJob
|
|
{
|
|
private readonly IDbContextFactory<AppDbContext> _dbFactory;
|
|
private readonly ILogger<PartitionManagerJob> _logger;
|
|
private readonly IStorageObjectDeletion? _storage;
|
|
|
|
/// <summary>Number of months to retain old partitions.</summary>
|
|
private const int RetentionMonths = 12;
|
|
|
|
/// <summary>Number of future months to pre-create.</summary>
|
|
private const int PreCreateMonths = 2;
|
|
|
|
private static readonly CultureInfo InvariantCulture = CultureInfo.InvariantCulture;
|
|
|
|
public PartitionManagerJob(
|
|
IDbContextFactory<AppDbContext> dbFactory,
|
|
ILogger<PartitionManagerJob> logger,
|
|
IStorageObjectDeletion? storage = null)
|
|
{
|
|
_dbFactory = dbFactory;
|
|
_logger = logger;
|
|
_storage = storage;
|
|
}
|
|
|
|
public static bool TryParsePartitionDate(string name, out DateTime date)
|
|
{
|
|
date = default;
|
|
const string prefix = "camera_events_";
|
|
if (name.Length != 21 || !name.StartsWith(prefix, StringComparison.Ordinal) ||
|
|
name[18] != '_' || !IsDigits(name.AsSpan(14, 4)) ||
|
|
!IsDigits(name.AsSpan(19, 2)))
|
|
return false;
|
|
return DateTime.TryParseExact(name.AsSpan(14), "yyyy_MM", InvariantCulture,
|
|
DateTimeStyles.None, out date);
|
|
}
|
|
|
|
private static bool IsDigits(ReadOnlySpan<char> value)
|
|
{
|
|
foreach (var ch in value)
|
|
if (ch is < '0' or > '9') return false;
|
|
return true;
|
|
}
|
|
|
|
public async Task ExecuteAsync(CancellationToken ct)
|
|
{
|
|
await using var db = await _dbFactory.CreateDbContextAsync(ct);
|
|
var now = DateTime.UtcNow;
|
|
var created = 0;
|
|
var dropped = 0;
|
|
|
|
// ── Create future partitions ────────────────────────────────────────
|
|
for (int i = 0; i <= PreCreateMonths; i++)
|
|
{
|
|
var from = new DateTime(now.Year, now.Month, 1, 0, 0, 0, DateTimeKind.Utc).AddMonths(i);
|
|
var to = from.AddMonths(1);
|
|
var partitionName = $"camera_events_{from.ToString("yyyy_MM", InvariantCulture)}";
|
|
|
|
var sql = $@"
|
|
CREATE TABLE IF NOT EXISTS public.""{partitionName}""
|
|
PARTITION OF public.""camera_events""
|
|
FOR VALUES FROM ('{from.ToString("yyyy-MM-dd", InvariantCulture)}') TO ('{to.ToString("yyyy-MM-dd", InvariantCulture)}');
|
|
";
|
|
|
|
try
|
|
{
|
|
await db.Database.ExecuteSqlRawAsync(sql, ct).ConfigureAwait(false);
|
|
created++;
|
|
_logger.LogDebug("Partition {Partition} ensured (FROM {From} TO {To})",
|
|
partitionName,
|
|
from.ToString("yyyy-MM-dd", InvariantCulture),
|
|
to.ToString("yyyy-MM-dd", InvariantCulture));
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogWarning(ex, "Failed to create partition {Partition}", partitionName);
|
|
}
|
|
}
|
|
|
|
// ── Drop old partitions beyond retention ────────────────────────────
|
|
var cutoff = new DateTime(now.Year, now.Month, 1, 0, 0, 0, DateTimeKind.Utc).AddMonths(-RetentionMonths);
|
|
|
|
// Only consider actual partitions of the intended public parent table.
|
|
const string listSql = @"
|
|
SELECT child.relname
|
|
FROM pg_inherits inheritance
|
|
JOIN pg_class parent ON parent.oid = inheritance.inhparent
|
|
JOIN pg_namespace parent_schema ON parent_schema.oid = parent.relnamespace
|
|
JOIN pg_class child ON child.oid = inheritance.inhrelid
|
|
JOIN pg_namespace child_schema ON child_schema.oid = child.relnamespace
|
|
WHERE parent_schema.nspname = 'public' AND parent.relname = 'camera_events'
|
|
AND child_schema.nspname = 'public'
|
|
ORDER BY child.relname;
|
|
";
|
|
|
|
try
|
|
{
|
|
var connection = db.Database.GetDbConnection();
|
|
await connection.OpenAsync(ct).ConfigureAwait(false);
|
|
|
|
await using var cmd = connection.CreateCommand();
|
|
cmd.CommandText = listSql;
|
|
|
|
var partitionsToDrop = new List<string>();
|
|
await using (var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false))
|
|
{
|
|
while (await reader.ReadAsync(ct).ConfigureAwait(false))
|
|
{
|
|
var tableName = reader.GetString(0);
|
|
if (TryParsePartitionDate(tableName, out var partitionDate) && partitionDate < cutoff)
|
|
partitionsToDrop.Add(tableName);
|
|
}
|
|
}
|
|
|
|
foreach (var partition in partitionsToDrop)
|
|
{
|
|
try
|
|
{
|
|
// Delete managed snapshots first. A failed object deletion keeps
|
|
// the partition so the next sweep can retry with its metadata.
|
|
var partitionDate = DateTime.SpecifyKind(
|
|
DateTime.ParseExact(partition[14..], "yyyy_MM", InvariantCulture), DateTimeKind.Utc);
|
|
await DeletePartitionSnapshotsAsync(db, partitionDate, ct).ConfigureAwait(false);
|
|
|
|
// Partition name is validated above (alphanumeric + underscore only)
|
|
#pragma warning disable EF1002 // DDL — table name cannot be parameterized
|
|
await db.Database.ExecuteSqlRawAsync(
|
|
$"DROP TABLE IF EXISTS public.\"{partition}\";", ct).ConfigureAwait(false);
|
|
#pragma warning restore EF1002
|
|
dropped++;
|
|
_logger.LogInformation("Dropped old partition {Partition}", partition);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogWarning(ex, "Failed to drop partition {Partition}", partition);
|
|
}
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogWarning(ex, "Failed to list/drop old partitions");
|
|
}
|
|
|
|
_logger.LogInformation(
|
|
"Partition management complete: {Created} ensured, {Dropped} dropped (retention {Retention} months)",
|
|
created, dropped, RetentionMonths);
|
|
}
|
|
|
|
private async Task DeletePartitionSnapshotsAsync(AppDbContext db, DateTime from, CancellationToken ct)
|
|
{
|
|
const int batchSize = 500;
|
|
var to = from.AddMonths(1);
|
|
var offset = 0;
|
|
while (true)
|
|
{
|
|
var events = await db.CameraEvents.IgnoreQueryFilters().AsNoTracking()
|
|
.Where(e => e.OccurredAt >= from && e.OccurredAt < to &&
|
|
(e.SnapshotObjectKey != null || e.SnapshotThumbObjectKey != null))
|
|
.OrderBy(e => e.Id).Skip(offset).Take(batchSize)
|
|
.Select(e => new
|
|
{
|
|
e.Id,
|
|
e.SnapshotObjectKey,
|
|
e.SnapshotThumbObjectKey,
|
|
e.SnapshotStorageProvider,
|
|
e.SnapshotStorageRoot,
|
|
e.SnapshotStorageEndpoint,
|
|
e.SnapshotStorageBucket
|
|
}).ToListAsync(ct).ConfigureAwait(false);
|
|
if (events.Count == 0) break;
|
|
if (_storage is null) throw new InvalidOperationException("Snapshot storage deletion is unavailable");
|
|
|
|
var objectsByLocation = new Dictionary<StorageLocation, List<string>>();
|
|
foreach (var ev in events)
|
|
{
|
|
if (ev.SnapshotStorageProvider is null)
|
|
throw new InvalidOperationException($"Snapshot destination is incomplete for event {ev.Id}");
|
|
var location = new StorageLocation(ev.SnapshotStorageProvider.Value,
|
|
ev.SnapshotStorageRoot, ev.SnapshotStorageEndpoint, ev.SnapshotStorageBucket);
|
|
if (!location.IsComplete)
|
|
throw new InvalidOperationException($"Snapshot destination is incomplete for event {ev.Id}");
|
|
if (!objectsByLocation.TryGetValue(location, out var keys))
|
|
objectsByLocation[location] = keys = [];
|
|
if (ev.SnapshotObjectKey is { } snapshot) keys.Add(snapshot);
|
|
if (ev.SnapshotThumbObjectKey is { } thumb) keys.Add(thumb);
|
|
}
|
|
foreach (var (location, keys) in objectsByLocation)
|
|
await _storage.DeleteBatchAsync(keys, location, ct).ConfigureAwait(false);
|
|
|
|
offset += events.Count;
|
|
if (events.Count < batchSize) break;
|
|
}
|
|
}
|
|
}
|