using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories; namespace ZB.MOM.WW.ScadaBridge.AuditLog.Central; /// /// Central hosted service that links newly written AuditLog rows into their month's /// SHA-256 hash chain (audit roadmap T1, alog.md §11.4, ScadaBridge#41). The chaining /// job of alog.md §11.4, run incrementally — every /// rather than only once a month has closed, so a row is tamper-evident within about a /// minute of reaching central instead of up to a month later. /// /// /// /// Same shape as : a background loop, a /// fresh DI scope per tick, every failure logged and contained. Runs on BOTH central nodes; /// takes an exclusive SQL application /// lock with a zero timeout, so the peer's pass skips instead of racing (and correctness /// does not depend on Akka's view of which node is active). /// /// public sealed class AuditLogHashChainService : IHostedService, IDisposable { private readonly IServiceScopeFactory _scopeFactory; private readonly IOptions _options; private readonly ILogger _logger; private CancellationTokenSource? _cts; private Task? _loop; /// Initializes the service. /// Scope factory used to resolve the scoped chain implementation per tick. /// Hash-chain options. /// Logger. public AuditLogHashChainService( IServiceScopeFactory scopeFactory, IOptions options, ILogger logger) { _scopeFactory = scopeFactory ?? throw new ArgumentNullException(nameof(scopeFactory)); _options = options ?? throw new ArgumentNullException(nameof(options)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } /// public Task StartAsync(CancellationToken cancellationToken) { if (!_options.Value.Enabled) { _logger.LogInformation("AuditLog hash chain disabled (AuditLog:HashChain:Enabled=false); no chaining job started."); return Task.CompletedTask; } var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); _cts = cts; var token = cts.Token; _loop = Task.Run(() => RunLoopAsync(token), CancellationToken.None); return Task.CompletedTask; } private async Task RunLoopAsync(CancellationToken ct) { while (!ct.IsCancellationRequested) { await TickAsync(ct).ConfigureAwait(false); try { await Task.Delay(TimeSpan.FromSeconds(_options.Value.IntervalSeconds), ct).ConfigureAwait(false); } catch (OperationCanceledException) { break; } } } /// /// Runs one tick: chains batches until the backlog is empty, the peer holds the lock, /// or is reached. /// /// Cancellation token. /// The number of rows chained in this tick. internal async Task TickAsync(CancellationToken ct) { long total = 0; try { var options = _options.Value; await using var scope = _scopeFactory.CreateAsyncScope(); var chain = scope.ServiceProvider.GetRequiredService(); for (var i = 0; i < options.MaxBatchesPerTick && !ct.IsCancellationRequested; i++) { var result = await chain.ChainPendingAsync(options.BatchSize, options.ChainBacklog, ct).ConfigureAwait(false); total += result.RowsChained; if (result.LockBusy || result.RowsChained == 0) { break; } } if (total > 0) { _logger.LogDebug("AuditLog hash chain linked {Rows} rows this tick.", total); } } catch (OperationCanceledException) when (ct.IsCancellationRequested) { // Shutdown. } catch (Exception ex) { // Contained: a transient SQL failure must not end the loop; the next tick // resumes from wherever the last committed pass left the chain. _logger.LogError(ex, "AuditLog hash-chain tick failed after linking {Rows} rows.", total); } return total; } /// public Task StopAsync(CancellationToken cancellationToken) { try { _cts?.Cancel(); } catch (ObjectDisposedException) { // Dispose already cancelled the loop. } return _loop ?? Task.CompletedTask; } /// public void Dispose() { try { _cts?.Cancel(); } catch (ObjectDisposedException) { // Idempotent. } _cts?.Dispose(); } }