Path: redb-tsak/src/redb.Tsak.Core/Audit/AuditRetentionRouteBuilder.cs
Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak
Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Core/Audit/AuditRetentionRouteBuilder.cs
----
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Tsak.Core.Audit;
///
/// Daily audit-log retention as a first-class redb.Route cron route (cron://tsak-audit-retention)
/// instead of a bare Quartz job — so it shows up in the Routes API/dashboard as well as the scheduler
/// page, and Tsak eats its own dog food (uses redb.Route + the Cron connector like any business route).
/// Prunes tsak_audit_log rows older than Tsak:Audit:RetentionDays. The cron://
/// consumer runs on the shared scheduler injected into every Tsak context, so it stays visible on the
/// scheduler dashboard. Registered by only when audit
/// persistence is active and retention is enabled.
///
public sealed class AuditRetentionRouteBuilder : RouteBuilder
{
/// Route id — how the sweep shows up in the Routes API and the dashboard.
public const string RouteIdName = "tsak-audit-retention";
/// Default retention window when the config key is absent.
public const int DefaultRetentionDays = 90;
/// Daily at 03:00 (Quartz cron). Kept off the top of the hour of nothing in particular.
public const string CronSchedule = "0 0 3 * * ?";
private readonly AuditQueryService _audit;
private readonly int _retentionDays;
private readonly ILogger? _logger;
public AuditRetentionRouteBuilder(AuditQueryService audit, int retentionDays, ILogger? logger)
{
_audit = audit;
_retentionDays = retentionDays;
_logger = logger;
}
protected override void Configure()
{
From($"cron://{RouteIdName}?schedule={CronSchedule}")
.RouteId(RouteIdName)
// No .Cluster(true): on a clustered job store Quartz fires the sweep on one node of the cluster, and the
// cluster layer does not apply a leader-only policy to a Quartz consumer. On a store that is not shared
// every node runs it; the prune is an idempotent DELETE-by-cutoff, so that is harmless.
.Process(async (IExchange exchange, CancellationToken ct) =>
{
if (!_audit.IsAvailable || _retentionDays <= 0) return;
var cutoff = DateTimeOffset.UtcNow.AddDays(-_retentionDays);
try
{
var removed = await _audit.PruneAsync(cutoff, ct);
if (removed > 0)
_logger?.LogInformation(
"Audit retention: removed {Removed} entries older than {Cutoff:o} ({Days}d)",
removed, cutoff, _retentionDays);
}
catch (Exception ex)
{
_logger?.LogWarning(ex, "Audit retention sweep failed");
}
});
}
}