refactor(auditlog): rename audit correlation field, add cross-helper tests
This commit is contained in:
@@ -0,0 +1,179 @@
|
||||
using Akka.Actor;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using ScadaLink.Commons.Entities.Audit;
|
||||
using ScadaLink.Commons.Interfaces.Services;
|
||||
using ScadaLink.Commons.Types.Enums;
|
||||
using ScadaLink.SiteRuntime.Scripts;
|
||||
|
||||
namespace ScadaLink.SiteRuntime.Tests.Scripts;
|
||||
|
||||
/// <summary>
|
||||
/// Audit Log #23 — execution-correlation tests exercised through a full
|
||||
/// <see cref="ScriptRuntimeContext"/>:
|
||||
///
|
||||
/// <list type="bullet">
|
||||
/// <item><description>
|
||||
/// The <c>?? Guid.NewGuid()</c> fallback in the <see cref="ScriptRuntimeContext"/>
|
||||
/// ctor: when no audit correlation id is supplied (tag-change / timer-triggered
|
||||
/// executions) a fresh, non-empty id is minted and stamped on the emitted rows.
|
||||
/// </description></item>
|
||||
/// <item><description>
|
||||
/// The execution-wide contract: an <c>ExternalSystem.Call</c> and a sync
|
||||
/// <c>Database</c> write performed through ONE context share a single
|
||||
/// <see cref="AuditEvent.CorrelationId"/>.
|
||||
/// </description></item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
public class ExecutionCorrelationContextTests
|
||||
{
|
||||
/// <summary>
|
||||
/// In-memory <see cref="IAuditWriter"/> capturing every emitted event
|
||||
/// (mirrors the <c>CapturingAuditWriter</c> stubs in
|
||||
/// <see cref="ExternalSystemCallAuditEmissionTests"/> /
|
||||
/// <see cref="DatabaseSyncEmissionTests"/>).
|
||||
/// </summary>
|
||||
private sealed class CapturingAuditWriter : IAuditWriter
|
||||
{
|
||||
public List<AuditEvent> Events { get; } = new();
|
||||
|
||||
public Task WriteAsync(AuditEvent evt, CancellationToken ct = default)
|
||||
{
|
||||
Events.Add(evt);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
private const string InstanceName = "Plant.Pump42";
|
||||
private const string ConnectionName = "machineData";
|
||||
|
||||
/// <summary>
|
||||
/// Builds a full <see cref="ScriptRuntimeContext"/> wired with the external
|
||||
/// system client, database gateway and audit writer the cross-helper test
|
||||
/// needs. The actor refs are <see cref="ActorRefs.Nobody"/> — the
|
||||
/// integration helpers (ExternalSystem / Database) never touch them — and
|
||||
/// <paramref name="auditCorrelationId"/> defaults to null so the ctor's
|
||||
/// <c>?? Guid.NewGuid()</c> fallback is exercised unless a test supplies one.
|
||||
/// </summary>
|
||||
private static ScriptRuntimeContext CreateContext(
|
||||
IExternalSystemClient? externalSystemClient,
|
||||
IDatabaseGateway? databaseGateway,
|
||||
IAuditWriter? auditWriter,
|
||||
Guid? auditCorrelationId = null)
|
||||
{
|
||||
var compilationService = new ScriptCompilationService(
|
||||
NullLogger<ScriptCompilationService>.Instance);
|
||||
var sharedScriptLibrary = new SharedScriptLibrary(
|
||||
compilationService, NullLogger<SharedScriptLibrary>.Instance);
|
||||
|
||||
return new ScriptRuntimeContext(
|
||||
ActorRefs.Nobody,
|
||||
ActorRefs.Nobody,
|
||||
sharedScriptLibrary,
|
||||
currentCallDepth: 0,
|
||||
maxCallDepth: 10,
|
||||
askTimeout: TimeSpan.FromSeconds(5),
|
||||
instanceName: InstanceName,
|
||||
logger: NullLogger.Instance,
|
||||
externalSystemClient: externalSystemClient,
|
||||
databaseGateway: databaseGateway,
|
||||
storeAndForward: null,
|
||||
siteCommunicationActor: null,
|
||||
siteId: "site-77",
|
||||
sourceScript: "ScriptActor:OnTick",
|
||||
auditWriter: auditWriter,
|
||||
operationTrackingStore: null,
|
||||
cachedForwarder: null,
|
||||
auditCorrelationId: auditCorrelationId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Spin up a fresh in-memory SQLite database with a tiny single-table
|
||||
/// schema. The keep-alive root must outlive any auditing wrapper the test
|
||||
/// exercises (mirrors <c>DatabaseSyncEmissionTests.NewInMemoryDb</c>).
|
||||
/// </summary>
|
||||
private static SqliteConnection NewInMemoryDb(out SqliteConnection keepAlive)
|
||||
{
|
||||
var dbName = $"db-{Guid.NewGuid():N}";
|
||||
var connStr = $"Data Source={dbName};Mode=Memory;Cache=Shared";
|
||||
|
||||
keepAlive = new SqliteConnection(connStr);
|
||||
keepAlive.Open();
|
||||
using (var seed = keepAlive.CreateCommand())
|
||||
{
|
||||
seed.CommandText =
|
||||
"CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT NOT NULL);";
|
||||
seed.ExecuteNonQuery();
|
||||
}
|
||||
|
||||
var live = new SqliteConnection(connStr);
|
||||
live.Open();
|
||||
return live;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task NoCorrelationIdSupplied_SyncCall_StampsFreshNonEmptyCorrelationId()
|
||||
{
|
||||
// No auditCorrelationId argument — the ScriptRuntimeContext ctor's
|
||||
// `?? Guid.NewGuid()` fallback must mint one (this is the unsupplied-id
|
||||
// branch every other audit test bypasses by passing an explicit id).
|
||||
var client = new Mock<IExternalSystemClient>();
|
||||
client
|
||||
.Setup(c => c.CallAsync("ERP", "GetOrder", It.IsAny<IReadOnlyDictionary<string, object?>?>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new ExternalCallResult(true, "{}", null));
|
||||
var writer = new CapturingAuditWriter();
|
||||
|
||||
var context = CreateContext(client.Object, databaseGateway: null, writer);
|
||||
await context.ExternalSystem.Call("ERP", "GetOrder");
|
||||
|
||||
var evt = Assert.Single(writer.Events);
|
||||
Assert.NotNull(evt.CorrelationId);
|
||||
Assert.NotEqual(Guid.Empty, evt.CorrelationId!.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SameContext_ApiCallAndDbWrite_ShareTheSameCorrelationId()
|
||||
{
|
||||
// The execution-wide contract: an ExternalSystem.Call AND a sync
|
||||
// Database write performed through ONE ScriptRuntimeContext must both
|
||||
// carry the same execution correlation id, so an audit reader can tie
|
||||
// every trust-boundary action from one script run together.
|
||||
using var keepAlive = new SqliteConnection("Data Source=ecc;Mode=Memory;Cache=Shared");
|
||||
var innerDb = NewInMemoryDb(out var _);
|
||||
|
||||
var client = new Mock<IExternalSystemClient>();
|
||||
client
|
||||
.Setup(c => c.CallAsync("ERP", "GetOrder", It.IsAny<IReadOnlyDictionary<string, object?>?>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new ExternalCallResult(true, "{}", null));
|
||||
|
||||
var gateway = new Mock<IDatabaseGateway>();
|
||||
gateway
|
||||
.Setup(g => g.GetConnectionAsync(ConnectionName, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(innerDb);
|
||||
|
||||
var writer = new CapturingAuditWriter();
|
||||
var context = CreateContext(client.Object, gateway.Object, writer);
|
||||
|
||||
// 1) outbound API call through the context's ExternalSystem helper.
|
||||
await context.ExternalSystem.Call("ERP", "GetOrder");
|
||||
|
||||
// 2) sync DB write through the SAME context's Database helper.
|
||||
await using (var conn = await context.Database.Connection(ConnectionName))
|
||||
await using (var cmd = conn.CreateCommand())
|
||||
{
|
||||
cmd.CommandText = "INSERT INTO t (id, name) VALUES (1, 'alpha')";
|
||||
await cmd.ExecuteNonQueryAsync();
|
||||
}
|
||||
|
||||
Assert.Equal(2, writer.Events.Count);
|
||||
var apiRow = Assert.Single(writer.Events, e => e.Channel == AuditChannel.ApiOutbound);
|
||||
var dbRow = Assert.Single(writer.Events, e => e.Channel == AuditChannel.DbOutbound);
|
||||
|
||||
Assert.NotNull(apiRow.CorrelationId);
|
||||
Assert.NotEqual(Guid.Empty, apiRow.CorrelationId!.Value);
|
||||
// The ApiCall row and the DbWrite row, emitted by two different helpers
|
||||
// resolved off one context, carry the identical execution correlation id.
|
||||
Assert.Equal(apiRow.CorrelationId, dbRow.CorrelationId);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user