Merge branch 'review/wp6' into review/integration
# Conflicts: # docs/requirements/Component-StoreAndForward.md # src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/DeploymentManagerRepository.cs # src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardStorage.cs # src/ZB.MOM.WW.ScadaBridge.Transport/Import/BundleImporter.cs # tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/StoreAndForwardStorageTests.cs
This commit is contained in:
@@ -0,0 +1,138 @@
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZB.MOM.WW.Audit;
|
||||
using ZB.MOM.WW.ScadaBridge.AuditLog.Site;
|
||||
using ZB.MOM.WW.ScadaBridge.AuditLog.Tests.TestSupport;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.AuditLog.Tests.Site;
|
||||
|
||||
/// <summary>
|
||||
/// WP6 task 6.4: connection isolation (AUD-2) and the index shapes behind the reconciliation
|
||||
/// pull (AUD-3) and the retention purge (AUD-4).
|
||||
/// </summary>
|
||||
public class SqliteAuditWriterIndexingTests : IDisposable
|
||||
{
|
||||
private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"audit-idx-{Guid.NewGuid():N}.db");
|
||||
|
||||
/// <summary>Deletes the temp database files.</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
SqliteConnection.ClearAllPools();
|
||||
foreach (var suffix in new[] { "", "-wal", "-shm" })
|
||||
{
|
||||
try { File.Delete(_dbPath + suffix); } catch { /* best-effort */ }
|
||||
}
|
||||
}
|
||||
|
||||
private SqliteAuditWriter CreateWriter() => new(
|
||||
Options.Create(new SqliteAuditWriterOptions { DatabasePath = _dbPath }),
|
||||
NullLogger<SqliteAuditWriter>.Instance,
|
||||
new FakeNodeIdentityProvider());
|
||||
|
||||
private static AuditEvent NewEvent(DateTime occurredAtUtc) => ScadaBridgeAuditEventFactory.Create(
|
||||
eventId: Guid.NewGuid(),
|
||||
occurredAtUtc: occurredAtUtc,
|
||||
channel: AuditChannel.ApiOutbound,
|
||||
kind: AuditKind.ApiCall,
|
||||
status: AuditStatus.Delivered);
|
||||
|
||||
/// <summary>
|
||||
/// AUD-2: an open read transaction on a connection opened like the writer's read connection
|
||||
/// must not stall the batch writer (it did under Cache=Shared: table-level shared-cache locks).
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task OpenReadTransaction_DoesNotStallTheWriter()
|
||||
{
|
||||
await using var writer = CreateWriter();
|
||||
Assert.DoesNotContain("Cache=Shared", writer.ConnectionString, StringComparison.OrdinalIgnoreCase);
|
||||
await writer.WriteAsync(NewEvent(DateTime.UtcNow));
|
||||
|
||||
await using var reader = new SqliteConnection(writer.ConnectionString);
|
||||
await reader.OpenAsync();
|
||||
await using var tx = reader.BeginTransaction(deferred: true);
|
||||
await using (var select = reader.CreateCommand())
|
||||
{
|
||||
select.Transaction = tx;
|
||||
select.CommandText = "SELECT COUNT(*) FROM audit_event";
|
||||
Assert.Equal(1L, (long)(await select.ExecuteScalarAsync())!);
|
||||
}
|
||||
|
||||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||
await writer.WriteAsync(NewEvent(DateTime.UtcNow)).WaitAsync(TimeSpan.FromSeconds(5));
|
||||
sw.Stop();
|
||||
Assert.True(sw.ElapsedMilliseconds < 1000, $"writer stalled {sw.ElapsedMilliseconds} ms behind an open read");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// AUD-3: the pull pages the owed backlog as an ordered range of IX_fwd_owed (no temp sort),
|
||||
/// and the keyset cursor still yields every owed row exactly once, in order.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task ReconciliationPull_IsAnOrderedRangeRead_AndPagesCorrectly()
|
||||
{
|
||||
await using var writer = CreateWriter();
|
||||
var t0 = new DateTime(2026, 11, 1, 0, 0, 0, DateTimeKind.Utc);
|
||||
var ids = new List<Guid>();
|
||||
for (var i = 0; i < 25; i++)
|
||||
{
|
||||
// pairs share an instant so the EventId tiebreak is exercised
|
||||
var e = NewEvent(t0.AddSeconds(i / 2));
|
||||
ids.Add(e.EventId);
|
||||
await writer.WriteAsync(e);
|
||||
}
|
||||
|
||||
var served = new List<Guid>();
|
||||
var since = DateTime.MinValue.ToUniversalTime();
|
||||
string? afterId = null;
|
||||
while (true)
|
||||
{
|
||||
var page = await writer.ReadPendingSinceAsync(since, 4, afterId);
|
||||
if (page.Count == 0) break;
|
||||
served.AddRange(page.Select(p => p.EventId));
|
||||
since = page[^1].OccurredAtUtc.UtcDateTime;
|
||||
afterId = page[^1].EventId.ToString();
|
||||
}
|
||||
Assert.Equal(ids.Count, served.Count);
|
||||
Assert.Equal(served.Count, served.Distinct().Count());
|
||||
|
||||
var plan = await PlanAsync($"""
|
||||
SELECT fs.EventId FROM audit_forward_state fs INDEXED BY IX_fwd_owed
|
||||
JOIN audit_event ae ON ae.EventId = fs.EventId
|
||||
WHERE fs.ForwardState IN ({SqliteAuditWriter.OwedStatesSql}) AND fs.OccurredAtUtc >= '2026'
|
||||
ORDER BY fs.OccurredAtUtc ASC, fs.EventId ASC LIMIT 256
|
||||
""");
|
||||
Assert.Contains(plan, p => p.Contains("IX_fwd_owed"));
|
||||
Assert.DoesNotContain(plan, p => p.Contains("TEMP B-TREE"));
|
||||
}
|
||||
|
||||
/// <summary>AUD-4: the purge page seeks IX_fwd on (state, kind, age) rather than state alone.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task PurgePage_SeeksOnAge()
|
||||
{
|
||||
await using (CreateWriter()) { }
|
||||
var plan = await PlanAsync("""
|
||||
SELECT EventId FROM audit_forward_state
|
||||
WHERE ForwardState IN ('Forwarded', 'Reconciled') AND IsCachedKind IN (0, 1)
|
||||
AND OccurredAtUtc < '2026' LIMIT 5000
|
||||
""");
|
||||
Assert.Contains(plan, p => p.Contains("IX_fwd") && p.Contains("OccurredAtUtc<?"));
|
||||
}
|
||||
|
||||
private async Task<List<string>> PlanAsync(string sql)
|
||||
{
|
||||
await using var connection = new SqliteConnection($"Data Source={_dbPath}");
|
||||
await connection.OpenAsync();
|
||||
await using var cmd = connection.CreateCommand();
|
||||
cmd.CommandText = "EXPLAIN QUERY PLAN " + sql;
|
||||
var plan = new List<string>();
|
||||
await using var r = await cmd.ExecuteReaderAsync();
|
||||
while (await r.ReadAsync()) plan.Add(r.GetString(3));
|
||||
return plan;
|
||||
}
|
||||
}
|
||||
+49
@@ -416,6 +416,55 @@ public class SiteAuditTelemetryActorTests : TestKit
|
||||
Assert.Equal(expectedIds, emittedEventIds);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// AUD-7 (WP6 6.4): a drain resolves its rows' tracking snapshots with ONE batched read of
|
||||
/// the distinct ids when the store offers it, instead of one writer-queue barrier per row.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task CachedDrain_ResolvesTrackingWithOneBatchedRead()
|
||||
{
|
||||
var store = Substitute.For<IOperationTrackingStore, IOperationTrackingBatchReader>();
|
||||
var op = Guid.NewGuid();
|
||||
var other = Guid.NewGuid();
|
||||
var cachedRows = new[]
|
||||
{
|
||||
NewCachedEvent(AuditKind.CachedSubmit, correlationId: op),
|
||||
NewCachedEvent(AuditKind.ApiCallCached, correlationId: op),
|
||||
NewCachedEvent(AuditKind.CachedResolve, correlationId: other),
|
||||
};
|
||||
_queue.ReadPendingAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromResult<IReadOnlyList<AuditEvent>>(Array.Empty<AuditEvent>()));
|
||||
_queue.ReadPendingCachedTelemetryAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(
|
||||
Task.FromResult<IReadOnlyList<AuditEvent>>(cachedRows),
|
||||
Task.FromResult<IReadOnlyList<AuditEvent>>(Array.Empty<AuditEvent>()));
|
||||
((IOperationTrackingBatchReader)store)
|
||||
.GetStatusManyAsync(Arg.Any<IReadOnlyCollection<TrackedOperationId>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(c => Task.FromResult<IReadOnlyDictionary<TrackedOperationId, TrackingStatusSnapshot>>(
|
||||
c.Arg<IReadOnlyCollection<TrackedOperationId>>().ToDictionary(id => id, id => NewSnapshot(id))));
|
||||
_client.IngestCachedTelemetryAsync(Arg.Any<CachedTelemetryBatch>(), Arg.Any<CancellationToken>())
|
||||
.Returns(call =>
|
||||
{
|
||||
var ack = new IngestAck();
|
||||
foreach (var packet in call.Arg<CachedTelemetryBatch>().Packets)
|
||||
ack.AcceptedEventIds.Add(packet.AuditEvent.EventId);
|
||||
return Task.FromResult(ack);
|
||||
});
|
||||
|
||||
Sys.ActorOf(Props.Create(() => new SiteAuditTelemetryActor(
|
||||
_queue, _client, Opts(), NullLogger<SiteAuditTelemetryActor>.Instance,
|
||||
(IOperationTrackingStore?)store)));
|
||||
|
||||
await AwaitAssertAsync(async () =>
|
||||
await _queue.Received(1).MarkForwardedAsync(
|
||||
Arg.Is<IReadOnlyList<Guid>>(g => g.Count == 3), Arg.Any<CancellationToken>()),
|
||||
TimeSpan.FromSeconds(5));
|
||||
await ((IOperationTrackingBatchReader)store).Received(1).GetStatusManyAsync(
|
||||
Arg.Is<IReadOnlyCollection<TrackedOperationId>>(ids => ids.Count == 2), Arg.Any<CancellationToken>());
|
||||
await store.DidNotReceiveWithAnyArgs().GetStatusAsync(default, default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that the tracking-row versions central ACCEPTED are recorded as central acks
|
||||
/// in the tracking store — and only those — so the SiteCalls reconciliation pull stops
|
||||
|
||||
+44
-3
@@ -70,6 +70,46 @@ public class ParkedMessagesMutationRegressionTests : BunitContext
|
||||
await system.Terminate();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// UI-12 (WP6 6.8): a bulk retry authorises once — one site-list read for the whole batch,
|
||||
/// not one per message — and still relays every selected message.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task BulkRetry_AuthorisesOncePerAction_NotPerMessage()
|
||||
{
|
||||
using var system = ActorSystem.Create("parked-bulk-" + Guid.NewGuid().ToString("N"));
|
||||
var dispatched = new ConcurrentQueue<SiteEnvelope>();
|
||||
var comms = new CommunicationService(Options.Create(new CommunicationOptions()), NullLogger<CommunicationService>.Instance);
|
||||
comms.SetCommunicationActor(system.ActorOf(Props.Create(() => new ReplyActor(dispatched, 5))));
|
||||
Services.AddSingleton(comms);
|
||||
var sites = Substitute.For<ISiteRepository>();
|
||||
sites.GetAllSitesAsync(Arg.Any<CancellationToken>()).Returns(new List<Site> { new("Plant A", "plant-a") { Id = 42 } });
|
||||
Services.AddSingleton(sites);
|
||||
Services.AddSingleton<AuthenticationStateProvider>(new MutableAuth("42"));
|
||||
Services.AddScoped<SiteScopeService>();
|
||||
Services.AddAuthorizationCore();
|
||||
Services.AddLogging();
|
||||
var dialog = Substitute.For<IDialogService>();
|
||||
dialog.ConfirmAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<string?>()).Returns(true);
|
||||
Services.AddSingleton(dialog);
|
||||
JSInterop.Mode = JSRuntimeMode.Loose;
|
||||
|
||||
var page = Render<ParkedMessages>();
|
||||
await page.Find("select").ChangeAsync(new() { Value = "plant-a" });
|
||||
page.WaitForAssertion(() => Assert.Equal(5, page.FindAll("tr.parked-row").Count));
|
||||
await page.Find("input[aria-label='Select all']").ChangeAsync(new() { Value = true });
|
||||
page.WaitForAssertion(() => Assert.Contains("Retry selected", page.Markup));
|
||||
sites.ClearReceivedCalls();
|
||||
|
||||
await page.FindAll("button").Single(b => b.TextContent.Trim() == "Retry selected").ClickAsync(new());
|
||||
|
||||
page.WaitForAssertion(() => Assert.Equal(5, dispatched.Count(e => e.Message is ParkedMessageRetryRequest)));
|
||||
// One read for the bulk authorisation (the page refresh afterwards adds none of its own here).
|
||||
await sites.Received(1).GetAllSitesAsync(Arg.Any<CancellationToken>());
|
||||
await system.Terminate();
|
||||
}
|
||||
|
||||
private sealed class MutableAuth(string siteId) : AuthenticationStateProvider
|
||||
{
|
||||
/// <summary>Gets or sets the site identifier carried in the user's site-scope claim.</summary>
|
||||
@@ -87,14 +127,15 @@ public class ParkedMessagesMutationRegressionTests : BunitContext
|
||||
{
|
||||
/// <summary>Initializes the actor with the queue that records relayed retry requests.</summary>
|
||||
/// <param name="dispatched">The queue that receives each relayed retry envelope.</param>
|
||||
public ReplyActor(ConcurrentQueue<SiteEnvelope> dispatched)
|
||||
/// <param name="rows">How many parked rows the query reply carries.</param>
|
||||
public ReplyActor(ConcurrentQueue<SiteEnvelope> dispatched, int rows = 1)
|
||||
{
|
||||
Receive<SiteEnvelope>(envelope =>
|
||||
{
|
||||
if (envelope.Message is ParkedMessageQueryRequest query)
|
||||
Sender.Tell(new ParkedMessageQueryResponse(query.CorrelationId, envelope.SiteId,
|
||||
new[] { new ParkedMessageEntry("parked-message-1", "ERP", "Send", "Offline", 2, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow) },
|
||||
1, 1, 25, true, null, DateTimeOffset.UtcNow));
|
||||
Enumerable.Range(1, rows).Select(i => new ParkedMessageEntry($"parked-message-{i}", "ERP", "Send", "Offline", 2, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow)).ToArray(),
|
||||
rows, 1, 25, true, null, DateTimeOffset.UtcNow));
|
||||
else if (envelope.Message is ParkedMessageRetryRequest retry)
|
||||
{
|
||||
dispatched.Enqueue(envelope);
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
using ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Deployment;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Deployment;
|
||||
|
||||
/// <summary>UI-6 (WP6 6.8): Save overrides sends only the values that changed.</summary>
|
||||
public class OverrideSaveDiffTests
|
||||
{
|
||||
/// <summary>Only new or changed values are saved; an unchanged override (of ~260) is not.</summary>
|
||||
[Fact]
|
||||
public void Changed_ReturnsOnlyNewOrDifferentValues()
|
||||
{
|
||||
var existing = Enumerable.Range(0, 260).ToDictionary(
|
||||
i => $"A{i}", i => new InstanceAttributeOverride($"A{i}") { OverrideValue = i.ToString() });
|
||||
var working = existing.ToDictionary(kv => kv.Key, kv => kv.Value.OverrideValue);
|
||||
working["A7"] = "changed";
|
||||
working["New"] = "1";
|
||||
|
||||
var changed = OverrideSaveDiff.Changed(working, existing);
|
||||
|
||||
Assert.Equal(new[] { ("A7", (string?)"changed"), ("New", (string?)"1") },
|
||||
changed.OrderBy(c => c.Name).ToArray());
|
||||
}
|
||||
}
|
||||
+40
-1
@@ -29,15 +29,54 @@ public class SandboxWorkerIsolationTests
|
||||
{
|
||||
await allEntered.Task.WaitAsync(TimeSpan.FromSeconds(8));
|
||||
var fifthStarted = false;
|
||||
// UI-13: the queue wait is charged to the start-up ceiling; shrink it so the
|
||||
// queued fifth run still gives up quickly here.
|
||||
SandboxWorkerProtocol.StartupCeiling = TimeSpan.Zero;
|
||||
var fifth = await SandboxWorkerProtocol.RunCoreAsync(new SandboxRunRequest("return 1;", null, 1),
|
||||
services, catalog, CancellationToken.None, _ => fifthStarted = true);
|
||||
Assert.Equal(SandboxErrorKind.Timeout, fifth.ErrorKind);
|
||||
Assert.False(fifthStarted);
|
||||
}
|
||||
finally { release.TrySetResult(new ExternalCallResult(true, "null", null)); }
|
||||
finally
|
||||
{
|
||||
SandboxWorkerProtocol.StartupCeiling = TimeSpan.FromSeconds(30);
|
||||
release.TrySetResult(new ExternalCallResult(true, "null", null));
|
||||
}
|
||||
foreach (var result in await Task.WhenAll(workers)) Assert.True(result.Success, result.Error);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// UI-13 (WP6 6.8): the script deadline starts when the worker reports user code is about to
|
||||
/// run. A 1-second run queued behind four busy Test Runs for ~2 s (plus a cold worker start)
|
||||
/// used to report "exceeded the 1-second sandbox timeout"; it now succeeds.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task QueuedAndColdStartTime_IsNotChargedToTheScriptBudget()
|
||||
{
|
||||
var allEntered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var release = new TaskCompletionSource<ExternalCallResult>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var count = 0;
|
||||
var external = Substitute.For<IExternalSystemClient>();
|
||||
external.CallAsync("probe", "blocked", Arg.Any<IReadOnlyDictionary<string, object?>?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => { if (Interlocked.Increment(ref count) == 4) allEntered.TrySetResult(); return release.Task; });
|
||||
using var services = new ServiceCollection().AddSingleton(external).BuildServiceProvider();
|
||||
var catalog = Substitute.For<ISharedScriptCatalog>();
|
||||
var busy = Enumerable.Range(0, 4).Select(_ => SandboxWorkerProtocol.RunAsync(new SandboxRunRequest(
|
||||
"await ExternalSystem.Call(\"probe\", \"blocked\"); return 42;", null, 10), services, catalog, CancellationToken.None)).ToArray();
|
||||
await allEntered.Task.WaitAsync(TimeSpan.FromSeconds(10));
|
||||
|
||||
var queued = SandboxWorkerProtocol.RunAsync(new SandboxRunRequest("return 7;", null, 1),
|
||||
services, catalog, CancellationToken.None);
|
||||
await Task.Delay(TimeSpan.FromSeconds(2)); // queued longer than its whole 1 s script budget
|
||||
release.TrySetResult(new ExternalCallResult(true, "null", null));
|
||||
|
||||
var result = await queued.WaitAsync(TimeSpan.FromSeconds(30));
|
||||
Assert.True(result.Success, result.Error);
|
||||
Assert.Equal("7", result.ReturnValueJson);
|
||||
foreach (var r in await Task.WhenAll(busy)) Assert.True(r.Success, r.Error);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that an uncooperative broker still has its child killed at the deadline and keeps the lifetime until the broker completes.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
|
||||
+43
@@ -65,6 +65,49 @@ public class SitePairChannelProviderFailbackTests
|
||||
Assert.Equal(TimeSpan.FromSeconds(4), provider.GetFailbackBackoff(Site));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// COMM-8 (WP6 6.10): due failback probes run concurrently (bounded), so one slow NodeA per
|
||||
/// site no longer serialises the pass — 16 sites with a 400 ms probe each finish in well
|
||||
/// under the 6.4 s a serial pass takes, and never more than the bound run at once.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task DueProbes_RunConcurrently_UpToTheBound()
|
||||
{
|
||||
var inFlight = 0;
|
||||
var maxInFlight = 0;
|
||||
using var provider = Build(async (_, ct) =>
|
||||
{
|
||||
var now = Interlocked.Increment(ref inFlight);
|
||||
int seen;
|
||||
while ((seen = Volatile.Read(ref maxInFlight)) < now && Interlocked.CompareExchange(ref maxInFlight, now, seen) != seen) { }
|
||||
await Task.Delay(400, ct);
|
||||
Interlocked.Decrement(ref inFlight);
|
||||
return false;
|
||||
});
|
||||
const int sites = 16;
|
||||
for (var i = 0; i < sites; i++)
|
||||
{
|
||||
var site = $"site-{i}";
|
||||
provider.UpdateSite(site, $"http://localhost:{16000 + i}", $"http://localhost:{17000 + i}");
|
||||
GrpcChannel? first = null;
|
||||
await provider.ExecuteAsync(site, (channel, _) =>
|
||||
{
|
||||
if (first is null) { first = channel; throw GrpcRetrySafety.NotDispatched("not ready"); }
|
||||
return Task.FromResult(1);
|
||||
}, CancellationToken.None);
|
||||
Assert.False(provider.IsOnPreferredNode(site));
|
||||
}
|
||||
|
||||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||
await provider.RunDueFailbackProbesAsync(DateTime.UtcNow.AddMinutes(1), CancellationToken.None);
|
||||
sw.Stop();
|
||||
|
||||
Assert.True(sw.Elapsed < TimeSpan.FromSeconds(3), $"probe pass took {sw.ElapsedMilliseconds} ms");
|
||||
Assert.True(maxInFlight > 1, "probes did not run concurrently");
|
||||
Assert.True(maxInFlight <= SitePairChannelProvider.FailbackProbeParallelism);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that a successful real call on the preferred node after failback resets the backoff.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
|
||||
+1
@@ -186,6 +186,7 @@ public class AuditLogEntityTypeConfigurationTests : IDisposable
|
||||
var expected = new[]
|
||||
{
|
||||
"IX_AuditLog_Actor_Occurred",
|
||||
"IX_AuditLog_Channel_Occurred", // AuditLogChannelOccurredIndex (AUD-5)
|
||||
"IX_AuditLog_Channel_Status_Occurred",
|
||||
"IX_AuditLog_CorrelationId",
|
||||
"IX_AuditLog_Execution",
|
||||
|
||||
+5
-1
@@ -70,7 +70,11 @@ public sealed class FlipAuditLogClusteredKeyMigrationTests : IClassFixture<MsSql
|
||||
Assert.True(indexes["PK_AuditLog"].Clustered);
|
||||
Assert.Equal("EventId, OccurredAtUtc", indexes["UX_AuditLog_EventId_Occurred"].Keys);
|
||||
Assert.True(indexes["UX_AuditLog_EventId_Occurred"].Unique);
|
||||
Assert.Equal(NonClusteredIndexes.Length + 2, indexes.Count);
|
||||
// + PK + UX + IX_AuditLog_Channel_Occurred (AuditLogChannelOccurredIndex, AUD-5 — added
|
||||
// after the flip, so the pre-flip round-trip shape below does not carry it).
|
||||
Assert.Equal(NonClusteredIndexes.Length + 3, indexes.Count);
|
||||
Assert.Equal("Category, OccurredAtUtc", indexes["IX_AuditLog_Channel_Occurred"].Keys);
|
||||
Assert.False(indexes["IX_AuditLog_Channel_Occurred"].Clustered);
|
||||
Assert.All(indexes.Values, i => Assert.Equal("ps_AuditLog_Month", i.DataSpace));
|
||||
AssertNonClusteredIndexes(indexes, withChainIndexes: false);
|
||||
Assert.Equal(ExpectedGrants, await ReadGrantsAsync());
|
||||
|
||||
+22
@@ -84,6 +84,28 @@ public class PendingDeploymentRepositoryTests : IDisposable
|
||||
Assert.Equal(instanceId, current.InstanceId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DEP-5 (WP6 6.6): a prior pending row that the TTL purge (or reconciliation) deleted
|
||||
/// after this context loaded it must not fail the superseding stage with a concurrency
|
||||
/// error — the supersede is a set-based delete, not tracked key stubs.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task AddPendingDeployment_PriorRowDeletedConcurrently_DoesNotThrow()
|
||||
{
|
||||
var instanceId = await SeedInstanceAsync("Inst-race");
|
||||
await _repository.AddPendingDeploymentAsync(NewPending("depA", instanceId, "{}"));
|
||||
await _repository.SaveChangesAsync(); // depA is now tracked by this context
|
||||
|
||||
await _repository.AddPendingDeploymentAsync(NewPending("depB", instanceId, "{}"));
|
||||
// Between the supersede and the save, the purge actor removes depA on its own
|
||||
// connection/context (ExecuteDelete of expired rows).
|
||||
await _context.Database.ExecuteSqlRawAsync("DELETE FROM PendingDeployments WHERE DeploymentId = 'depA'");
|
||||
await _repository.SaveChangesAsync();
|
||||
|
||||
Assert.NotNull(await _repository.GetPendingDeploymentByIdAsync("depB"));
|
||||
}
|
||||
|
||||
/// <summary>Verifies that pending deployments for different instances coexist.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
|
||||
+23
@@ -24,10 +24,31 @@ public class AuditPurgeBudgetTests
|
||||
Assert.Equal(ConnectionState.Closed, connection.State);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// AUD-5 (WP6 6.5): the channel is bound as varchar(32) to match the Category column — an
|
||||
/// nvarchar parameter makes SQL Server convert the column under a SQL collation and rules
|
||||
/// out a seek on IX_AuditLog_Channel_Occurred.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task ChannelParameter_IsBoundAsVarchar32()
|
||||
{
|
||||
using var connection = new BackloggedConnection();
|
||||
await using var context = new ScadaBridgeDbContext(new DbContextOptionsBuilder<ScadaBridgeDbContext>()
|
||||
.UseSqlServer(connection).Options);
|
||||
await new AuditLogRepository(context).PurgeChannelOlderThanAsync(
|
||||
"ScriptTrace", DateTime.UtcNow, batchSize: 3, maxRows: 3);
|
||||
var channel = Assert.Single(connection.ChannelParameters);
|
||||
Assert.Equal(SqlDbType.VarChar, channel.Type);
|
||||
Assert.Equal(32, channel.Size);
|
||||
}
|
||||
|
||||
private sealed class BackloggedConnection : DbConnection
|
||||
{
|
||||
/// <summary>Gets the batch sizes requested by the purge, in order.</summary>
|
||||
public List<int> RequestedBatches { get; } = new();
|
||||
/// <summary>Gets the SQL type and size of each bound <c>@channel</c> parameter, in order.</summary>
|
||||
public List<(SqlDbType Type, int Size)> ChannelParameters { get; } = new();
|
||||
private ConnectionState _state;
|
||||
/// <inheritdoc />
|
||||
[AllowNull] public override string ConnectionString { get; set; } = "Server=localhost;Database=test";
|
||||
@@ -81,6 +102,8 @@ public class AuditPurgeBudgetTests
|
||||
throw new InvalidOperationException("Purge did not yield despite exhausting its row budget.");
|
||||
var requested = (int)_parameters.Parameters["@batch"].Value;
|
||||
owner.RequestedBatches.Add(requested);
|
||||
var channel = _parameters.Parameters["@channel"];
|
||||
owner.ChannelParameters.Add((channel.SqlDbType, channel.Size));
|
||||
return requested;
|
||||
}
|
||||
/// <inheritdoc />
|
||||
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Templates;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Repositories;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Repositories;
|
||||
|
||||
/// <summary>
|
||||
/// WP6 task 6.6 (DEP-4, DEP-6, TPL-4): the targeted, untracked repository reads that replace
|
||||
/// whole-graph or per-row tracked loads, asserted against real SQL on SQLite.
|
||||
/// </summary>
|
||||
public class TargetedLoadRepositoryTests : IDisposable
|
||||
{
|
||||
private readonly ScadaBridgeDbContext _context;
|
||||
private readonly TemplateEngineRepository _templates;
|
||||
private readonly DeploymentManagerRepository _deployments;
|
||||
|
||||
/// <summary>Initializes the test class with an in-memory context and the repositories.</summary>
|
||||
public TargetedLoadRepositoryTests()
|
||||
{
|
||||
_context = SqliteTestHelper.CreateInMemoryContext();
|
||||
_templates = new TemplateEngineRepository(_context, new TemplateGraphWatermark());
|
||||
_deployments = new DeploymentManagerRepository(_context);
|
||||
}
|
||||
|
||||
/// <summary>Releases the resources held by this test class.</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_context.Database.CloseConnection();
|
||||
_context.Dispose();
|
||||
}
|
||||
|
||||
private async Task<(int SiteId, int TemplateId, List<int> InstanceIds)> SeedAsync(int instances)
|
||||
{
|
||||
var site = new Site("Site", "S1");
|
||||
var template = new Template("T");
|
||||
_context.Sites.Add(site);
|
||||
_context.Templates.Add(template);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
var ids = new List<int>();
|
||||
for (var i = 0; i < instances; i++)
|
||||
{
|
||||
var instance = new Instance($"I{i:0000}") { SiteId = site.Id, TemplateId = template.Id };
|
||||
instance.AttributeOverrides.Add(new InstanceAttributeOverride("A") { OverrideValue = i.ToString() });
|
||||
_context.Instances.Add(instance);
|
||||
}
|
||||
await _context.SaveChangesAsync();
|
||||
ids.AddRange(await _context.Instances.Select(i => i.Id).ToListAsync());
|
||||
_context.ChangeTracker.Clear();
|
||||
return (site.Id, template.Id, ids);
|
||||
}
|
||||
|
||||
/// <summary>DEP-4: the batched loader returns every requested instance with its children, untracked, across chunks.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task GetInstancesByIdsUntracked_LoadsChildren_AcrossChunks_WithoutTracking()
|
||||
{
|
||||
var (_, _, ids) = await SeedAsync(620);
|
||||
|
||||
var loaded = await _templates.GetInstancesByIdsUntrackedAsync(ids.Append(ids[0]).Append(-1).ToList());
|
||||
|
||||
Assert.Equal(ids.Count, loaded.Count);
|
||||
Assert.All(loaded, i => Assert.Single(i.AttributeOverrides));
|
||||
Assert.Empty(_context.ChangeTracker.Entries());
|
||||
}
|
||||
|
||||
/// <summary>TPL-4: the shallow site read carries no child collections and tracks nothing.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task GetInstancesBySiteIdShallow_IsUntracked_AndCarriesNoChildren()
|
||||
{
|
||||
var (siteId, _, ids) = await SeedAsync(3);
|
||||
|
||||
var shallow = await _templates.GetInstancesBySiteIdShallowAsync(siteId);
|
||||
|
||||
Assert.Equal(ids.Count, shallow.Count);
|
||||
Assert.All(shallow, i => Assert.Empty(i.AttributeOverrides));
|
||||
Assert.Empty(_context.ChangeTracker.Entries());
|
||||
}
|
||||
|
||||
/// <summary>TPL-4: the folder-move collision check is a case-insensitive sibling-name query that excludes the moved template.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task TemplateNameExistsInFolder_IsCaseInsensitive_AndExcludesSelf()
|
||||
{
|
||||
var folder = new TemplateFolder("F");
|
||||
_context.TemplateFolders.Add(folder);
|
||||
await _context.SaveChangesAsync();
|
||||
var inFolder = new Template("Pump") { FolderId = folder.Id };
|
||||
var atRoot = new Template("Valve");
|
||||
_context.Templates.AddRange(inFolder, atRoot);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
Assert.True(await _templates.TemplateNameExistsInFolderAsync(folder.Id, "PUMP", atRoot.Id));
|
||||
Assert.False(await _templates.TemplateNameExistsInFolderAsync(folder.Id, "Pump", inFolder.Id));
|
||||
Assert.False(await _templates.TemplateNameExistsInFolderAsync(null, "Pump", atRoot.Id));
|
||||
Assert.True(await _templates.TemplateNameExistsInFolderAsync(null, "valve", inFolder.Id));
|
||||
}
|
||||
|
||||
/// <summary>DEP-6: the state read sees a state committed after this context loaded (and tracks) the instance.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task GetInstanceState_BypassesIdentityResolution()
|
||||
{
|
||||
var (_, _, ids) = await SeedAsync(1);
|
||||
var tracked = await _context.Instances.SingleAsync(i => i.Id == ids[0]);
|
||||
Assert.Equal(InstanceState.NotDeployed, tracked.State);
|
||||
|
||||
await _context.Database.ExecuteSqlRawAsync(
|
||||
"UPDATE Instances SET State = {0} WHERE Id = {1}", InstanceState.Disabled.ToString(), ids[0]);
|
||||
|
||||
Assert.Equal(InstanceState.NotDeployed, (await _context.Instances.SingleAsync(i => i.Id == ids[0])).State);
|
||||
Assert.Equal(InstanceState.Disabled, await _deployments.GetInstanceStateAsync(ids[0]));
|
||||
Assert.Null(await _deployments.GetInstanceStateAsync(-1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using Google.Protobuf.Collections;
|
||||
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Protocol;
|
||||
using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Adapters;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests;
|
||||
|
||||
/// <summary>DCL-10 (WP6 6.10): MxGateway quality mapping is table-driven and allocation-free.</summary>
|
||||
public class MxGatewayQualityMapTests
|
||||
{
|
||||
/// <summary>The quality byte maps exactly as the former range switch did.</summary>
|
||||
[Theory]
|
||||
[InlineData(-5, QualityCode.Bad)]
|
||||
[InlineData(0, QualityCode.Bad)]
|
||||
[InlineData(63, QualityCode.Bad)]
|
||||
[InlineData(64, QualityCode.Uncertain)]
|
||||
[InlineData(191, QualityCode.Uncertain)]
|
||||
[InlineData(192, QualityCode.Good)]
|
||||
[InlineData(255, QualityCode.Good)]
|
||||
[InlineData(1000, QualityCode.Good)]
|
||||
public void QualityByte_Maps(int quality, QualityCode expected)
|
||||
=> Assert.Equal(expected, RealMxGatewayClient.MapQuality(quality, new RepeatedField<MxStatusProxy>()));
|
||||
|
||||
/// <summary>A failing status is authoritative Bad; a success status defers to the byte.</summary>
|
||||
[Fact]
|
||||
public void FailingStatus_IsBad()
|
||||
{
|
||||
var ok = new RepeatedField<MxStatusProxy> { new MxStatusProxy { Category = MxStatusCategory.Ok } };
|
||||
var failing = new RepeatedField<MxStatusProxy> { new MxStatusProxy { Category = MxStatusCategory.Ok }, new MxStatusProxy() };
|
||||
Assert.Equal(QualityCode.Good, RealMxGatewayClient.MapQuality(192, ok));
|
||||
Assert.Equal(QualityCode.Bad, RealMxGatewayClient.MapQuality(192, failing));
|
||||
}
|
||||
|
||||
/// <summary>The per-event path allocates nothing (the old Any() boxed the enumerator per call).</summary>
|
||||
[Fact]
|
||||
public void MapQuality_DoesNotAllocate()
|
||||
{
|
||||
var statuses = new RepeatedField<MxStatusProxy> { new MxStatusProxy { Category = MxStatusCategory.Ok } };
|
||||
RealMxGatewayClient.MapQuality(192, statuses); // warm
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
for (var i = 0; i < 10_000; i++)
|
||||
RealMxGatewayClient.MapQuality(192, statuses);
|
||||
Assert.Equal(0, GC.GetAllocatedBytesForCurrentThread() - before);
|
||||
}
|
||||
}
|
||||
@@ -397,6 +397,62 @@ public class DeploySiteAsyncTests : TestKit
|
||||
Arg.Is<DeploymentRecord>(r => r.InstanceId == 2 || r.InstanceId == 4), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DEP-6 (WP6 6.6): an instance Disabled by another request AFTER the batch loaded its
|
||||
/// candidates is caught by the fresh, lock-held state read — skipped, never flattened,
|
||||
/// sent or finalised as enabled.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task DeploySiteAsync_InstanceDisabledAfterTheBatchStarted_IsSkippedNotReEnabled()
|
||||
{
|
||||
ArrangeInstances(3);
|
||||
// The candidate list (and the tracked entity Prepare re-reads) still says NotDeployed,
|
||||
// but the database already holds the operator's Disable.
|
||||
_repo.GetInstanceStateAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ci => ci.ArgAt<int>(0) == 2 ? InstanceState.Disabled : InstanceState.NotDeployed);
|
||||
|
||||
var commActor = Sys.ActorOf(Props.Create(() =>
|
||||
new ThrottledSiteActor(new ConcurrencyTracker(), slowInstanceName: null, slowDelay: TimeSpan.Zero)));
|
||||
|
||||
var result = await CreateService(commActor, maxParallelism: 2).DeploySiteAsync(SiteId, "admin");
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(2, result.Value.SuccessCount);
|
||||
Assert.DoesNotContain(result.Value.InstanceResults, r => r.UniqueName == "Inst-02");
|
||||
var skipped = Assert.Single(result.Value.SkippedInstances!);
|
||||
Assert.Equal("Inst-02", skipped.UniqueName);
|
||||
await _pipeline.DidNotReceive().FlattenAndValidateAsync(
|
||||
2, Arg.Any<CancellationToken>(), Arg.Any<bool>(), Arg.Any<FlattenSession?>());
|
||||
await _repo.DidNotReceive().AddDeploymentRecordAsync(
|
||||
Arg.Is<DeploymentRecord>(r => r.InstanceId == 2), Arg.Any<CancellationToken>());
|
||||
Assert.False(_lockManager.IsLocked("Inst-02"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DEP-5 (WP6 6.6): a failed staging save drops its pending changes from the shared
|
||||
/// context, so the instances staged after it are not poisoned by the same failure.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task DeploySiteAsync_FailedStagingWrite_DetachesItsPendingChanges()
|
||||
{
|
||||
ArrangeInstances(3);
|
||||
_repo.AddPendingDeploymentAsync(
|
||||
Arg.Is<PendingDeployment>(p => p.InstanceId == 1), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromException(new InvalidOperationException("staging save lost a race")));
|
||||
|
||||
var commActor = Sys.ActorOf(Props.Create(() =>
|
||||
new ThrottledSiteActor(new ConcurrencyTracker(), slowInstanceName: null, slowDelay: TimeSpan.Zero)));
|
||||
|
||||
var result = await CreateService(commActor, maxParallelism: 1).DeploySiteAsync(SiteId, "admin");
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Equal(2, result.Value.SuccessCount);
|
||||
Assert.Equal("Inst-01", Assert.Single(result.Value.InstanceResults, r => !r.Success).UniqueName);
|
||||
_repo.Received().DetachPendingChanges();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Phase 1 is serial, so an unreachable site used to cost the batch one
|
||||
/// full 30-second <c>QueryTimeout</c> PER INSTANCE before a single deploy was
|
||||
|
||||
+30
-1
@@ -1,3 +1,4 @@
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
@@ -35,6 +36,9 @@ public class DeploymentServiceStalenessTests
|
||||
private readonly RevisionHashService _hasher = new();
|
||||
private readonly DeploymentService _service;
|
||||
|
||||
/// <summary>DEP-4: the batched untracked instance loader the staleness read preloads from.</summary>
|
||||
private readonly ITemplateEngineRepository _templateRepo = Substitute.For<ITemplateEngineRepository>();
|
||||
|
||||
/// <summary>The single session every flatten in a batch must share.</summary>
|
||||
private readonly FlattenSession _session = new(new TemplateGraphWatermark());
|
||||
|
||||
@@ -61,7 +65,7 @@ public class DeploymentServiceStalenessTests
|
||||
_service = new DeploymentService(
|
||||
_repo,
|
||||
siteRepo,
|
||||
Substitute.For<ITemplateEngineRepository>(),
|
||||
_templateRepo,
|
||||
_pipeline,
|
||||
new CommunicationService(
|
||||
Options.Create(new CommunicationOptions()),
|
||||
@@ -182,6 +186,31 @@ public class DeploymentServiceStalenessTests
|
||||
await _pipeline.Received(1).ComputeRevisionHashAsync(3, _session, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DEP-4 (WP6 6.6): the deployed instances are bulk-loaded untracked (one call for the
|
||||
/// batch) and handed to the shared session, instead of one tracked load per flatten.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task GetInstanceStalenessAsync_BulkPreloadsDeployedInstancesUntracked()
|
||||
{
|
||||
var config = ScalarConfig("5");
|
||||
var hash = _hasher.ComputeHash(config);
|
||||
ArrangeDeployedHashes((1, hash), (2, hash));
|
||||
ArrangeFlatten(1, config, hash);
|
||||
ArrangeFlatten(2, config, hash);
|
||||
_templateRepo.GetInstancesByIdsUntrackedAsync(Arg.Any<IReadOnlyCollection<int>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(ci => (IReadOnlyList<Instance>)ci.ArgAt<IReadOnlyCollection<int>>(0)
|
||||
.Select(id => new Instance($"I{id}") { Id = id }).ToList());
|
||||
|
||||
await _service.GetInstanceStalenessAsync([1, 2, 3]); // 3 is not deployed: never loaded
|
||||
|
||||
await _templateRepo.Received(1).GetInstancesByIdsUntrackedAsync(
|
||||
Arg.Is<IReadOnlyCollection<int>>(ids => ids.Order().SequenceEqual(new[] { 1, 2 })),
|
||||
Arg.Any<CancellationToken>());
|
||||
Assert.NotNull(_session.TakePreloadedInstance(1));
|
||||
}
|
||||
|
||||
/// <summary>Verifies that a matching hash is reported as not stale and no snapshot is read.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
|
||||
@@ -97,6 +97,30 @@ public class FlattenSessionCacheTests
|
||||
await _siteRepo.Received(1).GetDataConnectionsBySiteIdAsync(SiteId, Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DEP-4 (WP6 6.6): an instance bulk-preloaded into the session is flattened from the
|
||||
/// session — no per-instance tracked repository load — and is consumed once taken.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task PreloadedInstances_AreFlattenedWithoutPerInstanceLoads()
|
||||
{
|
||||
const int instanceCount = 5;
|
||||
ArrangeSharedChain(instanceCount);
|
||||
|
||||
var session = _sut.CreateSession();
|
||||
session.PreloadInstances(Enumerable.Range(1, instanceCount)
|
||||
.Select(i => new Instance($"Tank-{i:00}") { Id = i, TemplateId = TemplateId, SiteId = SiteId }));
|
||||
for (var i = 1; i <= instanceCount; i++)
|
||||
{
|
||||
var result = await _sut.ComputeRevisionHashAsync(i, session, CancellationToken.None);
|
||||
Assert.True(result.IsSuccess);
|
||||
}
|
||||
|
||||
await _templateRepo.DidNotReceive().GetInstanceByIdAsync(Arg.Any<int>(), Arg.Any<CancellationToken>());
|
||||
Assert.Null(session.TakePreloadedInstance(1));
|
||||
}
|
||||
|
||||
/// <summary>Verifies that no shared session, every instance reloads the chain.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
using NSubstitute;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Schemas;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
|
||||
using ZB.MOM.WW.ScadaBridge.InboundAPI.Middleware;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.InboundAPI.Tests;
|
||||
|
||||
/// <summary>WP6 task 6.9: INB-2 (library snapshot), INB-3 (scratch sizing), INB-4 (time-based replay prune).</summary>
|
||||
public class Wp6InboundPerfTests
|
||||
{
|
||||
private const string RefDefinition = """[{"name":"p","type":"Object","$ref":"lib:Shape"}]""";
|
||||
|
||||
/// <summary>INB-2: repeated $ref resolution within the TTL reads the library once; after the TTL it reloads.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task SchemaLibrary_IsReadOncePerTtl_NotPerResolution()
|
||||
{
|
||||
var repo = Substitute.For<ISharedSchemaRepository>();
|
||||
repo.ListAsync(Arg.Any<CancellationToken>()).Returns(new List<SharedSchema> { new() { Name = "Shape", SchemaJson = "{\"type\":\"object\"}" } });
|
||||
var clock = new ManualClock(DateTimeOffset.UtcNow);
|
||||
var cache = new SharedSchemaLibraryCache(TimeSpan.FromSeconds(5), clock);
|
||||
|
||||
for (var i = 0; i < 100; i++)
|
||||
{
|
||||
var resolve = await SchemaRefResolver.BuildAsync(repo, [RefDefinition], cache);
|
||||
Assert.NotNull(resolve!("Shape"));
|
||||
}
|
||||
await repo.Received(1).ListAsync(Arg.Any<CancellationToken>());
|
||||
|
||||
clock.Advance(TimeSpan.FromSeconds(6));
|
||||
await SchemaRefResolver.BuildAsync(repo, [RefDefinition], cache);
|
||||
await repo.Received(2).ListAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>INB-3: the audit scratch buffer is sized to the declared body, not the 1 MiB cap.</summary>
|
||||
[Theory]
|
||||
[InlineData(200L, 1_048_576, 200)]
|
||||
[InlineData(null, 1_048_576, 1_048_576)]
|
||||
[InlineData(5_000_000L, 1_048_576, 1_048_576)]
|
||||
[InlineData(-1L, 1_048_576, 1_048_576)]
|
||||
public void AuditScratch_IsSizedToContentLength(long? contentLength, int cap, int expected)
|
||||
=> Assert.Equal(expected, AuditWriteMiddleware.ExpectedCaptureBytes(contentLength, cap));
|
||||
|
||||
/// <summary>INB-4: past the prune threshold, a burst of relayed proofs triggers at most one full scan per interval.</summary>
|
||||
[Fact]
|
||||
public void ReplayCache_PrunesOnATimeBasis_NotPerRequest()
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||
for (var i = 0; i < 5000; i++)
|
||||
Assert.True(RelayProvenance.TryRecordProof(Guid.NewGuid(), "n", now));
|
||||
|
||||
var before = Volatile.Read(ref RelayProvenance.PruneScans);
|
||||
for (var i = 0; i < 2000; i++)
|
||||
Assert.True(RelayProvenance.TryRecordProof(Guid.NewGuid(), "n", now));
|
||||
|
||||
Assert.True(Volatile.Read(ref RelayProvenance.PruneScans) - before <= 1,
|
||||
"the replay cache was scanned more than once inside one prune interval");
|
||||
// ...and a replay is still refused.
|
||||
var id = Guid.NewGuid();
|
||||
Assert.True(RelayProvenance.TryRecordProof(id, "x", now));
|
||||
Assert.False(RelayProvenance.TryRecordProof(id, "x", now));
|
||||
}
|
||||
|
||||
private sealed class ManualClock(DateTimeOffset start) : TimeProvider
|
||||
{
|
||||
private DateTimeOffset _now = start;
|
||||
/// <summary>Advances the clock.</summary>
|
||||
/// <param name="by">The amount to advance.</param>
|
||||
public void Advance(TimeSpan by) => _now += by;
|
||||
/// <inheritdoc />
|
||||
public override DateTimeOffset GetUtcNow() => _now;
|
||||
}
|
||||
}
|
||||
@@ -1192,6 +1192,9 @@ public class ManagementActorTests : TestKit, IDisposable
|
||||
// (review 2026-10-21 04/P6, 08/P1).
|
||||
_templateRepo.GetAllTemplatesForAnalysisAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Template> { template });
|
||||
// TPL-4: SetAlarmOverride reads the template's analysis closure, not the whole table.
|
||||
_templateRepo.GetTemplateAnalysisClosureAsync(template.Id, Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Template> { template });
|
||||
_templateRepo.GetAlarmOverrideAsync(10, "HighTemp", Arg.Any<CancellationToken>())
|
||||
.Returns((InstanceAlarmOverride?)null);
|
||||
|
||||
@@ -4071,14 +4074,15 @@ public class ManagementActorTests : TestKit, IDisposable
|
||||
|
||||
// The repository fan-out HandleExportBundle does at the top of its body.
|
||||
// Tests that only exercise role gating still need these resolved.
|
||||
_templateRepo.GetAllTemplatesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Template>());
|
||||
// MGT-5: template and instance names resolve against narrow projections.
|
||||
_templateRepo.GetTemplateStubsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Commons.Types.Templates.TemplateStub>());
|
||||
_templateRepo.GetAllSharedScriptsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Commons.Entities.Scripts.SharedScript>());
|
||||
// Export now also fans out to instances (template repo) and sites
|
||||
// (site repo) for the site/instance-scoped selection.
|
||||
_templateRepo.GetAllInstancesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Instance>());
|
||||
_templateRepo.GetInstanceNamesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<(int, string)>());
|
||||
|
||||
var siteRepo = Substitute.For<ISiteRepository>();
|
||||
siteRepo.GetAllSitesAsync(Arg.Any<CancellationToken>())
|
||||
@@ -4234,8 +4238,8 @@ public class ManagementActorTests : TestKit, IDisposable
|
||||
// curated message must surface verbatim to the caller.
|
||||
AddBundleSubstitutes();
|
||||
// No templates in the repo; the export selection names one anyway.
|
||||
_templateRepo.GetAllTemplatesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Template>());
|
||||
_templateRepo.GetTemplateStubsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Commons.Types.Templates.TemplateStub>());
|
||||
|
||||
var cmd = new ExportBundleCommand(
|
||||
All: false,
|
||||
@@ -4260,6 +4264,36 @@ public class ManagementActorTests : TestKit, IDisposable
|
||||
Assert.Contains("DoesNotExist", response.Error);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// MGT-5 (WP6 6.7): export resolves names against the (Id, Name) projections and never
|
||||
/// materialises the full template graph or every instance with its child collections.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void ExportBundleCommand_ResolvesNamesFromProjections_NotFullGraphs()
|
||||
{
|
||||
var (exporter, _) = AddBundleSubstitutes();
|
||||
_templateRepo.GetTemplateStubsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Commons.Types.Templates.TemplateStub> { new(7, "PumpBase", null, null, false, null) });
|
||||
Commons.Types.Transport.ExportSelection? captured = null;
|
||||
exporter.ExportAsync(
|
||||
Arg.Do<Commons.Types.Transport.ExportSelection>(s => captured = s),
|
||||
Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string?>(),
|
||||
Arg.Any<CancellationToken>())
|
||||
.Returns(_ => Task.FromResult<Stream>(new MemoryStream(new byte[] { 1 })));
|
||||
|
||||
var cmd = new ExportBundleCommand(
|
||||
All: false, TemplateNames: new[] { "PumpBase" }, SharedScriptNames: null,
|
||||
ExternalSystemNames: null, DatabaseConnectionNames: null,
|
||||
NotificationListNames: null, SmtpConfigurationNames: null, ApiMethodNames: null,
|
||||
IncludeDependencies: false, Passphrase: null, SourceEnvironment: "test-env");
|
||||
CreateActor().Tell(Envelope(cmd, "Designer"));
|
||||
|
||||
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
|
||||
Assert.Equal(new[] { 7 }, captured!.TemplateIds);
|
||||
_templateRepo.DidNotReceive().GetAllTemplatesAsync(Arg.Any<CancellationToken>());
|
||||
_templateRepo.DidNotReceive().GetAllInstancesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>Verifies that export bundle command, when with site and instance names, resolves to ids.</summary>
|
||||
[Fact]
|
||||
public void ExportBundleCommand_WithSiteAndInstanceNames_ResolvesToIds()
|
||||
@@ -4277,12 +4311,8 @@ public class ManagementActorTests : TestKit, IDisposable
|
||||
new("North Plant", "NORTH-01") { Id = 11 },
|
||||
new("East Plant", "EAST-02") { Id = 22 },
|
||||
});
|
||||
_templateRepo.GetAllInstancesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Instance>
|
||||
{
|
||||
new("NORTH-01.Pump1") { Id = 101, SiteId = 11, TemplateId = 1 },
|
||||
new("NORTH-01.Pump2") { Id = 102, SiteId = 11, TemplateId = 1 },
|
||||
});
|
||||
_templateRepo.GetInstanceNamesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<(int, string)> { (101, "NORTH-01.Pump1"), (102, "NORTH-01.Pump2") });
|
||||
|
||||
Commons.Types.Transport.ExportSelection? captured = null;
|
||||
exporter.ExportAsync(
|
||||
@@ -4328,12 +4358,8 @@ public class ManagementActorTests : TestKit, IDisposable
|
||||
new("North Plant", "NORTH-01") { Id = 11 },
|
||||
new("East Plant", "EAST-02") { Id = 22 },
|
||||
});
|
||||
_templateRepo.GetAllInstancesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<Instance>
|
||||
{
|
||||
new("NORTH-01.Pump1") { Id = 101, SiteId = 11, TemplateId = 1 },
|
||||
new("EAST-02.Pump9") { Id = 909, SiteId = 22, TemplateId = 1 },
|
||||
});
|
||||
_templateRepo.GetInstanceNamesAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(new List<(int, string)> { (101, "NORTH-01.Pump1"), (909, "EAST-02.Pump9") });
|
||||
|
||||
Commons.Types.Transport.ExportSelection? captured = null;
|
||||
exporter.ExportAsync(
|
||||
|
||||
@@ -84,6 +84,7 @@ public class SchemaIndexTests : IDisposable
|
||||
[Theory]
|
||||
[InlineData("severity", "idx_events_severity_timestamp")]
|
||||
[InlineData("event_type", "idx_events_type_timestamp")]
|
||||
[InlineData("instance_id", "idx_events_instance_timestamp")] // SEL-1 (WP6 6.5)
|
||||
public void EqualityFilteredPage_ReadsInTimestampOrder_WithoutSortingEveryMatch(string column, string expectedIndex)
|
||||
{
|
||||
foreach (var window in new[] { "", "AND timestamp >= '2026-01-01' " })
|
||||
@@ -135,7 +136,7 @@ public class SchemaIndexTests : IDisposable
|
||||
while (reader.Read()) indexes.Add(reader.GetString(0));
|
||||
|
||||
Assert.Equal(
|
||||
["idx_events_instance", "idx_events_severity_timestamp", "idx_events_timestamp", "idx_events_type_timestamp"],
|
||||
["idx_events_instance_timestamp", "idx_events_severity_timestamp", "idx_events_timestamp", "idx_events_type_timestamp"],
|
||||
indexes);
|
||||
using var count = connection.CreateCommand();
|
||||
count.CommandText = "SELECT COUNT(*) FROM site_events INDEXED BY idx_events_severity_timestamp WHERE severity = 'Info'";
|
||||
|
||||
@@ -121,7 +121,7 @@ public class SiteEventLogSchemaTests
|
||||
while (reader.Read()) indexes.Add(reader.GetString(0));
|
||||
|
||||
Assert.Equal(
|
||||
["idx_events_instance", "idx_events_severity_timestamp", "idx_events_timestamp", "idx_events_type_timestamp"],
|
||||
["idx_events_instance_timestamp", "idx_events_severity_timestamp", "idx_events_timestamp", "idx_events_type_timestamp"],
|
||||
indexes);
|
||||
}
|
||||
|
||||
|
||||
+4
-4
@@ -75,7 +75,7 @@ public class SiteEventsSchemaCalibrationTests
|
||||
Assert.True(
|
||||
indexes.SequenceEqual(
|
||||
[
|
||||
"idx_events_instance",
|
||||
"idx_events_instance_timestamp",
|
||||
"idx_events_severity_timestamp",
|
||||
"idx_events_timestamp",
|
||||
"idx_events_type_timestamp",
|
||||
@@ -89,14 +89,14 @@ public class SiteEventsSchemaCalibrationTests
|
||||
/// <param name="expectedColumns">The columns the index is expected to cover, comma-separated, in key order.</param>
|
||||
[Theory]
|
||||
[InlineData("idx_events_timestamp", "timestamp")]
|
||||
[InlineData("idx_events_instance", "instance_id")]
|
||||
[InlineData("idx_events_instance_timestamp", "instance_id,timestamp")]
|
||||
[InlineData("idx_events_type_timestamp", "event_type,timestamp")]
|
||||
[InlineData("idx_events_severity_timestamp", "severity,timestamp")]
|
||||
public void EachIndex_CoversExactlyTheColumnsTheSamplerSums(string indexName, string expectedColumns)
|
||||
{
|
||||
// The sampler's indexed_bytes expression sums 3 * octet_length(timestamp) +
|
||||
// The sampler's indexed_bytes expression sums 4 * octet_length(timestamp) +
|
||||
// octet_length(event_type) + octet_length(severity) + octet_length(instance_id):
|
||||
// timestamp once for its own index and once for each of the two composites (#123).
|
||||
// timestamp once for its own index and once for each of the three composites (#123, SEL-1).
|
||||
// Widening or re-pointing an index changes the real entry width without changing
|
||||
// what is sampled.
|
||||
using var connection = OpenWithSchema();
|
||||
|
||||
+45
@@ -116,6 +116,51 @@ public class InstanceActorChildRoutingTests : TestKit, IDisposable
|
||||
Assert.Single(actor.AllChangeChildren);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SRT-7 (WP6 6.2): an Expression script/alarm whose reads are literal keys is routed only to
|
||||
/// those attributes, so a change to any other attribute no longer reaches it.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void LiteralKeyExpression_RoutesOnlyToTheAttributesItReads()
|
||||
{
|
||||
var config = new FlattenedConfiguration
|
||||
{
|
||||
InstanceUniqueName = "ExprKeyPump",
|
||||
Attributes =
|
||||
[
|
||||
new ResolvedAttribute { CanonicalName = "A", Value = "1", DataType = "Double" },
|
||||
new ResolvedAttribute { CanonicalName = "B", Value = "2", DataType = "Double" },
|
||||
new ResolvedAttribute { CanonicalName = "C", Value = "3", DataType = "Double" }
|
||||
],
|
||||
Scripts =
|
||||
[
|
||||
new ResolvedScript
|
||||
{
|
||||
CanonicalName = "S_expr", Code = "return 3;",
|
||||
TriggerType = "Expression",
|
||||
TriggerConfiguration = "{\"expression\":\"(double)Attributes[\\\"A\\\"] > (double)Attributes[\\\"B\\\"]\"}"
|
||||
}
|
||||
],
|
||||
Alarms =
|
||||
[
|
||||
new ResolvedAlarm
|
||||
{
|
||||
CanonicalName = "ExprAlarm",
|
||||
TriggerType = "Expression",
|
||||
TriggerConfiguration = "{\"expression\":\"(double)Attributes[\\\"B\\\"] > 1\"}",
|
||||
PriorityLevel = 1
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
var actor = BuildInstance(config);
|
||||
|
||||
Assert.Empty(actor.AllChangeChildren);
|
||||
Assert.Single(actor.ChildrenByMonitoredAttribute["A"]); // the script
|
||||
Assert.Equal(2, actor.ChildrenByMonitoredAttribute["B"].Count); // script + alarm
|
||||
Assert.False(actor.ChildrenByMonitoredAttribute.ContainsKey("C"));
|
||||
}
|
||||
|
||||
/// <summary>Verifies that a monitored-attribute alarm routes only to its attribute while an expression alarm routes to all changes.</summary>
|
||||
[Fact]
|
||||
public void MonitoredAttributeAlarm_RoutesToItsAttribute_ExpressionAlarm_RoutesToAllChanges()
|
||||
|
||||
@@ -265,6 +265,75 @@ public class NativeAlarmActorTests : TestKit, IDisposable
|
||||
Assert.Contains(rows, r => r.ConditionJson.Contains("49"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SRT-5 (WP6 6.1): a persist flush that is waiting on the shared LocalDb write lock must not
|
||||
/// park the actor's dispatcher thread. While another connection holds the write lock the
|
||||
/// actor keeps processing transitions, and the blocked batch still commits (in order) once
|
||||
/// the lock is released.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Flush_BlockedOnWriteLock_DoesNotBlockTheActorThread()
|
||||
{
|
||||
var instance = CreateTestProbe();
|
||||
var dcl = CreateTestProbe();
|
||||
var actor = SpawnWithFlush(instance.Ref, dcl.Ref, TimeSpan.FromMilliseconds(50));
|
||||
dcl.ExpectMsg<SubscribeAlarmsRequest>();
|
||||
|
||||
await using var locker = _localDb.Db.CreateConnection();
|
||||
await using (var begin = locker.CreateCommand())
|
||||
{
|
||||
begin.CommandText = "BEGIN IMMEDIATE;";
|
||||
await begin.ExecuteNonQueryAsync();
|
||||
}
|
||||
|
||||
var t0 = DateTimeOffset.UtcNow;
|
||||
DeliverLiveTransition(actor, "ref-a", severity: 800, t0);
|
||||
instance.ExpectMsg<AlarmStateChanged>();
|
||||
await Task.Delay(300); // the 50 ms flush has started and is waiting on the lock
|
||||
|
||||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||
DeliverLiveTransition(actor, "ref-b", severity: 801, t0.AddMilliseconds(1));
|
||||
instance.ExpectMsg<AlarmStateChanged>(TimeSpan.FromMilliseconds(500));
|
||||
sw.Stop();
|
||||
|
||||
await using (var rollback = locker.CreateCommand())
|
||||
{
|
||||
rollback.CommandText = "ROLLBACK;";
|
||||
await rollback.ExecuteNonQueryAsync();
|
||||
}
|
||||
|
||||
Assert.True(sw.ElapsedMilliseconds < 500, $"actor stalled {sw.ElapsedMilliseconds} ms behind a blocked flush");
|
||||
await AwaitAssertAsync(async () =>
|
||||
Assert.Equal(2, (await _storage.GetNativeAlarmsAsync("inst", Source().CanonicalName)).Count),
|
||||
TimeSpan.FromSeconds(5));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SRT-14 (WP6 6.2): cap eviction picks the oldest conditions with a bounded heap; the
|
||||
/// selection (and its oldest-first order) matches the full sort it replaced.
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData(1)]
|
||||
[InlineData(3)]
|
||||
[InlineData(10)]
|
||||
public void SelectOldest_MatchesAFullSort(int count)
|
||||
{
|
||||
var rng = new Random(42);
|
||||
var t0 = DateTimeOffset.UtcNow;
|
||||
var alarms = Enumerable.Range(0, 1001)
|
||||
.Select(i => Transition($"ref-{i}", AlarmTransitionKind.Raise,
|
||||
new AlarmConditionState(true, false, null, AlarmShelveState.Unshelved, false, 800),
|
||||
t0.AddMilliseconds(rng.Next(0, 1_000_000))))
|
||||
.ToList();
|
||||
|
||||
var expected = alarms.OrderBy(a => a.TransitionTime).Take(count).Select(a => a.TransitionTime).ToList();
|
||||
var actual = NativeAlarmActor.SelectOldest(alarms, count).Select(a => a.TransitionTime).ToList();
|
||||
|
||||
Assert.Equal(expected, actual);
|
||||
Assert.Empty(NativeAlarmActor.SelectOldest(alarms, 0));
|
||||
}
|
||||
|
||||
/// <summary>A snapshot swap that drops several conditions deletes their rows via the batched flush, and a delete cancels a pending upsert (review 2026-10-21 01/SR-P2).</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
using ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests.Scripts;
|
||||
|
||||
/// <summary>
|
||||
/// SRT-7 (WP6 6.2): an Expression trigger is routed by the literal attribute keys it reads,
|
||||
/// and falls back to all-changes whenever those keys cannot be pinned down.
|
||||
/// </summary>
|
||||
public class TriggerExpressionKeysTests
|
||||
{
|
||||
/// <summary>Literal root and child reads are extracted as canonical keys.</summary>
|
||||
[Theory]
|
||||
[InlineData("(double)Attributes[\"Temp\"] > 50", new[] { "Temp" })]
|
||||
[InlineData("(double)Attributes[\"A\"] > (double)Attributes[\"B\"] && Attributes[\"A\"] != null", new[] { "A", "B" })]
|
||||
[InlineData("(double)Children[\"Pump1\"].Attributes[\"Speed\"] > 10", new[] { "Pump1.Speed" })]
|
||||
[InlineData("Attributes[\"Mode\"] as string == \"Auto\" || (bool)Children[\"V\"].Attributes[\"Open\"]", new[] { "Mode", "V.Open" })]
|
||||
public void LiteralReads_AreExtracted(string expression, string[] expected)
|
||||
{
|
||||
Assert.True(TriggerExpressionKeys.TryExtract(expression, out var keys));
|
||||
Assert.Equal(expected, keys);
|
||||
}
|
||||
|
||||
/// <summary>Anything that is not a recognised literal read falls back to all-changes.</summary>
|
||||
[Theory]
|
||||
[InlineData("true")] // no attribute read (may depend on the clock)
|
||||
[InlineData("DateTime.UtcNow.Second == 0")]
|
||||
[InlineData("Attributes[\"A\" + \"B\"] != null")] // non-literal key
|
||||
[InlineData("Attributes[name] != null")]
|
||||
[InlineData("Parent != null")]
|
||||
[InlineData("Children[\"P\"].Attributes[k] != null")] // non-literal child key
|
||||
[InlineData("Children[c].Attributes[\"S\"] != null")] // non-literal child name
|
||||
[InlineData("((Func<object>)(() => Attributes))() != null")] // alias of the global
|
||||
[InlineData("(double)Attributes[\"A\"] > 1 && this.Attributes[\"B\"] != null")]
|
||||
[InlineData("(double)Attributes[\"A\" > 1")] // parse error
|
||||
[InlineData("")]
|
||||
public void UnpinnableReads_FallBack(string expression)
|
||||
{
|
||||
Assert.False(TriggerExpressionKeys.TryExtract(expression, out _));
|
||||
}
|
||||
|
||||
/// <summary>Routing decisions for Expression scripts and alarms use the extracted keys.</summary>
|
||||
[Fact]
|
||||
public void ExpressionRouting_UsesKeysOrFallsBack()
|
||||
{
|
||||
var keyed = TriggerRouting.ForScript("Expression", "{\"expression\":\"(double)Attributes[\\\"A\\\"] > 1\"}");
|
||||
Assert.Equal(TriggerRoutingKind.MonitoredAttributes, keyed.Kind);
|
||||
Assert.Equal(new[] { "A" }, keyed.MonitoredAttributeSet);
|
||||
|
||||
var alarm = TriggerRouting.ForAlarm("Expression", "{\"expression\":\"Children[\\\"P\\\"].Attributes[\\\"X\\\"] != null\"}");
|
||||
Assert.Equal(TriggerRoutingKind.MonitoredAttributes, alarm.Kind);
|
||||
Assert.Equal(new[] { "P.X" }, alarm.MonitoredAttributeSet);
|
||||
|
||||
Assert.Equal(TriggerRoutingKind.AllChanges, TriggerRouting.ForScript("Expression", "{\"expression\":\"true\"}").Kind);
|
||||
Assert.Equal(TriggerRoutingKind.AllChanges, TriggerRouting.ForAlarm("Expression", "not json").Kind);
|
||||
}
|
||||
}
|
||||
@@ -282,6 +282,33 @@ public class OperationTrackingStoreTests : IDisposable
|
||||
Assert.Equal("node-a", snapshot!.SourceNode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// AUD-7 (WP6 6.4): the batched read returns every recorded id (read-your-writes, across
|
||||
/// more ids than one IN-chunk) and omits ids with no row.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task GetStatusManyAsync_ReturnsRecordedIds_AndOmitsMissing()
|
||||
{
|
||||
var (store, _) = CreateStore(nameof(GetStatusManyAsync_ReturnsRecordedIds_AndOmitsMissing));
|
||||
await using var _store = store;
|
||||
|
||||
var recorded = Enumerable.Range(0, 1203).Select(_ => TrackedOperationId.New()).ToList();
|
||||
foreach (var id in recorded)
|
||||
{
|
||||
await store.RecordEnqueueAsync(id, kind: nameof(AuditKind.ApiCallCached), targetSummary: "ERP.GetOrder",
|
||||
sourceInstanceId: null, sourceScript: null, sourceNode: "node-a");
|
||||
}
|
||||
var missing = TrackedOperationId.New();
|
||||
|
||||
var found = await store.GetStatusManyAsync(recorded.Append(missing).Append(recorded[0]).ToList());
|
||||
|
||||
Assert.Equal(recorded.Count, found.Count);
|
||||
Assert.All(recorded, id => Assert.Equal(id, found[id].Id));
|
||||
Assert.False(found.ContainsKey(missing));
|
||||
Assert.Empty(await store.GetStatusManyAsync(Array.Empty<TrackedOperationId>()));
|
||||
}
|
||||
|
||||
/// <summary>Verifies that recording an enqueue persists a null source node.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
|
||||
@@ -912,6 +912,36 @@ public class StoreAndForwardStorageTests : IAsyncLifetime, IDisposable
|
||||
Assert.Equal(new[] { "a", "b" }, ids);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SF-3 (WP6 6.3): the sweep ranks lanes over the covering lane index (no payload read, no
|
||||
/// sort for the window) and joins back only the chosen page by primary key.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task GetMessagesForRetry_RanksOverTheCoveringLaneIndex()
|
||||
{
|
||||
await using var connection = _localDb.Db.CreateConnection();
|
||||
await using var cmd = connection.CreateCommand();
|
||||
cmd.CommandText = @"EXPLAIN QUERY PLAN
|
||||
SELECT id, created_at, rowid,
|
||||
ROW_NUMBER() OVER lane AS lane_rank,
|
||||
SUM(CASE WHEN (last_attempt_at_ms IS NULL OR retry_interval_ms = 0
|
||||
OR (1 - last_attempt_at_ms) >= retry_interval_ms) THEN 0 ELSE 1 END) OVER lane AS blocked_by
|
||||
FROM sf_messages
|
||||
WHERE status = 0
|
||||
WINDOW lane AS (PARTITION BY category, target ORDER BY created_at ASC, rowid ASC
|
||||
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)";
|
||||
var plan = new List<string>();
|
||||
await using (var reader = await cmd.ExecuteReaderAsync())
|
||||
while (await reader.ReadAsync())
|
||||
plan.Add(reader.GetString(3));
|
||||
|
||||
Assert.Contains(plan, p => p.Contains("COVERING INDEX idx_sf_messages_lane"));
|
||||
// The SF-1 rowid tie-break is the one key past the index order: SQLite may sort only
|
||||
// rows tied on (category, target, created_at) — "FOR LAST TERM" — never the backlog.
|
||||
Assert.DoesNotContain(plan, p => p.Contains("TEMP B-TREE") && !p.Contains("LAST TERM"));
|
||||
}
|
||||
|
||||
// ReplaceAll_SwapsTheEntireBuffer_Atomically was DELETED with ReplaceAllAsync in
|
||||
// LocalDb Phase 2, and deliberately not replaced. It asserted a destructive
|
||||
// delete-all-then-insert-all, which was the standby's anti-entropy apply: a resync
|
||||
|
||||
@@ -36,6 +36,16 @@ internal static class AnalysisClosureMock
|
||||
},
|
||||
ct);
|
||||
});
|
||||
|
||||
// TPL-4: the folder-move collision check is a (FolderId, Name) existence query now;
|
||||
// answer it from the same seeded graph.
|
||||
repoMock
|
||||
.Setup(r => r.TemplateNameExistsInFolderAsync(
|
||||
It.IsAny<int?>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<CancellationToken>()))
|
||||
.Returns(async (int? folderId, string name, int excludeId, CancellationToken ct) =>
|
||||
((await repoMock.Object.GetAllTemplatesForAnalysisAsync(ct)) ?? Array.Empty<Template>())
|
||||
.Any(t => t.Id != excludeId && t.FolderId == folderId
|
||||
&& string.Equals(t.Name, name, StringComparison.OrdinalIgnoreCase)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -73,7 +73,7 @@ public class AreaServiceTests
|
||||
{
|
||||
_repoMock.Setup(r => r.GetAreaByIdAsync(1, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new Area("Building A") { Id = 1, SiteId = 1 });
|
||||
_repoMock.Setup(r => r.GetInstancesBySiteIdAsync(1, It.IsAny<CancellationToken>()))
|
||||
_repoMock.Setup(r => r.GetInstancesBySiteIdShallowAsync(1, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new List<Instance>
|
||||
{
|
||||
new("Inst1") { Id = 1, AreaId = 1, SiteId = 1 }
|
||||
@@ -94,7 +94,7 @@ public class AreaServiceTests
|
||||
{
|
||||
_repoMock.Setup(r => r.GetAreaByIdAsync(1, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new Area("Parent") { Id = 1, SiteId = 1 });
|
||||
_repoMock.Setup(r => r.GetInstancesBySiteIdAsync(1, It.IsAny<CancellationToken>()))
|
||||
_repoMock.Setup(r => r.GetInstancesBySiteIdShallowAsync(1, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new List<Instance>());
|
||||
_repoMock.Setup(r => r.GetAreasBySiteIdAsync(1, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new List<Area>
|
||||
@@ -116,7 +116,7 @@ public class AreaServiceTests
|
||||
{
|
||||
_repoMock.Setup(r => r.GetAreaByIdAsync(1, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new Area("Empty") { Id = 1, SiteId = 1 });
|
||||
_repoMock.Setup(r => r.GetInstancesBySiteIdAsync(1, It.IsAny<CancellationToken>()))
|
||||
_repoMock.Setup(r => r.GetInstancesBySiteIdShallowAsync(1, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new List<Instance>());
|
||||
_repoMock.Setup(r => r.GetAreasBySiteIdAsync(1, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new List<Area> { new("Empty") { Id = 1, SiteId = 1 } });
|
||||
@@ -312,7 +312,7 @@ public class AreaServiceTests
|
||||
new("Mid") { Id = 2, SiteId = 1, ParentAreaId = 1 },
|
||||
new("Leaf") { Id = 3, SiteId = 1, ParentAreaId = 2 }
|
||||
});
|
||||
_repoMock.Setup(r => r.GetInstancesBySiteIdAsync(1, It.IsAny<CancellationToken>()))
|
||||
_repoMock.Setup(r => r.GetInstancesBySiteIdShallowAsync(1, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new List<Instance>
|
||||
{
|
||||
new("DeepInstance") { Id = 10, AreaId = 3, SiteId = 1 }
|
||||
|
||||
@@ -18,6 +18,7 @@ public class InstanceServiceTests
|
||||
/// <summary>Initializes the test with a mocked repository and audit service and the service under test.</summary>
|
||||
public InstanceServiceTests()
|
||||
{
|
||||
_repoMock.ServeClosureFromFullGraph(); // TPL-4: SetAlarmOverride reads the analysis closure
|
||||
_sut = new InstanceService(_repoMock.Object, _auditMock.Object);
|
||||
}
|
||||
|
||||
@@ -108,6 +109,32 @@ public class InstanceServiceTests
|
||||
Assert.Contains("does not exist", result.Error);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// UI-6 (WP6 6.8): re-saving an override with its current value writes nothing and adds no
|
||||
/// UpdateOverride audit row.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task SetAttributeOverride_UnchangedValue_SkipsTheWriteAndTheAuditRow()
|
||||
{
|
||||
var instance = new Instance("Inst1") { Id = 1, TemplateId = 1 };
|
||||
var existing = new InstanceAttributeOverride("Threshold") { Id = 5, InstanceId = 1, OverrideValue = "99" };
|
||||
_repoMock.Setup(r => r.GetInstanceByIdAsync(1, It.IsAny<CancellationToken>())).ReturnsAsync(instance);
|
||||
_repoMock.Setup(r => r.GetAttributesByTemplateIdAsync(1, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new List<TemplateAttribute> { new("Threshold") { IsLocked = false } });
|
||||
_repoMock.Setup(r => r.GetOverridesByInstanceIdAsync(1, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new List<InstanceAttributeOverride> { existing });
|
||||
|
||||
var result = await _sut.SetAttributeOverrideAsync(1, "Threshold", "99", "admin");
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
Assert.Same(existing, result.Value);
|
||||
_repoMock.Verify(r => r.UpdateInstanceAttributeOverrideAsync(It.IsAny<InstanceAttributeOverride>(), It.IsAny<CancellationToken>()), Times.Never);
|
||||
_repoMock.Verify(r => r.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Never);
|
||||
_auditMock.Verify(a => a.LogAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(),
|
||||
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<object?>(), It.IsAny<CancellationToken>()), Times.Never);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that overriding an unlocked attribute returns success.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
|
||||
Reference in New Issue
Block a user