151 lines
6.0 KiB
C#
151 lines
6.0 KiB
C#
using System.Globalization;
|
|
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;
|
|
|
|
/// <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)
|
|
{
|
|
_dbFactory = dbFactory;
|
|
_logger = logger;
|
|
}
|
|
|
|
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
|
|
{
|
|
// 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);
|
|
}
|
|
}
|