refactor: rename ScadaLink → ZB.MOM.WW.ScadaBridge (code + projects + namespaces)
Solution + 23 src projects + 26 test projects renamed; folders, csproj, namespaces, and ScadaLinkDbContext/ScadaBridgeDbContext class updated. ActorSystem "scadalink" → "scadabridge", Akka seed-node URLs migrated. SQL roles/logins, LDAP domains, CLI command name, and CLI config dir (~/.scadalink → ~/.scadabridge) also renamed. Build green; 5 Host.Tests fail awaiting SQL login rename in next commit. Pre-existing StaleTagMonitor timing flakes unchanged. Rename script committed at tools/rename-to-scadabridge.sh.
This commit is contained in:
@@ -0,0 +1,134 @@
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Messages.RemoteQuery;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Regression tests for SiteEventLogging-010: previously untested behaviours —
|
||||
/// the query service error path and the recorder's disposed-state semantics.
|
||||
/// </summary>
|
||||
public class EventLogCoverageTests : IDisposable
|
||||
{
|
||||
private readonly string _dbPath;
|
||||
|
||||
public EventLogCoverageTests()
|
||||
{
|
||||
_dbPath = Path.Combine(Path.GetTempPath(), $"test_coverage_{Guid.NewGuid()}.db");
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (File.Exists(_dbPath)) File.Delete(_dbPath);
|
||||
}
|
||||
|
||||
private SiteEventLogger NewLogger() => new(
|
||||
Options.Create(new SiteEventLogOptions { DatabasePath = _dbPath }),
|
||||
NullLogger<SiteEventLogger>.Instance);
|
||||
|
||||
private static EventLogQueryRequest MakeRequest() => new(
|
||||
CorrelationId: "corr-err",
|
||||
SiteId: "site-1",
|
||||
From: null,
|
||||
To: null,
|
||||
EventType: null,
|
||||
Severity: null,
|
||||
InstanceId: null,
|
||||
KeywordFilter: null,
|
||||
ContinuationToken: null,
|
||||
PageSize: 500,
|
||||
Timestamp: DateTimeOffset.UtcNow);
|
||||
|
||||
[Fact]
|
||||
public void ExecuteQuery_ReturnsFailureResponse_WhenDatabaseUnavailable()
|
||||
{
|
||||
// The catch block in EventLogQueryService.ExecuteQuery was untested.
|
||||
// Disposing the recorder makes WithConnection throw ObjectDisposedException;
|
||||
// the query service must convert that into a Success=false response rather
|
||||
// than letting the exception escape to the actor.
|
||||
var logger = NewLogger();
|
||||
var queryService = new EventLogQueryService(
|
||||
logger,
|
||||
Options.Create(new SiteEventLogOptions { DatabasePath = _dbPath }),
|
||||
NullLogger<EventLogQueryService>.Instance);
|
||||
|
||||
logger.Dispose();
|
||||
|
||||
var response = queryService.ExecuteQuery(MakeRequest());
|
||||
|
||||
Assert.False(response.Success);
|
||||
Assert.NotNull(response.ErrorMessage);
|
||||
Assert.Empty(response.Entries);
|
||||
Assert.Null(response.ContinuationToken);
|
||||
Assert.Equal("corr-err", response.CorrelationId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LogEventAsync_AfterDispose_FaultsTask_NotReportsSuccess()
|
||||
{
|
||||
// SiteEventLogging-012: when the logger has been disposed the event cannot
|
||||
// be persisted. The returned Task must FAULT (not complete successfully) so
|
||||
// an awaiting caller can distinguish a dropped audit event from a written
|
||||
// one. Per the XML doc contract, the Task "faults if the write fails".
|
||||
var logger = NewLogger();
|
||||
logger.Dispose();
|
||||
|
||||
var task = logger.LogEventAsync("script", "Info", null, "Source", "After dispose");
|
||||
|
||||
await Assert.ThrowsAsync<ObjectDisposedException>(
|
||||
() => task.WaitAsync(TimeSpan.FromSeconds(5)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dispose_IsIdempotent()
|
||||
{
|
||||
// Re-entrant / repeated Dispose must be a safe no-op.
|
||||
var logger = NewLogger();
|
||||
logger.Dispose();
|
||||
logger.Dispose();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LogEventAsync_EnqueuedThenDisposed_FaultsTask_WhenWriteCannotComplete()
|
||||
{
|
||||
// SiteEventLogging-012, second path: an event enqueued onto the background
|
||||
// writer just before disposal must NOT be reported as persisted if the
|
||||
// writer's WithConnection returns false (logger disposed mid-drain). We
|
||||
// flood the queue and dispose immediately; any event whose write did not
|
||||
// actually run must have a faulted Task, never a successful one.
|
||||
var logger = NewLogger();
|
||||
|
||||
var tasks = new List<Task>();
|
||||
for (int i = 0; i < 200; i++)
|
||||
{
|
||||
tasks.Add(logger.LogEventAsync("script", "Info", null, "Source", $"event-{i}"));
|
||||
}
|
||||
|
||||
logger.Dispose();
|
||||
|
||||
// Every task must reach a terminal state. None may be left as a successful
|
||||
// completion for an event the writer never persisted: a task is either
|
||||
// RanToCompletion (genuinely written before the connection closed) or
|
||||
// Faulted (could not be persisted). Count persisted vs faulted and assert
|
||||
// the persisted count matches the actual row count.
|
||||
await Task.WhenAll(tasks.Select(t => t.ContinueWith(_ => { })));
|
||||
|
||||
var succeeded = tasks.Count(t => t.Status == TaskStatus.RanToCompletion);
|
||||
var faulted = tasks.Count(t => t.IsFaulted);
|
||||
Assert.Equal(tasks.Count, succeeded + faulted);
|
||||
|
||||
long rowCount;
|
||||
using (var conn = new Microsoft.Data.Sqlite.SqliteConnection($"Data Source={_dbPath}"))
|
||||
{
|
||||
conn.Open();
|
||||
using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = "SELECT COUNT(*) FROM site_events";
|
||||
rowCount = (long)cmd.ExecuteScalar()!;
|
||||
}
|
||||
|
||||
// A successfully-completed Task must correspond to a row that was actually
|
||||
// written. If the disposed-mid-drain path falsely reported success, the
|
||||
// success count would exceed the row count.
|
||||
Assert.Equal(rowCount, succeeded);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
using Akka.Actor;
|
||||
using Akka.TestKit.Xunit2;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Messages.RemoteQuery;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Regression tests for SiteEventLogging-010: the actor message contract of
|
||||
/// <see cref="EventLogHandlerActor"/> was previously untested.
|
||||
/// </summary>
|
||||
public class EventLogHandlerActorTests : TestKit
|
||||
{
|
||||
/// <summary>Test double returning a canned response and recording the request.</summary>
|
||||
private sealed class FakeQueryService : IEventLogQueryService
|
||||
{
|
||||
private readonly Func<EventLogQueryRequest, EventLogQueryResponse> _handler;
|
||||
public EventLogQueryRequest? LastRequest { get; private set; }
|
||||
|
||||
public FakeQueryService(Func<EventLogQueryRequest, EventLogQueryResponse> handler)
|
||||
=> _handler = handler;
|
||||
|
||||
public EventLogQueryResponse ExecuteQuery(EventLogQueryRequest request)
|
||||
{
|
||||
LastRequest = request;
|
||||
return _handler(request);
|
||||
}
|
||||
}
|
||||
|
||||
private static EventLogQueryRequest MakeRequest(string correlationId) => new(
|
||||
CorrelationId: correlationId,
|
||||
SiteId: "site-1",
|
||||
From: null,
|
||||
To: null,
|
||||
EventType: null,
|
||||
Severity: null,
|
||||
InstanceId: null,
|
||||
KeywordFilter: null,
|
||||
ContinuationToken: null,
|
||||
PageSize: 500,
|
||||
Timestamp: DateTimeOffset.UtcNow);
|
||||
|
||||
private static EventLogQueryResponse MakeResponse(EventLogQueryRequest req, bool success = true) => new(
|
||||
CorrelationId: req.CorrelationId,
|
||||
SiteId: req.SiteId,
|
||||
Entries: [],
|
||||
ContinuationToken: null,
|
||||
HasMore: false,
|
||||
Success: success,
|
||||
ErrorMessage: success ? null : "boom",
|
||||
Timestamp: DateTimeOffset.UtcNow);
|
||||
|
||||
[Fact]
|
||||
public void Actor_RepliesToSender_WithQueryResponse()
|
||||
{
|
||||
var fake = new FakeQueryService(req => MakeResponse(req));
|
||||
var actor = Sys.ActorOf(Props.Create(() => new EventLogHandlerActor(fake)));
|
||||
|
||||
var request = MakeRequest("corr-1");
|
||||
actor.Tell(request, TestActor);
|
||||
|
||||
var response = ExpectMsg<EventLogQueryResponse>();
|
||||
Assert.Equal("corr-1", response.CorrelationId);
|
||||
Assert.Equal("site-1", response.SiteId);
|
||||
Assert.True(response.Success);
|
||||
Assert.Same(request, fake.LastRequest);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Actor_PropagatesQueryServiceErrorResponse_ToSender()
|
||||
{
|
||||
var fake = new FakeQueryService(req => MakeResponse(req, success: false));
|
||||
var actor = Sys.ActorOf(Props.Create(() => new EventLogHandlerActor(fake)));
|
||||
|
||||
actor.Tell(MakeRequest("corr-2"), TestActor);
|
||||
|
||||
var response = ExpectMsg<EventLogQueryResponse>();
|
||||
Assert.False(response.Success);
|
||||
Assert.Equal("corr-2", response.CorrelationId);
|
||||
Assert.Equal("boom", response.ErrorMessage);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,380 @@
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests;
|
||||
|
||||
public class EventLogPurgeServiceTests : IDisposable
|
||||
{
|
||||
private readonly SiteEventLogger _eventLogger;
|
||||
private readonly string _dbPath;
|
||||
private readonly SiteEventLogOptions _options;
|
||||
|
||||
/// <summary>
|
||||
/// SiteEventLogging-023: stop flag for the concurrent stress test. Declared as
|
||||
/// a <c>volatile</c> field so every writer thread observes the main thread's
|
||||
/// `_stop = true` write without depending on JIT/runtime quirks. A plain
|
||||
/// <c>bool</c> local would be legal-cached in a register inside the tight
|
||||
/// <c>while (!_stop)</c> loop under release-mode optimisation.
|
||||
/// </summary>
|
||||
private volatile bool _stop;
|
||||
|
||||
public EventLogPurgeServiceTests()
|
||||
{
|
||||
_dbPath = Path.Combine(Path.GetTempPath(), $"test_purge_{Guid.NewGuid()}.db");
|
||||
_options = new SiteEventLogOptions
|
||||
{
|
||||
DatabasePath = _dbPath,
|
||||
RetentionDays = 30,
|
||||
MaxStorageMb = 1024
|
||||
};
|
||||
_eventLogger = new SiteEventLogger(
|
||||
Options.Create(_options),
|
||||
NullLogger<SiteEventLogger>.Instance);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_eventLogger.Dispose();
|
||||
if (File.Exists(_dbPath)) File.Delete(_dbPath);
|
||||
}
|
||||
|
||||
private EventLogPurgeService CreatePurgeService(
|
||||
SiteEventLogOptions? optionsOverride = null,
|
||||
SiteEventLogActiveNodeCheck? isActiveNode = null)
|
||||
{
|
||||
var opts = optionsOverride ?? _options;
|
||||
return new EventLogPurgeService(
|
||||
_eventLogger,
|
||||
Options.Create(opts),
|
||||
NullLogger<EventLogPurgeService>.Instance,
|
||||
isActiveNode);
|
||||
}
|
||||
|
||||
private void InsertEventWithTimestamp(DateTimeOffset timestamp)
|
||||
{
|
||||
_eventLogger.WithConnection(connection =>
|
||||
{
|
||||
using var cmd = connection.CreateCommand();
|
||||
cmd.CommandText = """
|
||||
INSERT INTO site_events (timestamp, event_type, severity, source, message)
|
||||
VALUES ($ts, 'script', 'Info', 'Test', 'Test message')
|
||||
""";
|
||||
cmd.Parameters.AddWithValue("$ts", timestamp.ToString("o"));
|
||||
cmd.ExecuteNonQuery();
|
||||
});
|
||||
}
|
||||
|
||||
private long GetEventCount()
|
||||
{
|
||||
return _eventLogger.WithConnection(connection =>
|
||||
{
|
||||
using var cmd = connection.CreateCommand();
|
||||
cmd.CommandText = "SELECT COUNT(*) FROM site_events";
|
||||
return (long)cmd.ExecuteScalar()!;
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PurgeByRetention_DeletesOldEvents()
|
||||
{
|
||||
// Insert an old event (31 days ago) and a recent one
|
||||
InsertEventWithTimestamp(DateTimeOffset.UtcNow.AddDays(-31));
|
||||
InsertEventWithTimestamp(DateTimeOffset.UtcNow);
|
||||
|
||||
var purge = CreatePurgeService();
|
||||
purge.RunPurge();
|
||||
|
||||
Assert.Equal(1, GetEventCount());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PurgeByRetention_KeepsRecentEvents()
|
||||
{
|
||||
InsertEventWithTimestamp(DateTimeOffset.UtcNow.AddDays(-29));
|
||||
InsertEventWithTimestamp(DateTimeOffset.UtcNow.AddDays(-1));
|
||||
InsertEventWithTimestamp(DateTimeOffset.UtcNow);
|
||||
|
||||
var purge = CreatePurgeService();
|
||||
purge.RunPurge();
|
||||
|
||||
Assert.Equal(3, GetEventCount());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PurgeByStorageCap_DeletesOldestWhenOverCap()
|
||||
{
|
||||
// Insert enough events to have some data
|
||||
for (int i = 0; i < 100; i++)
|
||||
{
|
||||
InsertEventWithTimestamp(DateTimeOffset.UtcNow);
|
||||
}
|
||||
|
||||
// Set an artificially small cap to trigger purge
|
||||
var smallCapOptions = new SiteEventLogOptions
|
||||
{
|
||||
DatabasePath = _dbPath,
|
||||
RetentionDays = 30,
|
||||
MaxStorageMb = 0 // 0 MB cap forces purge
|
||||
};
|
||||
|
||||
var purge = CreatePurgeService(smallCapOptions);
|
||||
purge.RunPurge();
|
||||
|
||||
// All events should be purged since cap is 0
|
||||
Assert.Equal(0, GetEventCount());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetDatabaseSizeBytes_ReturnsPositiveValue()
|
||||
{
|
||||
InsertEventWithTimestamp(DateTimeOffset.UtcNow);
|
||||
|
||||
var purge = CreatePurgeService();
|
||||
var size = purge.GetDatabaseSizeBytes();
|
||||
|
||||
Assert.True(size > 0);
|
||||
}
|
||||
|
||||
private void InsertBulkEvents(int count)
|
||||
{
|
||||
// Each event carries a sizeable details payload so the database grows
|
||||
// measurably and the storage cap can be exercised against a realistic file.
|
||||
var details = new string('x', 2000);
|
||||
_eventLogger.WithConnection(connection =>
|
||||
{
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
using var cmd = connection.CreateCommand();
|
||||
cmd.CommandText = """
|
||||
INSERT INTO site_events (timestamp, event_type, severity, source, message, details)
|
||||
VALUES ($ts, 'script', 'Info', 'Test', 'Bulk event', $details)
|
||||
""";
|
||||
cmd.Parameters.AddWithValue("$ts", DateTimeOffset.UtcNow.ToString("o"));
|
||||
cmd.Parameters.AddWithValue("$details", details);
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private long MinEventId()
|
||||
{
|
||||
return _eventLogger.WithConnection(connection =>
|
||||
{
|
||||
using var cmd = connection.CreateCommand();
|
||||
cmd.CommandText = "SELECT MIN(id) FROM site_events";
|
||||
var result = cmd.ExecuteScalar();
|
||||
return result is long l ? l : 0;
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PurgeByStorageCap_StopsWhenUnderCap_DoesNotEmptyTable()
|
||||
{
|
||||
// Regression test for SiteEventLogging-001 / -002:
|
||||
// a realistic non-zero cap must trim the oldest events to the budget,
|
||||
// not delete the entire table.
|
||||
InsertBulkEvents(3000);
|
||||
|
||||
var purge = CreatePurgeService();
|
||||
var totalSize = purge.GetDatabaseSizeBytes();
|
||||
|
||||
// Cap at roughly half the current database size — purge must keep some rows.
|
||||
var capBytes = totalSize / 2;
|
||||
var capOptions = new SiteEventLogOptions
|
||||
{
|
||||
DatabasePath = _dbPath,
|
||||
RetentionDays = 30,
|
||||
MaxStorageMb = (int)Math.Max(1, capBytes / (1024 * 1024))
|
||||
};
|
||||
|
||||
var cappedPurge = CreatePurgeService(capOptions);
|
||||
cappedPurge.RunPurge();
|
||||
|
||||
var remaining = GetEventCount();
|
||||
Assert.True(remaining > 0, "Storage-cap purge must not delete the entire table.");
|
||||
Assert.True(remaining < 3000, "Storage-cap purge must remove some events when over cap.");
|
||||
|
||||
// The database must actually be back under the cap after purge.
|
||||
var finalSize = cappedPurge.GetDatabaseSizeBytes();
|
||||
var finalCapBytes = (long)capOptions.MaxStorageMb * 1024 * 1024;
|
||||
Assert.True(finalSize <= finalCapBytes,
|
||||
$"Database size {finalSize} must be at or below cap {finalCapBytes} after purge.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PurgeByStorageCap_RemovesOldestEventsFirst()
|
||||
{
|
||||
// Regression test for SiteEventLogging-002: only the oldest events
|
||||
// (lowest ids) should be removed when trimming to the cap.
|
||||
InsertBulkEvents(3000);
|
||||
|
||||
var purge = CreatePurgeService();
|
||||
var totalSize = purge.GetDatabaseSizeBytes();
|
||||
|
||||
var capOptions = new SiteEventLogOptions
|
||||
{
|
||||
DatabasePath = _dbPath,
|
||||
RetentionDays = 30,
|
||||
MaxStorageMb = (int)Math.Max(1, (totalSize / 2) / (1024 * 1024))
|
||||
};
|
||||
|
||||
var minIdBefore = MinEventId();
|
||||
var cappedPurge = CreatePurgeService(capOptions);
|
||||
cappedPurge.RunPurge();
|
||||
var minIdAfter = MinEventId();
|
||||
|
||||
// The surviving rows must be the newest ones — minimum id has advanced.
|
||||
Assert.True(minIdAfter > minIdBefore,
|
||||
"Oldest events (lowest ids) must be purged first.");
|
||||
|
||||
// The newest event (highest id) must still be present.
|
||||
var newestPresent = _eventLogger.WithConnection(connection =>
|
||||
{
|
||||
using var cmd = connection.CreateCommand();
|
||||
cmd.CommandText = "SELECT COUNT(*) FROM site_events WHERE id = 3000";
|
||||
return (long)cmd.ExecuteScalar()!;
|
||||
});
|
||||
Assert.Equal(1L, newestPresent);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_DoesNotBlock_OnTheInitialPurge()
|
||||
{
|
||||
// SiteEventLogging-014 (re-triaged): on .NET 8+ BackgroundService runs
|
||||
// ExecuteAsync on a thread-pool thread — the synchronous prelude (the
|
||||
// initial RunPurge()) does NOT execute on the host startup thread, so
|
||||
// StartAsync returns promptly and host startup / the /health/ready gate is
|
||||
// not blocked even by a large initial purge. This test pins that behaviour:
|
||||
// StartAsync returns fast, and the initial purge still happens shortly
|
||||
// afterwards on the background scheduler.
|
||||
InsertEventWithTimestamp(DateTimeOffset.UtcNow.AddDays(-31));
|
||||
Assert.Equal(1, GetEventCount());
|
||||
|
||||
var purge = CreatePurgeService();
|
||||
using var cts = new CancellationTokenSource();
|
||||
|
||||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||
await purge.StartAsync(cts.Token);
|
||||
sw.Stop();
|
||||
|
||||
Assert.True(sw.ElapsedMilliseconds < 1000,
|
||||
$"StartAsync blocked for {sw.ElapsedMilliseconds} ms — the initial purge " +
|
||||
"must not run on the host startup thread.");
|
||||
|
||||
// The initial purge still runs on the background scheduler.
|
||||
var deadline = DateTime.UtcNow.AddSeconds(5);
|
||||
while (GetEventCount() != 0 && DateTime.UtcNow < deadline)
|
||||
{
|
||||
await Task.Delay(25);
|
||||
}
|
||||
Assert.Equal(0, GetEventCount());
|
||||
|
||||
await cts.CancelAsync();
|
||||
await purge.StopAsync(CancellationToken.None);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PurgeByStorageCap_ConcurrentWritesDoNotCorruptConnection()
|
||||
{
|
||||
// Regression test for SiteEventLogging-003: purge running on a background
|
||||
// thread while events are recorded on other threads must not throw
|
||||
// "DataReader already open" / "connection busy" from a shared connection.
|
||||
InsertBulkEvents(2000);
|
||||
|
||||
var purge = CreatePurgeService();
|
||||
var totalSize = purge.GetDatabaseSizeBytes();
|
||||
var capOptions = new SiteEventLogOptions
|
||||
{
|
||||
DatabasePath = _dbPath,
|
||||
RetentionDays = 30,
|
||||
MaxStorageMb = (int)Math.Max(1, (totalSize / 2) / (1024 * 1024))
|
||||
};
|
||||
|
||||
var exceptions = new System.Collections.Concurrent.ConcurrentBag<Exception>();
|
||||
// SiteEventLogging-023: must be volatile so the writer threads observe the
|
||||
// main thread's `stop = true` flip after the purge task completes. Without
|
||||
// it, a release-mode JIT is permitted to cache the `stop = false` read in
|
||||
// a register inside the tight `while (!stop)` loop and never see the flip,
|
||||
// causing the writer tasks to hang past xUnit's per-test timeout instead
|
||||
// of asserting `Empty(exceptions)`.
|
||||
_stop = false;
|
||||
|
||||
var purgeTask = Task.Run(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var p = CreatePurgeService(capOptions);
|
||||
for (int i = 0; i < 20; i++) p.RunPurge();
|
||||
}
|
||||
catch (Exception ex) { exceptions.Add(ex); }
|
||||
});
|
||||
|
||||
var writeTasks = Enumerable.Range(0, 4).Select(_ => Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
while (!_stop)
|
||||
{
|
||||
await _eventLogger.LogEventAsync("script", "Info", null, "Concurrent", "Concurrent write");
|
||||
}
|
||||
}
|
||||
catch (Exception ex) { exceptions.Add(ex); }
|
||||
})).ToArray();
|
||||
|
||||
await purgeTask;
|
||||
_stop = true;
|
||||
await Task.WhenAll(writeTasks);
|
||||
|
||||
Assert.Empty(exceptions);
|
||||
}
|
||||
|
||||
// ── SiteEventLogging-019: purge runs only on the active node ──
|
||||
|
||||
[Fact]
|
||||
public void RunPurge_OnStandbyNode_SkipsAllWork()
|
||||
{
|
||||
// SiteEventLogging-019: per design, the daily purge runs on the active
|
||||
// node only. The standby's local SQLite receives no writes, so purging
|
||||
// there is unnecessary; we gate the purge tick on the injected
|
||||
// active-node check and early-exit when it returns false. The row
|
||||
// inserted here is well past retention, so a real purge would delete
|
||||
// it — the standby gate must leave it intact.
|
||||
InsertEventWithTimestamp(DateTimeOffset.UtcNow.AddDays(-31));
|
||||
Assert.Equal(1, GetEventCount());
|
||||
|
||||
var purge = CreatePurgeService(isActiveNode: () => false);
|
||||
purge.RunPurge();
|
||||
|
||||
Assert.Equal(1, GetEventCount());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RunPurge_OnActiveNode_RunsTheRetentionPurge()
|
||||
{
|
||||
// SiteEventLogging-019: when the active-node check returns true the
|
||||
// service runs the purge as before. Pinned alongside the standby case
|
||||
// so a future regression that inverts the gate is caught.
|
||||
InsertEventWithTimestamp(DateTimeOffset.UtcNow.AddDays(-31));
|
||||
InsertEventWithTimestamp(DateTimeOffset.UtcNow);
|
||||
|
||||
var purge = CreatePurgeService(isActiveNode: () => true);
|
||||
purge.RunPurge();
|
||||
|
||||
Assert.Equal(1, GetEventCount());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RunPurge_WithNullCheck_FallsBackToRunning()
|
||||
{
|
||||
// SiteEventLogging-019: when no active-node check is supplied (the
|
||||
// default for non-clustered hosts and pre-existing tests), the service
|
||||
// preserves the pre-fix "run on every tick" behaviour rather than
|
||||
// silently skipping every tick. Backward compatibility guard.
|
||||
InsertEventWithTimestamp(DateTimeOffset.UtcNow.AddDays(-31));
|
||||
|
||||
var purge = CreatePurgeService(isActiveNode: null);
|
||||
purge.RunPurge();
|
||||
|
||||
Assert.Equal(0, GetEventCount());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Messages.RemoteQuery;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests;
|
||||
|
||||
public class EventLogQueryServiceTests : IDisposable
|
||||
{
|
||||
private readonly SiteEventLogger _eventLogger;
|
||||
private readonly EventLogQueryService _queryService;
|
||||
private readonly string _dbPath;
|
||||
|
||||
public EventLogQueryServiceTests()
|
||||
{
|
||||
_dbPath = Path.Combine(Path.GetTempPath(), $"test_query_{Guid.NewGuid()}.db");
|
||||
var options = Options.Create(new SiteEventLogOptions
|
||||
{
|
||||
DatabasePath = _dbPath,
|
||||
QueryPageSize = 500
|
||||
});
|
||||
_eventLogger = new SiteEventLogger(options, NullLogger<SiteEventLogger>.Instance);
|
||||
_queryService = new EventLogQueryService(
|
||||
_eventLogger,
|
||||
options,
|
||||
NullLogger<EventLogQueryService>.Instance);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_eventLogger.Dispose();
|
||||
if (File.Exists(_dbPath)) File.Delete(_dbPath);
|
||||
}
|
||||
|
||||
private async Task SeedEvents()
|
||||
{
|
||||
await _eventLogger.LogEventAsync("script", "Error", "inst-1", "ScriptActor:Monitor", "Script timeout");
|
||||
await _eventLogger.LogEventAsync("alarm", "Warning", "inst-1", "AlarmActor:TempHigh", "Alarm triggered");
|
||||
await _eventLogger.LogEventAsync("deployment", "Info", "inst-2", "DeploymentManager", "Instance deployed");
|
||||
await _eventLogger.LogEventAsync("connection", "Error", null, "DCL:OPC1", "Connection lost");
|
||||
await _eventLogger.LogEventAsync("script", "Info", "inst-2", "ScriptActor:Calculate", "Script completed");
|
||||
}
|
||||
|
||||
private EventLogQueryRequest MakeRequest(
|
||||
string? eventType = null,
|
||||
string? severity = null,
|
||||
string? instanceId = null,
|
||||
string? keyword = null,
|
||||
long? continuationToken = null,
|
||||
int pageSize = 500,
|
||||
DateTimeOffset? from = null,
|
||||
DateTimeOffset? to = null) =>
|
||||
new(
|
||||
CorrelationId: Guid.NewGuid().ToString(),
|
||||
SiteId: "site-1",
|
||||
From: from,
|
||||
To: to,
|
||||
EventType: eventType,
|
||||
Severity: severity,
|
||||
InstanceId: instanceId,
|
||||
KeywordFilter: keyword,
|
||||
ContinuationToken: continuationToken,
|
||||
PageSize: pageSize,
|
||||
Timestamp: DateTimeOffset.UtcNow);
|
||||
|
||||
[Fact]
|
||||
public async Task Query_ReturnsAllEvents_WhenNoFilters()
|
||||
{
|
||||
await SeedEvents();
|
||||
|
||||
var response = _queryService.ExecuteQuery(MakeRequest());
|
||||
|
||||
Assert.True(response.Success);
|
||||
Assert.Equal(5, response.Entries.Count);
|
||||
Assert.False(response.HasMore);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Query_FiltersByEventType()
|
||||
{
|
||||
await SeedEvents();
|
||||
|
||||
var response = _queryService.ExecuteQuery(MakeRequest(eventType: "script"));
|
||||
|
||||
Assert.True(response.Success);
|
||||
Assert.Equal(2, response.Entries.Count);
|
||||
Assert.All(response.Entries, e => Assert.Equal("script", e.EventType));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Query_FiltersBySeverity()
|
||||
{
|
||||
await SeedEvents();
|
||||
|
||||
var response = _queryService.ExecuteQuery(MakeRequest(severity: "Error"));
|
||||
|
||||
Assert.True(response.Success);
|
||||
Assert.Equal(2, response.Entries.Count);
|
||||
Assert.All(response.Entries, e => Assert.Equal("Error", e.Severity));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Query_FiltersByInstanceId()
|
||||
{
|
||||
await SeedEvents();
|
||||
|
||||
var response = _queryService.ExecuteQuery(MakeRequest(instanceId: "inst-1"));
|
||||
|
||||
Assert.True(response.Success);
|
||||
Assert.Equal(2, response.Entries.Count);
|
||||
Assert.All(response.Entries, e => Assert.Equal("inst-1", e.InstanceId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Query_KeywordSearch_MatchesMessage()
|
||||
{
|
||||
await SeedEvents();
|
||||
|
||||
var response = _queryService.ExecuteQuery(MakeRequest(keyword: "timeout"));
|
||||
|
||||
Assert.True(response.Success);
|
||||
Assert.Single(response.Entries);
|
||||
Assert.Contains("timeout", response.Entries[0].Message, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Query_KeywordSearch_MatchesSource()
|
||||
{
|
||||
await SeedEvents();
|
||||
|
||||
var response = _queryService.ExecuteQuery(MakeRequest(keyword: "AlarmActor"));
|
||||
|
||||
Assert.True(response.Success);
|
||||
Assert.Single(response.Entries);
|
||||
Assert.Contains("AlarmActor", response.Entries[0].Source);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Query_CombinesMultipleFilters()
|
||||
{
|
||||
await SeedEvents();
|
||||
|
||||
var response = _queryService.ExecuteQuery(MakeRequest(
|
||||
eventType: "script",
|
||||
severity: "Error",
|
||||
instanceId: "inst-1"));
|
||||
|
||||
Assert.True(response.Success);
|
||||
Assert.Single(response.Entries);
|
||||
Assert.Equal("Script timeout", response.Entries[0].Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Query_Pagination_ReturnsCorrectPageSize()
|
||||
{
|
||||
await SeedEvents();
|
||||
|
||||
var response = _queryService.ExecuteQuery(MakeRequest(pageSize: 2));
|
||||
|
||||
Assert.True(response.Success);
|
||||
Assert.Equal(2, response.Entries.Count);
|
||||
Assert.True(response.HasMore);
|
||||
Assert.NotNull(response.ContinuationToken);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Query_Pagination_ContinuationTokenWorksCorrectly()
|
||||
{
|
||||
await SeedEvents();
|
||||
|
||||
// Get first page
|
||||
var page1 = _queryService.ExecuteQuery(MakeRequest(pageSize: 2));
|
||||
Assert.Equal(2, page1.Entries.Count);
|
||||
Assert.True(page1.HasMore);
|
||||
|
||||
// Get second page using continuation token
|
||||
var page2 = _queryService.ExecuteQuery(MakeRequest(
|
||||
pageSize: 2,
|
||||
continuationToken: page1.ContinuationToken));
|
||||
Assert.Equal(2, page2.Entries.Count);
|
||||
Assert.True(page2.HasMore);
|
||||
|
||||
// Get third page
|
||||
var page3 = _queryService.ExecuteQuery(MakeRequest(
|
||||
pageSize: 2,
|
||||
continuationToken: page2.ContinuationToken));
|
||||
Assert.Single(page3.Entries);
|
||||
Assert.False(page3.HasMore);
|
||||
|
||||
// Verify no overlapping entries
|
||||
var allIds = page1.Entries.Select(e => e.Id)
|
||||
.Concat(page2.Entries.Select(e => e.Id))
|
||||
.Concat(page3.Entries.Select(e => e.Id))
|
||||
.ToList();
|
||||
Assert.Equal(5, allIds.Distinct().Count());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Query_FiltersByTimeRange()
|
||||
{
|
||||
// Insert events at controlled times
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
|
||||
// Insert with a direct SQL to control timestamps
|
||||
InsertEventAt(now.AddHours(-2), "script", "Info", null, "S1", "Old event");
|
||||
InsertEventAt(now.AddMinutes(-30), "script", "Info", null, "S2", "Recent event");
|
||||
InsertEventAt(now, "script", "Info", null, "S3", "Now event");
|
||||
|
||||
var response = _queryService.ExecuteQuery(MakeRequest(
|
||||
from: now.AddHours(-1),
|
||||
to: now.AddMinutes(1)));
|
||||
|
||||
Assert.True(response.Success);
|
||||
Assert.Equal(2, response.Entries.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Query_EmptyResult_WhenNoMatches()
|
||||
{
|
||||
await SeedEvents();
|
||||
|
||||
var response = _queryService.ExecuteQuery(MakeRequest(eventType: "nonexistent"));
|
||||
|
||||
Assert.True(response.Success);
|
||||
Assert.Empty(response.Entries);
|
||||
Assert.False(response.HasMore);
|
||||
Assert.Null(response.ContinuationToken);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Query_ReturnsCorrelationId()
|
||||
{
|
||||
var request = MakeRequest();
|
||||
var response = _queryService.ExecuteQuery(request);
|
||||
|
||||
Assert.Equal(request.CorrelationId, response.CorrelationId);
|
||||
Assert.Equal("site-1", response.SiteId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Query_ReturnsAllEventLogEntryFields()
|
||||
{
|
||||
await _eventLogger.LogEventAsync("script", "Error", "inst-1", "ScriptActor:Run", "Failure", "{\"stack\":\"trace\"}");
|
||||
|
||||
var response = _queryService.ExecuteQuery(MakeRequest());
|
||||
Assert.Single(response.Entries);
|
||||
|
||||
var entry = response.Entries[0];
|
||||
Assert.True(entry.Id > 0);
|
||||
Assert.Equal("script", entry.EventType);
|
||||
Assert.Equal("Error", entry.Severity);
|
||||
Assert.Equal("inst-1", entry.InstanceId);
|
||||
Assert.Equal("ScriptActor:Run", entry.Source);
|
||||
Assert.Equal("Failure", entry.Message);
|
||||
Assert.Equal("{\"stack\":\"trace\"}", entry.Details);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Query_KeywordSearch_TreatsUnderscoreAsLiteral_NotWildcard()
|
||||
{
|
||||
// SiteEventLogging-013: a SQL LIKE '_' matches any single character. A
|
||||
// keyword search for a literal underscore (common in identifiers such as
|
||||
// "store_and_forward") must NOT match strings that merely have any
|
||||
// character in that position.
|
||||
await _eventLogger.LogEventAsync("script", "Info", null, "store_and_forward", "Buffer queued");
|
||||
await _eventLogger.LogEventAsync("script", "Info", null, "storeXandYforward", "Other event");
|
||||
|
||||
var response = _queryService.ExecuteQuery(MakeRequest(keyword: "store_and_forward"));
|
||||
|
||||
Assert.True(response.Success);
|
||||
Assert.Single(response.Entries);
|
||||
Assert.Equal("store_and_forward", response.Entries[0].Source);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Query_KeywordSearch_TreatsPercentAsLiteral_NotWildcard()
|
||||
{
|
||||
// SiteEventLogging-013: a SQL LIKE '%' matches any run of characters. A
|
||||
// keyword search containing a literal '%' must match only the literal.
|
||||
await _eventLogger.LogEventAsync("script", "Warning", null, "ScriptActor:Run", "CPU at 90% utilisation");
|
||||
await _eventLogger.LogEventAsync("script", "Warning", null, "ScriptActor:Run", "CPU at 90 then 0 utilisation");
|
||||
|
||||
var response = _queryService.ExecuteQuery(MakeRequest(keyword: "90% utilisation"));
|
||||
|
||||
Assert.True(response.Success);
|
||||
Assert.Single(response.Entries);
|
||||
Assert.Contains("90% utilisation", response.Entries[0].Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Query_KeywordSearch_StillMatchesPlainSubstring()
|
||||
{
|
||||
// Escaping wildcards must not break ordinary substring search.
|
||||
await SeedEvents();
|
||||
|
||||
var response = _queryService.ExecuteQuery(MakeRequest(keyword: "timeout"));
|
||||
|
||||
Assert.True(response.Success);
|
||||
Assert.Single(response.Entries);
|
||||
}
|
||||
|
||||
private void InsertEventAt(DateTimeOffset timestamp, string eventType, string severity, string? instanceId, string source, string message)
|
||||
{
|
||||
_eventLogger.WithConnection(connection =>
|
||||
{
|
||||
using var cmd = connection.CreateCommand();
|
||||
cmd.CommandText = """
|
||||
INSERT INTO site_events (timestamp, event_type, severity, instance_id, source, message)
|
||||
VALUES ($ts, $et, $sev, $iid, $src, $msg)
|
||||
""";
|
||||
cmd.Parameters.AddWithValue("$ts", timestamp.ToString("o"));
|
||||
cmd.Parameters.AddWithValue("$et", eventType);
|
||||
cmd.Parameters.AddWithValue("$sev", severity);
|
||||
cmd.Parameters.AddWithValue("$iid", (object?)instanceId ?? DBNull.Value);
|
||||
cmd.Parameters.AddWithValue("$src", source);
|
||||
cmd.Parameters.AddWithValue("$msg", message);
|
||||
cmd.ExecuteNonQuery();
|
||||
});
|
||||
}
|
||||
|
||||
// --- SiteEventLogging-017: PageSize hard upper bound ---
|
||||
|
||||
[Fact]
|
||||
public async Task Query_PageSize_IsClampedToMaxQueryPageSize()
|
||||
{
|
||||
// Tighten the cap to make the assertion deterministic without seeding 100k rows.
|
||||
var dbPath = Path.Combine(Path.GetTempPath(), $"test_pagesize_{Guid.NewGuid()}.db");
|
||||
var options = Options.Create(new SiteEventLogOptions
|
||||
{
|
||||
DatabasePath = dbPath,
|
||||
QueryPageSize = 500,
|
||||
MaxQueryPageSize = 3,
|
||||
});
|
||||
using var logger = new SiteEventLogger(options, NullLogger<SiteEventLogger>.Instance);
|
||||
var query = new EventLogQueryService(logger, options, NullLogger<EventLogQueryService>.Instance);
|
||||
|
||||
try
|
||||
{
|
||||
// Seed 5 rows but request PageSize = 100_000 — must be clamped to 3.
|
||||
for (var i = 0; i < 5; i++)
|
||||
await logger.LogEventAsync("script", "Info", null, $"src-{i}", $"msg-{i}");
|
||||
|
||||
var response = query.ExecuteQuery(new EventLogQueryRequest(
|
||||
CorrelationId: Guid.NewGuid().ToString(),
|
||||
SiteId: "site-1",
|
||||
From: null, To: null,
|
||||
EventType: null, Severity: null, InstanceId: null, KeywordFilter: null,
|
||||
ContinuationToken: null,
|
||||
PageSize: 100_000,
|
||||
Timestamp: DateTimeOffset.UtcNow));
|
||||
|
||||
Assert.Equal(3, response.Entries.Count);
|
||||
Assert.True(response.HasMore);
|
||||
}
|
||||
finally
|
||||
{
|
||||
logger.Dispose();
|
||||
if (File.Exists(dbPath)) File.Delete(dbPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Regression tests for SiteEventLogging-006: the schema must index the columns the
|
||||
/// query service filters on so common queries do not full-scan a 1 GB database.
|
||||
/// </summary>
|
||||
public class SchemaIndexTests : IDisposable
|
||||
{
|
||||
private readonly SiteEventLogger _logger;
|
||||
private readonly SqliteConnection _verifyConnection;
|
||||
private readonly string _dbPath;
|
||||
|
||||
public SchemaIndexTests()
|
||||
{
|
||||
_dbPath = Path.Combine(Path.GetTempPath(), $"test_index_{Guid.NewGuid()}.db");
|
||||
var options = Options.Create(new SiteEventLogOptions { DatabasePath = _dbPath });
|
||||
_logger = new SiteEventLogger(options, NullLogger<SiteEventLogger>.Instance);
|
||||
|
||||
_verifyConnection = new SqliteConnection($"Data Source={_dbPath}");
|
||||
_verifyConnection.Open();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_verifyConnection.Dispose();
|
||||
_logger.Dispose();
|
||||
if (File.Exists(_dbPath)) File.Delete(_dbPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Schema_HasIndexOnSeverity()
|
||||
{
|
||||
using var cmd = _verifyConnection.CreateCommand();
|
||||
cmd.CommandText =
|
||||
"SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'site_events'";
|
||||
var indexes = new List<string>();
|
||||
using var reader = cmd.ExecuteReader();
|
||||
while (reader.Read()) indexes.Add(reader.GetString(0));
|
||||
|
||||
Assert.Contains("idx_events_severity", indexes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SeverityFilteredQuery_UsesIndex_NotFullScan()
|
||||
{
|
||||
await _logger.LogEventAsync("script", "Error", null, "S", "boom");
|
||||
await _logger.LogEventAsync("script", "Info", null, "S", "ok");
|
||||
|
||||
using var cmd = _verifyConnection.CreateCommand();
|
||||
cmd.CommandText =
|
||||
"EXPLAIN QUERY PLAN SELECT id FROM site_events WHERE severity = 'Error'";
|
||||
var plan = new System.Text.StringBuilder();
|
||||
using var reader = cmd.ExecuteReader();
|
||||
while (reader.Read())
|
||||
{
|
||||
// The detail column holds the human-readable plan step.
|
||||
plan.Append(reader.GetString(reader.GetOrdinal("detail"))).Append('\n');
|
||||
}
|
||||
|
||||
var planText = plan.ToString();
|
||||
Assert.Contains("idx_events_severity", planText);
|
||||
Assert.DoesNotContain("SCAN site_events", planText);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Regression tests for SiteEventLogging-007: the purge and query services must not
|
||||
/// downcast an injected <see cref="ISiteEventLogger"/> to the concrete type. They now
|
||||
/// depend on the concrete <see cref="SiteEventLogger"/> directly, and DI must resolve
|
||||
/// the recorder, query service, and purge service to a single shared instance.
|
||||
/// </summary>
|
||||
public class ServiceWiringTests : IDisposable
|
||||
{
|
||||
private readonly string _dbPath;
|
||||
private ServiceProvider? _provider;
|
||||
|
||||
public ServiceWiringTests()
|
||||
{
|
||||
_dbPath = Path.Combine(Path.GetTempPath(), $"test_wiring_{Guid.NewGuid()}.db");
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_provider?.Dispose();
|
||||
if (File.Exists(_dbPath)) File.Delete(_dbPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddSiteEventLogging_ResolvesAllServices_SharingOneRecorderInstance()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddLogging();
|
||||
services.Configure<SiteEventLogOptions>(o => o.DatabasePath = _dbPath);
|
||||
services.AddSiteEventLogging();
|
||||
|
||||
_provider = services.BuildServiceProvider();
|
||||
|
||||
var recorderViaInterface = _provider.GetRequiredService<ISiteEventLogger>();
|
||||
var recorderConcrete = _provider.GetRequiredService<SiteEventLogger>();
|
||||
var queryService = _provider.GetRequiredService<IEventLogQueryService>();
|
||||
|
||||
// The interface registration must forward to the concrete singleton — purge
|
||||
// and query depend on that same instance, so all three share one connection.
|
||||
Assert.Same(recorderConcrete, recorderViaInterface);
|
||||
Assert.NotNull(queryService);
|
||||
|
||||
// The hosted purge service must also resolve without an InvalidCastException.
|
||||
var hosted = _provider.GetServices<Microsoft.Extensions.Hosting.IHostedService>();
|
||||
Assert.Contains(hosted, h => h is EventLogPurgeService);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PurgeAndQueryServices_AcceptConcreteRecorder_WithoutDowncast()
|
||||
{
|
||||
// The services no longer take ISiteEventLogger and downcast it; they take the
|
||||
// concrete SiteEventLogger. Constructing them directly must compile and work.
|
||||
var options = Options.Create(new SiteEventLogOptions { DatabasePath = _dbPath });
|
||||
using var loggerFactory = LoggerFactory.Create(_ => { });
|
||||
using var recorder = new SiteEventLogger(
|
||||
options, loggerFactory.CreateLogger<SiteEventLogger>());
|
||||
|
||||
var purge = new EventLogPurgeService(
|
||||
recorder, options, loggerFactory.CreateLogger<EventLogPurgeService>());
|
||||
var query = new EventLogQueryService(
|
||||
recorder, options, loggerFactory.CreateLogger<EventLogQueryService>());
|
||||
|
||||
Assert.NotNull(purge);
|
||||
Assert.NotNull(query);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
using System.Diagnostics;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Regression tests for SiteEventLogging-005 (synchronous I/O on caller thread)
|
||||
/// and SiteEventLogging-008 (write failures silently swallowed).
|
||||
/// </summary>
|
||||
public class SiteEventLoggerAsyncTests : IDisposable
|
||||
{
|
||||
private readonly SiteEventLogger _logger;
|
||||
private readonly string _dbPath;
|
||||
|
||||
public SiteEventLoggerAsyncTests()
|
||||
{
|
||||
_dbPath = Path.Combine(Path.GetTempPath(), $"test_async_{Guid.NewGuid()}.db");
|
||||
var options = Options.Create(new SiteEventLogOptions { DatabasePath = _dbPath });
|
||||
_logger = new SiteEventLogger(options, NullLogger<SiteEventLogger>.Instance);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_logger.Dispose();
|
||||
if (File.Exists(_dbPath)) File.Delete(_dbPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LogEventAsync_DoesNotBlockCaller_WhenWriteIsSlow()
|
||||
{
|
||||
// SiteEventLogging-005: LogEventAsync must not perform the SQLite write
|
||||
// inline on the caller's thread. We hold the recorder busy on a long
|
||||
// database operation from one thread, then time how long it takes the
|
||||
// caller of LogEventAsync to get control back. If recording is offloaded
|
||||
// to a background writer, the caller returns essentially immediately even
|
||||
// though the database is busy. If recording is synchronous (the bug), the
|
||||
// caller blocks on the write lock for the full busy period.
|
||||
var busyStarted = new ManualResetEventSlim(false);
|
||||
var releaseBusy = new ManualResetEventSlim(false);
|
||||
|
||||
var busyThread = new Thread(() =>
|
||||
{
|
||||
_logger.WithConnection(_ =>
|
||||
{
|
||||
busyStarted.Set();
|
||||
// Hold the connection lock until the test releases it.
|
||||
releaseBusy.Wait(TimeSpan.FromSeconds(10));
|
||||
});
|
||||
});
|
||||
busyThread.Start();
|
||||
|
||||
Assert.True(busyStarted.Wait(TimeSpan.FromSeconds(5)), "Busy thread did not start.");
|
||||
|
||||
var sw = Stopwatch.StartNew();
|
||||
var recordTask = _logger.LogEventAsync("script", "Info", null, "Caller", "Should not block");
|
||||
sw.Stop();
|
||||
|
||||
// The CALL must return quickly even though the database is busy for ~1s.
|
||||
Assert.True(sw.ElapsedMilliseconds < 500,
|
||||
$"LogEventAsync blocked the caller for {sw.ElapsedMilliseconds} ms — recording is not offloaded.");
|
||||
|
||||
// Release the busy thread; the record must still complete successfully.
|
||||
releaseBusy.Set();
|
||||
busyThread.Join(TimeSpan.FromSeconds(10));
|
||||
|
||||
await recordTask.WaitAsync(TimeSpan.FromSeconds(10));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LogEventAsync_TaskCompletes_AfterEventIsPersisted()
|
||||
{
|
||||
// Awaiting the returned Task must guarantee the row is durably written.
|
||||
await _logger.LogEventAsync("script", "Info", "inst-1", "Source", "Persisted event");
|
||||
|
||||
var count = _logger.WithConnection(connection =>
|
||||
{
|
||||
using var cmd = connection.CreateCommand();
|
||||
cmd.CommandText = "SELECT COUNT(*) FROM site_events";
|
||||
return (long)cmd.ExecuteScalar()!;
|
||||
});
|
||||
Assert.Equal(1, count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LogEventAsync_FaultsTask_AndCountsFailure_OnWriteError()
|
||||
{
|
||||
// SiteEventLogging-008: a write failure must not be silently swallowed.
|
||||
// The returned Task must fault and the failure counter must increment so
|
||||
// Health Monitoring can surface a logging outage.
|
||||
using var failingConnection = new SqliteConnection("Data Source=:memory:");
|
||||
failingConnection.Open();
|
||||
var options = Options.Create(new SiteEventLogOptions
|
||||
{
|
||||
DatabasePath = Path.Combine(Path.GetTempPath(), $"test_fail_{Guid.NewGuid()}.db")
|
||||
});
|
||||
var logger = new SiteEventLogger(options, NullLogger<SiteEventLogger>.Instance);
|
||||
|
||||
// Drop the table so every write fails with "no such table".
|
||||
logger.WithConnection(connection =>
|
||||
{
|
||||
using var cmd = connection.CreateCommand();
|
||||
cmd.CommandText = "DROP TABLE site_events";
|
||||
cmd.ExecuteNonQuery();
|
||||
});
|
||||
|
||||
await Assert.ThrowsAnyAsync<SqliteException>(() =>
|
||||
logger.LogEventAsync("script", "Error", null, "Source", "Failing write"));
|
||||
|
||||
Assert.True(logger.FailedWriteCount > 0,
|
||||
"FailedWriteCount must increment when an event write fails.");
|
||||
|
||||
logger.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests;
|
||||
|
||||
public class SiteEventLoggerTests : IDisposable
|
||||
{
|
||||
private readonly SiteEventLogger _logger;
|
||||
private readonly SqliteConnection _verifyConnection;
|
||||
private readonly string _dbPath;
|
||||
|
||||
public SiteEventLoggerTests()
|
||||
{
|
||||
_dbPath = Path.Combine(Path.GetTempPath(), $"test_events_{Guid.NewGuid()}.db");
|
||||
var options = Options.Create(new SiteEventLogOptions { DatabasePath = _dbPath });
|
||||
_logger = new SiteEventLogger(options, NullLogger<SiteEventLogger>.Instance);
|
||||
|
||||
// Separate connection for verification queries
|
||||
_verifyConnection = new SqliteConnection($"Data Source={_dbPath}");
|
||||
_verifyConnection.Open();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_verifyConnection.Dispose();
|
||||
_logger.Dispose();
|
||||
if (File.Exists(_dbPath)) File.Delete(_dbPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LogEventAsync_InsertsRecord()
|
||||
{
|
||||
await _logger.LogEventAsync("script", "Error", "inst-1", "ScriptActor:Monitor", "Script failed", "{\"stack\":\"...\"}");
|
||||
|
||||
using var cmd = _verifyConnection.CreateCommand();
|
||||
cmd.CommandText = "SELECT COUNT(*) FROM site_events";
|
||||
var count = (long)cmd.ExecuteScalar()!;
|
||||
Assert.Equal(1, count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LogEventAsync_StoresAllFields()
|
||||
{
|
||||
await _logger.LogEventAsync("alarm", "Warning", "inst-2", "AlarmActor:TempHigh", "Alarm triggered", "{\"value\":95}");
|
||||
|
||||
using var cmd = _verifyConnection.CreateCommand();
|
||||
cmd.CommandText = "SELECT event_type, severity, instance_id, source, message, details FROM site_events LIMIT 1";
|
||||
using var reader = cmd.ExecuteReader();
|
||||
Assert.True(reader.Read());
|
||||
Assert.Equal("alarm", reader.GetString(0));
|
||||
Assert.Equal("Warning", reader.GetString(1));
|
||||
Assert.Equal("inst-2", reader.GetString(2));
|
||||
Assert.Equal("AlarmActor:TempHigh", reader.GetString(3));
|
||||
Assert.Equal("Alarm triggered", reader.GetString(4));
|
||||
Assert.Equal("{\"value\":95}", reader.GetString(5));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LogEventAsync_NullableFieldsAllowed()
|
||||
{
|
||||
await _logger.LogEventAsync("deployment", "Info", null, "DeploymentManager", "Deployed instance");
|
||||
|
||||
using var cmd = _verifyConnection.CreateCommand();
|
||||
cmd.CommandText = "SELECT instance_id, details FROM site_events LIMIT 1";
|
||||
using var reader = cmd.ExecuteReader();
|
||||
Assert.True(reader.Read());
|
||||
Assert.True(reader.IsDBNull(0));
|
||||
Assert.True(reader.IsDBNull(1));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LogEventAsync_StoresIso8601UtcTimestamp()
|
||||
{
|
||||
await _logger.LogEventAsync("connection", "Info", null, "DCL", "Connected");
|
||||
|
||||
using var cmd = _verifyConnection.CreateCommand();
|
||||
cmd.CommandText = "SELECT timestamp FROM site_events LIMIT 1";
|
||||
var ts = (string)cmd.ExecuteScalar()!;
|
||||
var parsed = DateTimeOffset.Parse(ts);
|
||||
Assert.Equal(TimeSpan.Zero, parsed.Offset);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LogEventAsync_ThrowsOnEmptyEventType()
|
||||
{
|
||||
await Assert.ThrowsAsync<ArgumentException>(() =>
|
||||
_logger.LogEventAsync("", "Info", null, "Source", "Message"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LogEventAsync_ThrowsOnEmptySeverity()
|
||||
{
|
||||
await Assert.ThrowsAsync<ArgumentException>(() =>
|
||||
_logger.LogEventAsync("script", "", null, "Source", "Message"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LogEventAsync_ThrowsOnEmptySource()
|
||||
{
|
||||
await Assert.ThrowsAsync<ArgumentException>(() =>
|
||||
_logger.LogEventAsync("script", "Info", null, "", "Message"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LogEventAsync_ThrowsOnEmptyMessage()
|
||||
{
|
||||
await Assert.ThrowsAsync<ArgumentException>(() =>
|
||||
_logger.LogEventAsync("script", "Info", null, "Source", ""));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LogEventAsync_MultipleEvents_AutoIncrementIds()
|
||||
{
|
||||
await _logger.LogEventAsync("script", "Info", null, "S1", "First");
|
||||
await _logger.LogEventAsync("script", "Info", null, "S2", "Second");
|
||||
await _logger.LogEventAsync("script", "Info", null, "S3", "Third");
|
||||
|
||||
using var cmd = _verifyConnection.CreateCommand();
|
||||
cmd.CommandText = "SELECT id FROM site_events ORDER BY id";
|
||||
using var reader = cmd.ExecuteReader();
|
||||
var ids = new List<long>();
|
||||
while (reader.Read()) ids.Add(reader.GetInt64(0));
|
||||
|
||||
Assert.Equal(3, ids.Count);
|
||||
Assert.True(ids[0] < ids[1] && ids[1] < ids[2]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AllEventTypes_Accepted()
|
||||
{
|
||||
var types = new[] { "script", "alarm", "deployment", "connection", "store_and_forward", "instance_lifecycle" };
|
||||
foreach (var t in types)
|
||||
{
|
||||
await _logger.LogEventAsync(t, "Info", null, "Test", $"Event type: {t}");
|
||||
}
|
||||
|
||||
using var cmd = _verifyConnection.CreateCommand();
|
||||
cmd.CommandText = "SELECT COUNT(DISTINCT event_type) FROM site_events";
|
||||
var count = (long)cmd.ExecuteScalar()!;
|
||||
Assert.Equal(6, count);
|
||||
}
|
||||
|
||||
// --- SiteEventLogging-020: severity validation against the closed set ---
|
||||
|
||||
[Theory]
|
||||
[InlineData("info")] // wrong casing
|
||||
[InlineData("warn")] // abbreviation
|
||||
[InlineData("ERROR")] // wrong casing
|
||||
[InlineData("Debug")] // not in set
|
||||
[InlineData("Critical")] // not in set
|
||||
public async Task LogEventAsync_ThrowsOnUnknownSeverity(string badSeverity)
|
||||
{
|
||||
var ex = await Assert.ThrowsAsync<ArgumentException>(
|
||||
() => _logger.LogEventAsync("script", badSeverity, null, "Source", "Message"));
|
||||
Assert.Contains(badSeverity, ex.Message);
|
||||
Assert.Contains("Info, Warning, Error", ex.Message);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Info")]
|
||||
[InlineData("Warning")]
|
||||
[InlineData("Error")]
|
||||
public async Task LogEventAsync_AcceptsAllDocumentedSeverities(string severity)
|
||||
{
|
||||
await _logger.LogEventAsync("script", severity, null, "Source", "Message");
|
||||
|
||||
using var cmd = _verifyConnection.CreateCommand();
|
||||
cmd.CommandText = "SELECT severity FROM site_events";
|
||||
var stored = (string)cmd.ExecuteScalar()!;
|
||||
Assert.Equal(severity, stored);
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Akka.TestKit.Xunit2" />
|
||||
<PackageReference Include="coverlet.collector" />
|
||||
<PackageReference Include="Microsoft.Data.Sqlite" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||
<PackageReference Include="xunit" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../src/ZB.MOM.WW.ScadaBridge.SiteEventLogging/ZB.MOM.WW.ScadaBridge.SiteEventLogging.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
Reference in New Issue
Block a user