using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
namespace ZB.MOM.WW.ScadaBridge.AuditLog.Site;
///
/// Site-side hosted service that runs the SQLite retention purge on a timer
/// (PLAN-04 Task 3, S1/U2). Each tick calls
/// with a cutoff of
/// UtcNow - ,
/// deleting Forwarded/Reconciled rows past the retention window and reclaiming the
/// freed pages. Without it the ephemeral site store grows unbounded until the next
/// deployment recreates it.
///
///
///
/// Cadence. First tick after
/// (default 5 min — short so a node that recycles daily still purges shortly after
/// start), then every
/// (default 24 h). Mirrors the loop shape of .
///
///
/// Failure containment. Each purge is wrapped in a try/catch so a transient
/// SQLite error never tears down the hosted service — the next tick retries.
///
///
public sealed class SiteAuditRetentionService : IHostedService, IDisposable
{
private readonly ISiteAuditQueue _queue;
private readonly SiteAuditRetentionOptions _options;
private readonly ILogger _logger;
private CancellationTokenSource? _cts;
private Task? _loop;
/// Initializes a new instance of .
/// The site audit queue whose retention purge is driven.
/// Retention cadence + window options.
/// Logger instance.
public SiteAuditRetentionService(
ISiteAuditQueue queue,
IOptions options,
ILogger logger)
{
_queue = queue ?? throw new ArgumentNullException(nameof(queue));
_options = (options ?? throw new ArgumentNullException(nameof(options))).Value;
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
/// Starts the background purge loop.
/// Cancellation token signalling host shutdown.
/// A task that represents the asynchronous operation.
public Task StartAsync(CancellationToken ct)
{
// Linked CTS so both StopAsync and the host shutdown token abort the loop.
_cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
_loop = Task.Run(() => RunLoopAsync(_cts.Token));
return Task.CompletedTask;
}
private async Task RunLoopAsync(CancellationToken ct)
{
// InitialDelay before the first purge — short so a daily-recycled node
// still purges soon after start rather than waiting a full interval it may
// never reach.
try
{
await Task.Delay(_options.InitialDelay, ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return;
}
await SafePurgeAsync(ct).ConfigureAwait(false);
while (!ct.IsCancellationRequested)
{
try
{
await Task.Delay(_options.ResolvedPurgeInterval, ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
break;
}
await SafePurgeAsync(ct).ConfigureAwait(false);
}
}
private async Task SafePurgeAsync(CancellationToken ct)
{
try
{
var cutoff = DateTime.UtcNow.AddDays(-_options.ResolvedRetentionDays);
var purged = await _queue.PurgeExpiredAsync(cutoff, ct).ConfigureAwait(false);
if (purged > 0)
{
_logger.LogInformation(
"Site audit retention purge removed {Count} row(s) older than {Cutoff:o}.",
purged, cutoff);
}
}
catch (OperationCanceledException)
{
// Shutdown — let the outer loop exit cleanly.
throw;
}
catch (Exception ex)
{
// Catch-all is deliberate: a transient SQLite fault must not tear down
// the hosted service; the next tick retries.
_logger.LogWarning(ex, "SiteAuditRetentionService purge failed; next tick will retry.");
}
}
/// Signals the purge loop to stop and waits for it to complete.
/// Cancellation token (not used; the internal CTS governs shutdown).
/// A task that represents the asynchronous operation.
public Task StopAsync(CancellationToken ct)
{
_cts?.Cancel();
return _loop ?? Task.CompletedTask;
}
/// Releases the internal .
public void Dispose()
{
_cts?.Dispose();
}
}