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:
@@ -14,4 +14,27 @@ public interface IAuditService
|
||||
/// <param name="cancellationToken">Cancellation token for the log write.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
Task LogAsync(string user, string action, string entityType, string entityId, string entityName, object? afterState, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Appends an audit log entry AND persists it immediately, best-effort: any failure
|
||||
/// (including the save) is logged and swallowed, and the unsaved entry is detached so it
|
||||
/// cannot poison a later save. Never throws (code review 2026-12-02 DEP-1/MGT-1/TPL-3).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Use this — not <see cref="LogAsync"/> — wherever the audit call comes AFTER the
|
||||
/// operation's final <c>SaveChangesAsync</c>: <see cref="LogAsync"/> only stages the
|
||||
/// row on the change tracker, so a staged row with no later save is silently discarded
|
||||
/// when the DI scope is disposed. The save flushes the whole unit of work, so call this
|
||||
/// only once the operation's own changes are saved; inside an ambient transaction the
|
||||
/// row commits (or rolls back) with that transaction.
|
||||
/// </remarks>
|
||||
/// <param name="user">The authenticated username performing the action.</param>
|
||||
/// <param name="action">The action performed (e.g., "Create", "Update", "Delete").</param>
|
||||
/// <param name="entityType">The type name of the affected entity.</param>
|
||||
/// <param name="entityId">The string representation of the entity's primary key.</param>
|
||||
/// <param name="entityName">The display name of the affected entity.</param>
|
||||
/// <param name="afterState">The entity state after the action; may be null for deletes.</param>
|
||||
/// <param name="cancellationToken">Cancellation token for the log write.</param>
|
||||
/// <returns>A task that represents the asynchronous operation; it never faults.</returns>
|
||||
Task LogAndSaveAsync(string user, string action, string entityType, string entityId, string entityName, object? afterState, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -245,6 +245,11 @@ public class ArtifactDeploymentService
|
||||
/// error — never <see cref="SecretArtifact.Ciphertext"/>, <c>Nonce</c>, <c>Tag</c>,
|
||||
/// <c>WrappedDek</c>, or any other material (global constraint: never plaintext or material
|
||||
/// in logs or audit rows).
|
||||
///
|
||||
/// The row is saved here (<see cref="IAuditService.LogAndSaveAsync"/>, which never throws):
|
||||
/// on the retry path nothing saves after it, so a staged-only row was discarded with the
|
||||
/// DI scope — a refused retry (missing secret) wrote no row at all (code review
|
||||
/// 2026-12-02 DEP-1).
|
||||
/// </summary>
|
||||
private Task LogSecretsAuditAsync(
|
||||
string user,
|
||||
@@ -269,7 +274,7 @@ public class ArtifactDeploymentService
|
||||
if (!hasSecretRefs)
|
||||
return Task.CompletedTask;
|
||||
|
||||
return _auditService.LogAsync(
|
||||
return _auditService.LogAndSaveAsync(
|
||||
user, "DeploySiteSecrets", "SiteSecrets", siteIdentifier, siteName,
|
||||
new
|
||||
{
|
||||
@@ -596,6 +601,22 @@ public class ArtifactDeploymentService
|
||||
// Only sites whose deploy SUCCEEDED are stamped. A failed site is deliberately
|
||||
// left untouched so it keeps its previous stamp (or none at all) and keeps
|
||||
// reading "out of date" on the Sites page.
|
||||
var summary = new ArtifactDeploymentSummary(
|
||||
deploymentId,
|
||||
results.ToList(),
|
||||
results.Count(r => r.Success),
|
||||
results.Count(r => !r.Success));
|
||||
|
||||
// Code review 2026-12-02 DEP-1: this row used to be staged with LogAsync AFTER the
|
||||
// stamp's save, so nothing ever wrote it (zero DeployArtifacts rows on the rig). It is
|
||||
// now saved on its own (LogAndSaveAsync never throws) and — per the ordering rule
|
||||
// above — BEFORE the best-effort stamp, so a failed stamp that leaves Site entries
|
||||
// tracked as Modified cannot take the audit row's save down with it.
|
||||
await _auditService.LogAndSaveAsync(user, "DeployArtifacts", "SystemArtifact",
|
||||
deploymentId, "Artifacts",
|
||||
new { summary.SuccessCount, summary.FailureCount },
|
||||
cancellationToken);
|
||||
|
||||
var successfulSites = sites
|
||||
.Where(site => perSiteResults.TryGetValue(site.SiteIdentifier, out var r) && r.Success)
|
||||
.ToList();
|
||||
@@ -606,17 +627,6 @@ public class ArtifactDeploymentService
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
var summary = new ArtifactDeploymentSummary(
|
||||
deploymentId,
|
||||
results.ToList(),
|
||||
results.Count(r => r.Success),
|
||||
results.Count(r => !r.Success));
|
||||
|
||||
await _auditService.LogAsync(user, "DeployArtifacts", "SystemArtifact",
|
||||
deploymentId, "Artifacts",
|
||||
new { summary.SuccessCount, summary.FailureCount },
|
||||
cancellationToken);
|
||||
|
||||
return Result<ArtifactDeploymentSummary>.Success(summary);
|
||||
}
|
||||
|
||||
@@ -682,7 +692,9 @@ public class ArtifactDeploymentService
|
||||
// returned Result — an old site's/partial site's reply must not read as success.
|
||||
var result = ReconcileSecretsOutcome(command, response, siteIdentifier, siteIdentifier);
|
||||
|
||||
await _auditService.LogAsync(user, "RetryArtifactDeployment", "SystemArtifact",
|
||||
// Saved here (DEP-1): nothing on the retry path saves after it unless the
|
||||
// retry succeeds and the stamp runs.
|
||||
await _auditService.LogAndSaveAsync(user, "RetryArtifactDeployment", "SystemArtifact",
|
||||
command.DeploymentId, siteIdentifier, new { result.Success }, cancellationToken);
|
||||
|
||||
// Ordering rule: audit before the best-effort stamp.
|
||||
|
||||
@@ -2328,7 +2328,9 @@ public class DeploymentService
|
||||
// who issued the original timed-out / stuck deployment. The original
|
||||
// deployer is preserved in the detail object so forensics can still
|
||||
// see who launched the run that reconciliation rescued.
|
||||
await _auditService.LogAsync(currentUser, "DeployReconciled", "Instance",
|
||||
// LogAndSaveAsync: the row comes after the last save above (code review
|
||||
// 2026-12-02 DEP-1) — a staged LogAsync row here was never written.
|
||||
await _auditService.LogAndSaveAsync(currentUser, "DeployReconciled", "Instance",
|
||||
instance.Id.ToString(), instance.UniqueName,
|
||||
new
|
||||
{
|
||||
@@ -2522,6 +2524,11 @@ public class DeploymentService
|
||||
/// must NEVER surface to the caller or flip the committed status — "audit-write
|
||||
/// failure NEVER aborts the user-facing action" (Centralized Audit Log design).
|
||||
/// Any exception is swallowed and logged at Warning.
|
||||
/// <para>
|
||||
/// Every caller runs this AFTER its final <c>SaveChangesAsync</c>, so the row must be
|
||||
/// saved here (<see cref="IAuditService.LogAndSaveAsync"/>): a staged-only
|
||||
/// <c>LogAsync</c> row was discarded with the DI scope (code review 2026-12-02 DEP-1).
|
||||
/// </para>
|
||||
/// </summary>
|
||||
private async Task TryLogAuditAsync(
|
||||
string user,
|
||||
@@ -2534,7 +2541,7 @@ public class DeploymentService
|
||||
{
|
||||
try
|
||||
{
|
||||
await _auditService.LogAsync(
|
||||
await _auditService.LogAndSaveAsync(
|
||||
user, action, entityType, entityId, entityName, afterState, cancellationToken);
|
||||
}
|
||||
catch (Exception auditEx)
|
||||
@@ -2556,7 +2563,8 @@ public class DeploymentService
|
||||
{
|
||||
try
|
||||
{
|
||||
await _auditService.LogAsync(
|
||||
// Post-save, like TryLogAuditAsync: persist the row here (DEP-1).
|
||||
await _auditService.LogAndSaveAsync(
|
||||
user,
|
||||
action,
|
||||
"Instance",
|
||||
|
||||
@@ -737,6 +737,22 @@ public class ManagementActor : ReceiveActor
|
||||
await auditService.LogAsync(user, action, entityType, entityId, entityName, afterState);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Logs AND persists an audit entry, best-effort, for a handler that is NOT a
|
||||
/// configuration command (code review 2026-12-02 MGT-1).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <see cref="AuditAsync"/> only stages the row; for a command in
|
||||
/// <see cref="IsConfigurationCommand"/> the <c>ConfigurationCommandTransaction</c>'s final
|
||||
/// save flushes it. A command outside that list runs through plain
|
||||
/// <c>DispatchCommand</c> with no trailing save, so a staged row there was discarded with
|
||||
/// the scope (API keys, shared schemas, external-system methods, data-connection move).
|
||||
/// Such handlers call this AFTER their own save (or after a store call that saves
|
||||
/// internally); it never throws.
|
||||
/// </remarks>
|
||||
private static Task AuditAndSaveAsync(IServiceProvider sp, string user, string action, string entityType, string entityId, string entityName, object? afterState) =>
|
||||
sp.GetRequiredService<IAuditService>().LogAndSaveAsync(user, action, entityType, entityId, entityName, afterState);
|
||||
|
||||
// ========================================================================
|
||||
// Template handlers
|
||||
// ========================================================================
|
||||
@@ -1027,7 +1043,9 @@ public class ManagementActor : ReceiveActor
|
||||
var svc = sp.GetRequiredService<InstanceService>();
|
||||
var result = await svc.CreateInstanceAsync(cmd.UniqueName, cmd.TemplateId, cmd.SiteId, cmd.AreaId, user.Username);
|
||||
if (!result.IsSuccess) throw new ManagementCommandException(result.Error);
|
||||
await AuditAsync(sp, user.Username, "Create", "Instance", result.Value.Id.ToString(), result.Value.UniqueName, result.Value);
|
||||
// No AuditAsync here: InstanceService.CreateInstanceAsync audits the Create itself
|
||||
// (see the AuditAsync contract). Both rows used to be staged and lost (code review
|
||||
// 2026-12-02 TPL-3); now that the service saves its row, a second row would double-log.
|
||||
return result.Value;
|
||||
}
|
||||
|
||||
@@ -2378,7 +2396,10 @@ public class ManagementActor : ReceiveActor
|
||||
conn.SiteId = cmd.TargetSiteId;
|
||||
await repo.UpdateDataConnectionAsync(conn);
|
||||
await repo.SaveChangesAsync();
|
||||
await AuditAsync(sp, user, "Move", "DataConnection", conn.Id.ToString(), conn.Name, conn);
|
||||
// AuditAndSaveAsync (MGT-1): Move is not a configuration command, so a staged row
|
||||
// was never saved. The after-state is the scrubbed public shape (MGT-4) — the raw
|
||||
// entity carries the decrypted protocol configuration, credentials included.
|
||||
await AuditAndSaveAsync(sp, user, "Move", "DataConnection", conn.Id.ToString(), conn.Name, DataConnectionPublicShape(conn));
|
||||
return conn;
|
||||
}
|
||||
|
||||
@@ -2520,7 +2541,7 @@ public class ManagementActor : ReceiveActor
|
||||
await repo.AddExternalSystemMethodAsync(method);
|
||||
await repo.SaveChangesAsync();
|
||||
await InvalidateExternalDefinitionCacheAfterCommit(sp);
|
||||
await AuditAsync(sp, user, "Create", "ExternalSystemMethod", method.Id.ToString(), method.Name, method);
|
||||
await AuditAndSaveAsync(sp, user, "Create", "ExternalSystemMethod", method.Id.ToString(), method.Name, method);
|
||||
return method;
|
||||
}
|
||||
|
||||
@@ -2537,7 +2558,7 @@ public class ManagementActor : ReceiveActor
|
||||
await repo.UpdateExternalSystemMethodAsync(method);
|
||||
await repo.SaveChangesAsync();
|
||||
await InvalidateExternalDefinitionCacheAfterCommit(sp);
|
||||
await AuditAsync(sp, user, "Update", "ExternalSystemMethod", method.Id.ToString(), method.Name, method);
|
||||
await AuditAndSaveAsync(sp, user, "Update", "ExternalSystemMethod", method.Id.ToString(), method.Name, method);
|
||||
return method;
|
||||
}
|
||||
|
||||
@@ -2547,7 +2568,7 @@ public class ManagementActor : ReceiveActor
|
||||
await repo.DeleteExternalSystemMethodAsync(cmd.MethodId);
|
||||
await repo.SaveChangesAsync();
|
||||
await InvalidateExternalDefinitionCacheAfterCommit(sp);
|
||||
await AuditAsync(sp, user, "Delete", "ExternalSystemMethod", cmd.MethodId.ToString(), cmd.MethodId.ToString(), null);
|
||||
await AuditAndSaveAsync(sp, user, "Delete", "ExternalSystemMethod", cmd.MethodId.ToString(), cmd.MethodId.ToString(), null);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -3031,7 +3052,7 @@ public class ManagementActor : ReceiveActor
|
||||
var admin = sp.GetRequiredService<IInboundApiKeyAdmin>();
|
||||
var created = await admin.CreateAsync(cmd.Name, cmd.Methods);
|
||||
|
||||
await AuditAsync(sp, user, "Create", "ApiKey", created.KeyId, cmd.Name,
|
||||
await AuditAndSaveAsync(sp, user, "Create", "ApiKey", created.KeyId, cmd.Name,
|
||||
new { created.KeyId, cmd.Name });
|
||||
|
||||
return new
|
||||
@@ -3048,7 +3069,7 @@ public class ManagementActor : ReceiveActor
|
||||
var deleted = await admin.DeleteAsync(cmd.KeyId);
|
||||
if (!deleted)
|
||||
throw new ManagementCommandException($"API key '{cmd.KeyId}' not found.");
|
||||
await AuditAsync(sp, user, "Delete", "ApiKey", cmd.KeyId, cmd.KeyId, null);
|
||||
await AuditAndSaveAsync(sp, user, "Delete", "ApiKey", cmd.KeyId, cmd.KeyId, null);
|
||||
return deleted;
|
||||
}
|
||||
|
||||
@@ -3750,7 +3771,7 @@ public class ManagementActor : ReceiveActor
|
||||
|
||||
var schema = new SharedSchema { Name = name, Scope = cmd.Scope, SchemaJson = cmd.SchemaJson };
|
||||
await repo.AddAsync(schema);
|
||||
await AuditAsync(sp, user, "Create", "SharedSchema", schema.Id.ToString(), schema.Name, new { schema.Id, schema.Name, schema.Scope });
|
||||
await AuditAndSaveAsync(sp, user, "Create", "SharedSchema", schema.Id.ToString(), schema.Name, new { schema.Id, schema.Name, schema.Scope });
|
||||
return schema;
|
||||
}
|
||||
|
||||
@@ -3775,7 +3796,7 @@ public class ManagementActor : ReceiveActor
|
||||
schema.Scope = cmd.Scope;
|
||||
schema.SchemaJson = cmd.SchemaJson;
|
||||
await repo.UpdateAsync(schema);
|
||||
await AuditAsync(sp, user, "Update", "SharedSchema", schema.Id.ToString(), schema.Name, new { schema.Id, schema.Name, schema.Scope });
|
||||
await AuditAndSaveAsync(sp, user, "Update", "SharedSchema", schema.Id.ToString(), schema.Name, new { schema.Id, schema.Name, schema.Scope });
|
||||
return schema;
|
||||
}
|
||||
|
||||
@@ -3787,7 +3808,7 @@ public class ManagementActor : ReceiveActor
|
||||
// Site delete handler. Falls back to the id when the row is already absent.
|
||||
var schema = await repo.GetByIdAsync(cmd.SharedSchemaId);
|
||||
await repo.DeleteAsync(cmd.SharedSchemaId);
|
||||
await AuditAsync(sp, user, "Delete", "SharedSchema", cmd.SharedSchemaId.ToString(),
|
||||
await AuditAndSaveAsync(sp, user, "Delete", "SharedSchema", cmd.SharedSchemaId.ToString(),
|
||||
schema?.Name ?? cmd.SharedSchemaId.ToString(), null);
|
||||
return true;
|
||||
}
|
||||
@@ -4100,7 +4121,7 @@ public class ManagementActor : ReceiveActor
|
||||
var updated = await admin.SetEnabledAsync(cmd.KeyId, cmd.IsEnabled);
|
||||
if (!updated)
|
||||
throw new ManagementCommandException($"API key '{cmd.KeyId}' not found.");
|
||||
await AuditAsync(sp, user, "Update", "ApiKey", cmd.KeyId, cmd.KeyId,
|
||||
await AuditAndSaveAsync(sp, user, "Update", "ApiKey", cmd.KeyId, cmd.KeyId,
|
||||
new { cmd.KeyId, cmd.IsEnabled });
|
||||
return new { cmd.KeyId, cmd.IsEnabled };
|
||||
}
|
||||
@@ -4116,7 +4137,7 @@ public class ManagementActor : ReceiveActor
|
||||
var updated = await admin.SetMethodsAsync(cmd.KeyId, cmd.Methods);
|
||||
if (!updated)
|
||||
throw new ManagementCommandException($"API key '{cmd.KeyId}' not found.");
|
||||
await AuditAsync(sp, user, "Update", "ApiKey", cmd.KeyId, cmd.KeyId,
|
||||
await AuditAndSaveAsync(sp, user, "Update", "ApiKey", cmd.KeyId, cmd.KeyId,
|
||||
new { cmd.KeyId, cmd.Methods });
|
||||
return new { cmd.KeyId, Methods = cmd.Methods };
|
||||
}
|
||||
|
||||
@@ -70,7 +70,7 @@ public class AreaService
|
||||
await _repository.AddAreaAsync(area, cancellationToken);
|
||||
await _repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
await _auditService.LogAsync(user, "Create", "Area", area.Id.ToString(), name, area, cancellationToken);
|
||||
await _auditService.LogAndSaveAsync(user, "Create", "Area", area.Id.ToString(), name, area, cancellationToken);
|
||||
|
||||
return Result<Area>.Success(area);
|
||||
}
|
||||
@@ -107,7 +107,7 @@ public class AreaService
|
||||
await _repository.UpdateAreaAsync(area, cancellationToken);
|
||||
await _repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
await _auditService.LogAsync(user, "Update", "Area", area.Id.ToString(), name, area, cancellationToken);
|
||||
await _auditService.LogAndSaveAsync(user, "Update", "Area", area.Id.ToString(), name, area, cancellationToken);
|
||||
|
||||
return Result<Area>.Success(area);
|
||||
}
|
||||
@@ -167,7 +167,7 @@ public class AreaService
|
||||
await _repository.UpdateAreaAsync(area, cancellationToken);
|
||||
await _repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
await _auditService.LogAsync(user, "Move", "Area", area.Id.ToString(), area.Name, area, cancellationToken);
|
||||
await _auditService.LogAndSaveAsync(user, "Move", "Area", area.Id.ToString(), area.Name, area, cancellationToken);
|
||||
|
||||
return Result<Area>.Success(area);
|
||||
}
|
||||
@@ -218,7 +218,7 @@ public class AreaService
|
||||
await _repository.DeleteAreaAsync(areaId, cancellationToken);
|
||||
await _repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
await _auditService.LogAsync(user, "Delete", "Area", areaId.ToString(), area.Name, null, cancellationToken);
|
||||
await _auditService.LogAndSaveAsync(user, "Delete", "Area", areaId.ToString(), area.Name, null, cancellationToken);
|
||||
|
||||
return Result<bool>.Success(true);
|
||||
}
|
||||
|
||||
@@ -11,6 +11,9 @@ namespace ZB.MOM.WW.ScadaBridge.TemplateEngine.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Instance CRUD operations.
|
||||
/// Every mutation audits with <see cref="IAuditService.LogAndSaveAsync"/> AFTER its own save
|
||||
/// (code review 2026-12-02 TPL-3): a staged-only <c>LogAsync</c> row was lost whenever the
|
||||
/// caller — the management/CLI path — did not happen to save again.
|
||||
/// - Create instance from template at site
|
||||
/// - Assign to area
|
||||
/// - Override non-locked attribute values
|
||||
@@ -99,7 +102,7 @@ public class InstanceService
|
||||
try { await _repository.SaveChangesAsync(cancellationToken); }
|
||||
catch (InstanceNameConflictException ex) { return Result<Instance>.Failure(ex.Message); }
|
||||
|
||||
await _auditService.LogAsync(user, "Create", "Instance", instance.Id.ToString(),
|
||||
await _auditService.LogAndSaveAsync(user, "Create", "Instance", instance.Id.ToString(),
|
||||
uniqueName, instance, cancellationToken);
|
||||
|
||||
return Result<Instance>.Success(instance);
|
||||
@@ -136,7 +139,7 @@ public class InstanceService
|
||||
await _repository.UpdateInstanceAsync(instance, cancellationToken);
|
||||
await _repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
await _auditService.LogAsync(user, "AssignArea", "Instance", instance.Id.ToString(),
|
||||
await _auditService.LogAndSaveAsync(user, "AssignArea", "Instance", instance.Id.ToString(),
|
||||
instance.UniqueName, instance, cancellationToken);
|
||||
|
||||
return Result<Instance>.Success(instance);
|
||||
@@ -187,7 +190,7 @@ public class InstanceService
|
||||
await _repository.UpdateInstanceAttributeOverrideAsync(existingOverride, cancellationToken);
|
||||
await _repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
await _auditService.LogAsync(user, "UpdateOverride", "InstanceAttributeOverride",
|
||||
await _auditService.LogAndSaveAsync(user, "UpdateOverride", "InstanceAttributeOverride",
|
||||
existingOverride.Id.ToString(), attributeName, existingOverride, cancellationToken);
|
||||
|
||||
return Result<InstanceAttributeOverride>.Success(existingOverride);
|
||||
@@ -204,7 +207,7 @@ public class InstanceService
|
||||
await _repository.AddInstanceAttributeOverrideAsync(newOverride, cancellationToken);
|
||||
await _repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
await _auditService.LogAsync(user, "CreateOverride", "InstanceAttributeOverride",
|
||||
await _auditService.LogAndSaveAsync(user, "CreateOverride", "InstanceAttributeOverride",
|
||||
newOverride.Id.ToString(), attributeName, newOverride, cancellationToken);
|
||||
|
||||
return Result<InstanceAttributeOverride>.Success(newOverride);
|
||||
@@ -272,7 +275,7 @@ public class InstanceService
|
||||
await _repository.UpdateInstanceAlarmOverrideAsync(existingOverride, cancellationToken);
|
||||
await _repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
await _auditService.LogAsync(user, "UpdateAlarmOverride", "InstanceAlarmOverride",
|
||||
await _auditService.LogAndSaveAsync(user, "UpdateAlarmOverride", "InstanceAlarmOverride",
|
||||
existingOverride.Id.ToString(), alarmCanonicalName, existingOverride, cancellationToken);
|
||||
|
||||
return Result<InstanceAlarmOverride>.Success(existingOverride);
|
||||
@@ -290,7 +293,7 @@ public class InstanceService
|
||||
await _repository.AddInstanceAlarmOverrideAsync(newOverride, cancellationToken);
|
||||
await _repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
await _auditService.LogAsync(user, "CreateAlarmOverride", "InstanceAlarmOverride",
|
||||
await _auditService.LogAndSaveAsync(user, "CreateAlarmOverride", "InstanceAlarmOverride",
|
||||
newOverride.Id.ToString(), alarmCanonicalName, newOverride, cancellationToken);
|
||||
|
||||
return Result<InstanceAlarmOverride>.Success(newOverride);
|
||||
@@ -320,7 +323,7 @@ public class InstanceService
|
||||
await _repository.DeleteInstanceAlarmOverrideAsync(existing.Id, cancellationToken);
|
||||
await _repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
await _auditService.LogAsync(user, "DeleteAlarmOverride", "InstanceAlarmOverride",
|
||||
await _auditService.LogAndSaveAsync(user, "DeleteAlarmOverride", "InstanceAlarmOverride",
|
||||
existing.Id.ToString(), alarmCanonicalName, existing, cancellationToken);
|
||||
|
||||
return Result<bool>.Success(true);
|
||||
@@ -373,7 +376,7 @@ public class InstanceService
|
||||
|
||||
await _repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
await _auditService.LogAsync(user, "SetConnectionBindings", "Instance",
|
||||
await _auditService.LogAndSaveAsync(user, "SetConnectionBindings", "Instance",
|
||||
instance.Id.ToString(), instance.UniqueName, bindings, cancellationToken);
|
||||
|
||||
return Result<IReadOnlyList<InstanceConnectionBinding>>.Success(results);
|
||||
@@ -396,7 +399,7 @@ public class InstanceService
|
||||
await _repository.UpdateInstanceAsync(instance, cancellationToken);
|
||||
await _repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
await _auditService.LogAsync(user, "Enable", "Instance", instance.Id.ToString(),
|
||||
await _auditService.LogAndSaveAsync(user, "Enable", "Instance", instance.Id.ToString(),
|
||||
instance.UniqueName, instance, cancellationToken);
|
||||
|
||||
return Result<Instance>.Success(instance);
|
||||
@@ -419,7 +422,7 @@ public class InstanceService
|
||||
await _repository.UpdateInstanceAsync(instance, cancellationToken);
|
||||
await _repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
await _auditService.LogAsync(user, "Disable", "Instance", instance.Id.ToString(),
|
||||
await _auditService.LogAndSaveAsync(user, "Disable", "Instance", instance.Id.ToString(),
|
||||
instance.UniqueName, instance, cancellationToken);
|
||||
|
||||
return Result<Instance>.Success(instance);
|
||||
@@ -441,7 +444,7 @@ public class InstanceService
|
||||
await _repository.DeleteInstanceAsync(instanceId, cancellationToken);
|
||||
await _repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
await _auditService.LogAsync(user, "Delete", "Instance", instanceId.ToString(),
|
||||
await _auditService.LogAndSaveAsync(user, "Delete", "Instance", instanceId.ToString(),
|
||||
instance.UniqueName, null, cancellationToken);
|
||||
|
||||
return Result<bool>.Success(true);
|
||||
|
||||
@@ -51,7 +51,7 @@ public class SiteService
|
||||
await _repository.AddSiteAsync(site, cancellationToken);
|
||||
await _repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
await _auditService.LogAsync(user, "Create", "Site", site.Id.ToString(), name, site, cancellationToken);
|
||||
await _auditService.LogAndSaveAsync(user, "Create", "Site", site.Id.ToString(), name, site, cancellationToken);
|
||||
|
||||
return Result<Site>.Success(site);
|
||||
}
|
||||
@@ -76,7 +76,7 @@ public class SiteService
|
||||
await _repository.UpdateSiteAsync(site, cancellationToken);
|
||||
await _repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
await _auditService.LogAsync(user, "Update", "Site", site.Id.ToString(), name, site, cancellationToken);
|
||||
await _auditService.LogAndSaveAsync(user, "Update", "Site", site.Id.ToString(), name, site, cancellationToken);
|
||||
|
||||
return Result<Site>.Success(site);
|
||||
}
|
||||
@@ -104,7 +104,7 @@ public class SiteService
|
||||
await _repository.DeleteSiteAsync(siteId, cancellationToken);
|
||||
await _repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
await _auditService.LogAsync(user, "Delete", "Site", siteId.ToString(), site.Name, null, cancellationToken);
|
||||
await _auditService.LogAndSaveAsync(user, "Delete", "Site", siteId.ToString(), site.Name, null, cancellationToken);
|
||||
|
||||
return Result<bool>.Success(true);
|
||||
}
|
||||
@@ -144,7 +144,7 @@ public class SiteService
|
||||
await _repository.DeleteDataConnectionAsync(connectionId, cancellationToken);
|
||||
await _repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
await _auditService.LogAsync(user, "Delete", "DataConnection",
|
||||
await _auditService.LogAndSaveAsync(user, "Delete", "DataConnection",
|
||||
connectionId.ToString(), connection.Name, null, cancellationToken);
|
||||
|
||||
return Result<bool>.Success(true);
|
||||
|
||||
Reference in New Issue
Block a user