fix(audit): persist config audit rows written after the final save (DEP-1, MGT-1, TPL-3, WP1 task 1.4)
IAuditService.LogAsync only stages the row; every caller that audited after its last SaveChangesAsync, outside the configuration-command transaction, lost the row with the DI scope (rig: zero Disable/Enable/ Delete/DeployArtifacts rows, 16 Deploy rows for 62 deployments, one Create/Instance row for ids up to 3876). - New IAuditService.LogAndSaveAsync: stage + save, best-effort (logs and swallows any failure incl. cancellation, detaches the unsaved row). - DeploymentService (deploy/failed/reconciled/lifecycle + timeouts), ArtifactDeploymentService (DeployArtifacts now before the best-effort stamp, RetryArtifactDeployment, DeploySiteSecrets), InstanceService, AreaService, SiteService: post-save LogAsync -> LogAndSaveAsync. - ManagementActor: AuditAndSaveAsync for the non-configuration handlers (API keys, shared schemas, ES methods, data-connection move); move now audits the scrubbed public shape (MGT-4) so the fix does not start writing protocol credentials into AuditLogEntries. - HandleCreateInstance no longer stages a second Create row on top of InstanceService's own. Tests: real-context (SQLite) tests per family read the row back through a second context - DeploymentService, ArtifactDeploymentService, InstanceService, ManagementActor; each fails against the old code. Test projects gain a ConfigurationDatabase + EF Sqlite reference.
This commit is contained in:
@@ -1,4 +1,7 @@
|
||||
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;
|
||||
@@ -9,6 +12,7 @@ public class AuditService : IAuditService
|
||||
{
|
||||
private readonly ScadaBridgeDbContext _context;
|
||||
private readonly IAuditCorrelationContext _correlationContext;
|
||||
private readonly ILogger<AuditService> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Serializer options for audit <c>afterState</c> payloads. Audit writes commit in the
|
||||
@@ -37,10 +41,15 @@ public class AuditService : IAuditService
|
||||
/// </summary>
|
||||
/// <param name="context">The EF Core database context used to stage audit entries.</param>
|
||||
/// <param name="correlationContext">Provides the active bundle import id for audit row stamping.</param>
|
||||
public AuditService(ScadaBridgeDbContext context, IAuditCorrelationContext correlationContext)
|
||||
/// <param name="logger">Logs a failed best-effort <see cref="LogAndSaveAsync"/>; optional.</param>
|
||||
public AuditService(
|
||||
ScadaBridgeDbContext context,
|
||||
IAuditCorrelationContext correlationContext,
|
||||
ILogger<AuditService>? logger = null)
|
||||
{
|
||||
_context = context ?? throw new ArgumentNullException(nameof(context));
|
||||
_correlationContext = correlationContext ?? throw new ArgumentNullException(nameof(correlationContext));
|
||||
_logger = logger ?? NullLogger<AuditService>.Instance;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
@@ -53,7 +62,51 @@ public class AuditService : IAuditService
|
||||
object? afterState,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var entry = new AuditLogEntry(user, action, entityType, entityId, entityName)
|
||||
// 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);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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
|
||||
@@ -64,10 +117,6 @@ public class AuditService : IAuditService
|
||||
// interactive code path.
|
||||
BundleImportId = _correlationContext.BundleImportId
|
||||
};
|
||||
|
||||
// Add to change tracker only — caller is responsible for calling SaveChangesAsync
|
||||
// to ensure atomicity with the entity change.
|
||||
await _context.AuditLogEntries.AddAsync(entry, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
Reference in New Issue
Block a user