using System.Text.Json; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using ZB.MOM.WW.ScadaBridge.Commons.Entities.Audit; using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services; using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Transport; namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Services; public class AuditService : IAuditService { private readonly ScadaBridgeDbContext _context; private readonly IAuditCorrelationContext _correlationContext; private readonly ILogger _logger; /// /// Serializer options for audit afterState payloads. Audit writes commit in the /// same transaction as the change they record, so a serialization exception here would /// roll back the entire business operation. Reference cycles (common when an EF entity /// with loaded navigations is passed in) are ignored rather than thrown, and depth is /// bounded so a pathological graph cannot produce an unbounded payload. /// private static readonly JsonSerializerOptions AuditSerializerOptions = new() { ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles, MaxDepth = 32 }; /// /// Upper bound (characters) on a serialized AfterStateJson. A larger payload (e.g. a /// whole template graph with every script body) is replaced by a small truncation marker so /// one audit row can never grow without bound. Valid JSON is preserved either way. /// public const int MaxAfterStateChars = 256 * 1024; private const int TruncatedPreviewChars = 4 * 1024; /// /// Initializes the audit service with the EF Core context and correlation context. /// /// The EF Core database context used to stage audit entries. /// Provides the active bundle import id for audit row stamping. /// Logs a failed best-effort ; optional. public AuditService( ScadaBridgeDbContext context, IAuditCorrelationContext correlationContext, ILogger? logger = null) { _context = context ?? throw new ArgumentNullException(nameof(context)); _correlationContext = correlationContext ?? throw new ArgumentNullException(nameof(correlationContext)); _logger = logger ?? NullLogger.Instance; } /// public async Task LogAsync( string user, string action, string entityType, string entityId, string entityName, object? afterState, CancellationToken cancellationToken = default) { // Add to change tracker only — caller is responsible for calling SaveChangesAsync // to ensure atomicity with the entity change. await _context.AuditLogEntries.AddAsync( BuildEntry(user, action, entityType, entityId, entityName, afterState), cancellationToken); } /// public async Task LogAndSaveAsync( string user, string action, string entityType, string entityId, string entityName, object? afterState, CancellationToken cancellationToken = default) { AuditLogEntry? entry = null; try { entry = BuildEntry(user, action, entityType, entityId, entityName, afterState); await _context.AuditLogEntries.AddAsync(entry, cancellationToken); await _context.SaveChangesAsync(cancellationToken); } catch (Exception ex) { // Best-effort: the action this row records has already committed, so an audit // failure must never surface to the caller. Detach the unsaved row so it cannot // fail (or be silently written by) a later save on this unit of work. if (entry is not null) { try { _context.Entry(entry).State = EntityState.Detached; } catch { /* the row was never tracked */ } } _logger.LogWarning(ex, "Failed to persist {Action} audit entry for {EntityType} {EntityName} ({EntityId}) by {User}; " + "the action itself succeeded and audit is best-effort", action, entityType, entityName, entityId, user); } } private AuditLogEntry BuildEntry( string user, string action, string entityType, string entityId, string entityName, object? afterState) { return new AuditLogEntry(user, action, entityType, entityId, entityName) { Timestamp = DateTimeOffset.UtcNow, AfterStateJson = afterState != null ? SerializeAfterState(afterState) : null, // Stamp the active bundle import id (if any) so audit rows emitted during a // bundle import are attributable to that import session. Null in the normal // interactive code path. BundleImportId = _correlationContext.BundleImportId }; } /// /// Serializes the caller-supplied after-state, tolerating arbitrary object shapes. /// Reference cycles are ignored via . If serialization /// still fails (e.g. MaxDepth exceeded), the audit entry is preserved with a /// diagnostic placeholder rather than throwing — a serialization failure must never /// roll back the business operation the audit entry is recording. /// private static string SerializeAfterState(object afterState) { try { var json = JsonSerializer.Serialize(afterState, AuditSerializerOptions); if (json.Length <= MaxAfterStateChars) return json; return JsonSerializer.Serialize(new { AuditTruncated = true, OriginalLength = json.Length, StateType = afterState.GetType().FullName, Preview = json[..TruncatedPreviewChars] }); } catch (Exception ex) when (ex is JsonException or NotSupportedException) { return JsonSerializer.Serialize(new { AuditSerializationError = ex.Message, StateType = afterState.GetType().FullName }); } } }