fix(perf): #996 Wave 4 — blob-free health probes, narrow data-connections load, off-thread coordinator acks + AdminOps audit, events page cap, capped reservations page

C-6: DeploymentQueries projects Deployment without ArtifactBlob (DbHealthProbe, readiness, ClusterOverview, DriverHost boot).
C-11/A-5: DraftSnapshotFactory.FromConfigDbForDataConnectionsAsync + one-parse-per-artifact LoadAppliedAsync + capped pickers.
H-6: ConfigPublishCoordinator persists acks off the actor thread (AckPersisted); deadline backlog kicked in parallel.
H-3: Restart/Reconnect reply = dispatch; ConfigEdit audit written off-mailbox, failure logged not surfaced.
U-6: ServerHistorian:MaxEventsPerRead (default 10000) pages HistoryReadEvents; advertised as MaxReturnEventValues.
A-8: /reservations active-only by default, projected, capped at 200.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-12-03 10:58:50 -05:00
parent b9955f6946
commit ea976ffa81
31 changed files with 1184 additions and 104 deletions
@@ -0,0 +1,110 @@
using System.Data.Common;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
using ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.DataConnections;
/// <summary>
/// lmxopcua#996 (review A-5): <c>LoadAppliedAsync</c> fetches and inflates each DISTINCT applied artifact once, however
/// many nodes share it. Counted on a real SQL Server (EF InMemory has no command stream to observe).
/// </summary>
[Collection(nameof(AdminUiSqlServerCollection))]
public sealed class DataConnectionsAppliedReadSqlServerTests(AdminUiSqlServerFixture sql)
{
[SqlServerFact]
public async Task Two_nodes_on_one_deployment_read_the_artifact_blob_once()
{
var ct = TestContext.Current.CancellationToken;
var suffix = Guid.NewGuid().ToString("N")[..8];
var cluster = $"c996-{suffix}";
string[] nodes = [$"n1-{suffix}:4840", $"n2-{suffix}:4840"];
var deploymentId = Guid.NewGuid();
var at = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var draft = new DraftSnapshot
{
GenerationId = 0, ClusterId = cluster,
ServerClusters = [new ServerCluster { ClusterId = cluster, Name = "c", Enterprise = "e", Site = "s", NodeCount = 2, RedundancyMode = RedundancyMode.Warm, CreatedBy = "t", CreatedAt = at }],
ClusterNodes = nodes.Select(n => new ClusterNode { NodeId = n, ClusterId = cluster, Host = n.Split(':')[0], ApplicationUri = "urn:" + n, CreatedAt = at, CreatedBy = "t" }).ToList(),
DataConnections = [new DataConnection
{
DataConnectionId = $"peer-{suffix}", ClusterId = cluster, Enabled = true, ConsumerNodeIds = [.. nodes],
TargetMode = DataTargetMode.Cluster, ExpectedClusterId = "remote", EligibleTargetNodeIds = ["r1"],
Endpoints = ["https://peer:7443"], SecretReference = "secret:data/up", SecretScopeClusterId = cluster,
AllowedOperations = DataOperations.Browse | DataOperations.Read,
}],
};
var blob = ConfigComposer.Compose(draft).Blob;
await using (var db = await sql.Factory.CreateDbContextAsync(ct))
{
db.ServerClusters.AddRange(draft.ServerClusters);
db.ClusterNodes.AddRange(draft.ClusterNodes);
db.Deployments.Add(new Deployment { DeploymentId = deploymentId, RevisionHash = $"r-{suffix}", CreatedBy = "t", Status = DeploymentStatus.Sealed, ArtifactBlob = blob });
await db.SaveChangesAsync(ct);
db.NodeDeploymentStates.AddRange(nodes.Select(n => new NodeDeploymentState { NodeId = n, DeploymentId = deploymentId, Status = NodeDeploymentStatus.Applied }));
await db.SaveChangesAsync(ct);
}
try
{
var counter = new BlobReadCounter();
var factory = new CountingFactory(sql.ConnectionString!, counter);
var service = new DataConnectionAdminService(factory, new Auth(), new User());
var applied = await service.LoadAppliedAsync(cluster, ct);
applied.Select(a => a.NodeId).OrderBy(x => x).ShouldBe(nodes.OrderBy(x => x));
applied.ShouldAllBe(a => a.ConnectionId == $"peer-{suffix}");
counter.BlobReads.ShouldBe(1);
}
finally
{
await using var db = await sql.Factory.CreateDbContextAsync(CancellationToken.None);
await db.NodeDeploymentStates.Where(s => s.DeploymentId == deploymentId).ExecuteDeleteAsync(CancellationToken.None);
await db.Deployments.Where(d => d.DeploymentId == deploymentId).ExecuteDeleteAsync(CancellationToken.None);
await db.ClusterNodes.Where(n => n.ClusterId == cluster).ExecuteDeleteAsync(CancellationToken.None);
await db.ServerClusters.Where(c => c.ClusterId == cluster).ExecuteDeleteAsync(CancellationToken.None);
}
}
private sealed class BlobReadCounter : DbCommandInterceptor
{
public int BlobReads;
public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(DbCommand command, CommandEventData data, InterceptionResult<DbDataReader> result, CancellationToken ct = default)
{
if (command.CommandText.Contains("ArtifactBlob", StringComparison.Ordinal)) Interlocked.Increment(ref BlobReads);
return ValueTask.FromResult(result);
}
}
private sealed class CountingFactory(string connectionString, BlobReadCounter counter) : IDbContextFactory<OtOpcUaConfigDbContext>
{
public OtOpcUaConfigDbContext CreateDbContext() =>
new(new DbContextOptionsBuilder<OtOpcUaConfigDbContext>().UseSqlServer(connectionString).AddInterceptors(counter).Options);
public Task<OtOpcUaConfigDbContext> CreateDbContextAsync(CancellationToken cancellationToken = default) => Task.FromResult(CreateDbContext());
}
private sealed class User : AuthenticationStateProvider
{
public override Task<AuthenticationState> GetAuthenticationStateAsync() => Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity("test"))));
}
private sealed class Auth : IAuthorizationService
{
public Task<AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user, object? resource, IEnumerable<IAuthorizationRequirement> requirements) => Task.FromResult(AuthorizationResult.Success());
public Task<AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user, object? resource, string policyName) => Task.FromResult(AuthorizationResult.Success());
}
}
@@ -0,0 +1,129 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.EntityFrameworkCore;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections;
using ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Acls;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.DataConnections;
/// <summary>
/// lmxopcua#996 (review C-11 / A-5): the data-connections page and its save/delete no longer read the whole ConfigDb.
/// The narrow loader must (a) skip the tables the validator never reads, (b) keep exactly the tag data the rules do read
/// (the alarm bit), and (c) leave the authoring rules unchanged.
/// </summary>
[Trait("Category", "Unit"), Trait("Feature", "GrpcData")]
public sealed class DataConnectionsNarrowLoadTests
{
private const string AlarmConfig = "{\"alarm\":{\"alarmType\":\"AlarmCondition\",\"severity\":700}}";
private static async Task<IDbContextFactory<OtOpcUaConfigDbContext>> SeedAsync()
{
var name = $"dc-narrow-{Guid.NewGuid():N}";
await using (var db = AclScopeTestDb.CreateNamed(name))
{
AclScopeTestDb.Seed(db); // MAIN cluster, DEV-1, TAG-speed ("{}") and four ApiKeys
db.Tags.Add(new Tag
{
TagId = "TAG-alarm", DeviceId = AclScopeTestDb.DeviceId, TagGroupId = null, Name = "overtemp",
DataType = "Boolean", AccessLevel = TagAccessLevel.Read, TagConfig = AlarmConfig,
});
db.Tags.Add(new Tag
{
TagId = "TAG-bulky", DeviceId = AclScopeTestDb.DeviceId, TagGroupId = null, Name = "bulky",
DataType = "Float", AccessLevel = TagAccessLevel.Read, TagConfig = "{\"address\":\"" + new string('x', 4000) + "\"}",
});
db.Scripts.Add(new Script { ScriptId = "S1", Name = "s", SourceCode = "return 1;", SourceHash = "h" });
await db.SaveChangesAsync(TestContext.Current.CancellationToken);
}
return AclScopeTestDb.Factory(name);
}
[Fact]
public async Task Narrow_snapshot_skips_tables_the_validator_never_reads_and_strips_tag_config()
{
var ct = TestContext.Current.CancellationToken;
var factory = await SeedAsync();
await using var db = await factory.CreateDbContextAsync(ct);
var narrow = await DraftSnapshotFactory.FromConfigDbForDataConnectionsAsync(db, ct);
var full = await DraftSnapshotFactory.FromConfigDbAsync(db, ct);
// Positive control: the full snapshot DOES carry them, so the absence below is a real difference.
full.ApiKeys.Count.ShouldBeGreaterThan(0);
full.Scripts.Count.ShouldBe(1);
full.Tags.Single(t => t.TagId == "TAG-bulky").TagConfig.Length.ShouldBeGreaterThan(4000);
narrow.ApiKeys.ShouldBeEmpty();
narrow.Scripts.ShouldBeEmpty();
narrow.NodeAcls.ShouldBeEmpty();
narrow.PollGroups.ShouldBeEmpty();
narrow.ActiveReservations.ShouldBeEmpty();
narrow.Tags.Select(t => t.TagId).ShouldBe(full.Tags.Select(t => t.TagId));
narrow.Tags.Single(t => t.TagId == "TAG-bulky").TagConfig.ShouldBe("{}");
narrow.Tags.Single(t => t.TagId == AclScopeTestDb.TagId).TagConfig.ShouldBe("{}");
narrow.Tags.Single(t => t.TagId == "TAG-alarm").TagConfig.ShouldBe(AlarmConfig);
// Same rows for everything the validator reads.
narrow.DataConnections.Count.ShouldBe(full.DataConnections.Count);
narrow.ClusterNodes.Count.ShouldBe(full.ClusterNodes.Count);
narrow.Devices.Count.ShouldBe(full.Devices.Count);
DataConnectionValidator.Validate(narrow).ShouldBe(DataConnectionValidator.Validate(full));
}
[Fact]
public void Narrow_tag_query_selects_tag_config_only_behind_an_alarm_guard()
{
using var db = new OtOpcUaConfigDbContext(new DbContextOptionsBuilder<OtOpcUaConfigDbContext>()
.UseSqlServer("Server=127.0.0.1,1;Database=never;Connect Timeout=1").Options);
var sql = DraftSnapshotFactory.NarrowTags(db).ToQueryString();
sql.ShouldContain("CASE");
sql.ShouldContain("alarm");
sql.ShouldNotContain("[t].[DataType]");
sql.ShouldNotContain("[t].[AccessLevel]");
sql.ShouldNotContain("[t].[PollGroupId]");
// Positive control: the whole-entity read selects them.
var whole = db.Tags.AsNoTracking().ToQueryString();
whole.ShouldContain("[t].[DataType]");
}
[Fact]
public async Task An_export_rooted_at_an_alarm_bearing_tag_is_still_refused_through_the_narrow_load()
{
var ct = TestContext.Current.CancellationToken;
var factory = await SeedAsync();
var service = new DataConnectionAdminService(factory, new Auth(), new User());
DataExport Export(string id, string tag) => new()
{
ClusterId = "MAIN", DataExportId = id, Enabled = true, Realm = DataRealm.Raw,
RootKind = "RawTag", RootEntityId = tag, PrincipalId = "peer",
AllowedOperations = DataOperations.Browse | DataOperations.Read,
};
await service.SaveAsync("MAIN", Export("exp-value", AclScopeTestDb.TagId), ct);
await Should.ThrowAsync<InvalidOperationException>(() => service.SaveAsync("MAIN", Export("exp-alarm", "TAG-alarm"), ct));
(await service.LoadAsync(ct)).DataExports.Select(e => e.DataExportId).ShouldBe(["exp-value"]);
}
private sealed class User : AuthenticationStateProvider
{
public override Task<AuthenticationState> GetAuthenticationStateAsync() => Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity("test"))));
}
private sealed class Auth : IAuthorizationService
{
public Task<AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user, object? resource, IEnumerable<IAuthorizationRequirement> requirements) => Task.FromResult(AuthorizationResult.Success());
public Task<AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user, object? resource, string policyName) => Task.FromResult(AuthorizationResult.Success());
}
}
@@ -0,0 +1,114 @@
using Akka.Actor;
using Microsoft.EntityFrameworkCore;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Mesh;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations;
using ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests;
/// <summary>
/// lmxopcua#996 (review H-3): Restart/Reconnect report the DISPATCH. A ConfigDb failure while writing the audit row
/// must not turn an already-dispatched command into a "failed" reply (the operator retries ⇒ a second restart), and the
/// audit write must not suspend the admin mailbox.
/// </summary>
public sealed class AdminOperationsActorDriverOperationTests : ControlPlaneActorTestBase
{
private static readonly TimeSpan AckBudget = TimeSpan.FromSeconds(1);
private (IActorRef Actor, Akka.TestKit.TestProbe Router) Create(IDbContextFactory<OtOpcUaConfigDbContext> factory)
{
var router = CreateTestProbe("router");
var coordinator = CreateTestProbe("coord");
var actor = Sys.ActorOf(AdminOperationsActor.Props(factory, coordinator.Ref, Enumerable.Empty<IDriverProbe>(), meshRouter: router.Ref));
return (actor, router);
}
/// <summary>The audit write throws: the command still went out and the reply says so (success).</summary>
[Theory]
[InlineData(true)]
[InlineData(false)]
public void Audit_failure_does_not_turn_a_dispatched_command_into_a_failure(bool restart)
{
var (actor, router) = Create(new ThrowingAsyncFactory(NewInMemoryDbFactory()));
var correlation = Guid.NewGuid();
if (restart) actor.Tell(new RestartDriver("MAIN", "drv-1", "joe", correlation));
else actor.Tell(new ReconnectDriver("MAIN", "drv-1", "joe", correlation));
var command = router.ExpectMsg<MeshCommand>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
if (restart) command.Message.ShouldBeOfType<RestartDriver>();
else command.Message.ShouldBeOfType<ReconnectDriver>();
if (restart)
{
var reply = ExpectMsg<RestartDriverResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
reply.Ok.ShouldBeTrue();
reply.CorrelationId.ShouldBe(correlation);
}
else
{
var reply = ExpectMsg<ReconnectDriverResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
reply.Ok.ShouldBeTrue();
reply.CorrelationId.ShouldBe(correlation);
}
}
/// <summary>
/// While the audit write is parked on a gated DB, the reply is already out and an alarm ack is answered; releasing the
/// gate writes the row (positive control: the audit is not skipped, only moved off the mailbox).
/// </summary>
[Fact]
public void Audit_write_does_not_hold_the_mailbox_and_is_still_recorded()
{
var inner = NewInMemoryDbFactory();
var gated = new GatedAsyncFactory(inner);
var (actor, router) = Create(gated);
gated.Hold();
actor.Tell(new RestartDriver("MAIN", "drv-2", "joe", Guid.NewGuid()));
ExpectMsg<RestartDriverResult>(AckBudget, cancellationToken: TestContext.Current.CancellationToken).Ok.ShouldBeTrue();
gated.Entered.Wait(PresenceBudget, TestContext.Current.CancellationToken).ShouldBeTrue("the audit write must be parked");
// The mailbox is free: a second operation is dispatched and answered while the first audit is still parked.
actor.Tell(new ReconnectDriver("MAIN", "drv-3", "kim", Guid.NewGuid()));
ExpectMsg<ReconnectDriverResult>(AckBudget, cancellationToken: TestContext.Current.CancellationToken).Ok.ShouldBeTrue();
using (var db = inner.CreateDbContext()) db.ConfigEdits.ShouldBeEmpty();
gated.Release();
AwaitAssert(() =>
{
using var db = inner.CreateDbContext();
db.ConfigEdits.Count().ShouldBe(2);
db.ConfigEdits.Select(e => e.EditedBy).OrderBy(x => x).ToList().ShouldBe(["joe", "kim"]);
}, duration: PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
router.ExpectMsg<MeshCommand>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
}
private sealed class ThrowingAsyncFactory(IDbContextFactory<OtOpcUaConfigDbContext> inner) : IDbContextFactory<OtOpcUaConfigDbContext>
{
public OtOpcUaConfigDbContext CreateDbContext() => inner.CreateDbContext();
public Task<OtOpcUaConfigDbContext> CreateDbContextAsync(CancellationToken cancellationToken = default) =>
throw new InvalidOperationException("ConfigDb unreachable (simulated)");
}
private sealed class GatedAsyncFactory(IDbContextFactory<OtOpcUaConfigDbContext> inner) : IDbContextFactory<OtOpcUaConfigDbContext>
{
private volatile TaskCompletionSource? _gate;
public ManualResetEventSlim Entered { get; } = new();
public void Hold() => _gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
public void Release() => _gate?.TrySetResult();
public OtOpcUaConfigDbContext CreateDbContext() => inner.CreateDbContext();
public async Task<OtOpcUaConfigDbContext> CreateDbContextAsync(CancellationToken cancellationToken = default)
{
Entered.Set();
if (_gate is { } gate) await gate.Task.WaitAsync(cancellationToken);
return inner.CreateDbContext();
}
}
}
@@ -0,0 +1,107 @@
using System.Diagnostics;
using Akka.Actor;
using Microsoft.EntityFrameworkCore;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.ControlPlane.Coordinators;
using ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests;
/// <summary>
/// lmxopcua#996 (review H-6): the per-node ack write used to be a blocking <c>SaveChanges</c> on the coordinator's
/// thread, so with a slow or unreachable ConfigDb N acks cost N x the connect timeout of unresponsive mailbox. The
/// write now runs on a pool thread and reports back as a message.
/// </summary>
public sealed class ConfigPublishCoordinatorOffThreadAckTests : ControlPlaneActorTestBase
{
private static readonly RevisionHash Revision = RevisionHash.Parse(new string('e', 64));
private static readonly TimeSpan NoTimeout = TimeSpan.FromMinutes(5);
private static readonly TimeSpan PerCall = TimeSpan.FromMilliseconds(500);
private const int NodeCount = 6;
/// <summary>
/// Six acks arrive while every ConfigDb call takes 500 ms (a slow link or a connect timeout). The mailbox stays live
/// (an Identify round-trip answers in well under the 3 s the serialised writes would take), and every ack still lands
/// and seals the deployment (positive control: the writes DID happen, off-thread).
/// </summary>
[Fact]
public async Task Slow_ConfigDb_acks_do_not_block_the_coordinator_mailbox_and_still_seal()
{
var ct = TestContext.Current.CancellationToken;
var dbName = Guid.NewGuid().ToString("N");
var direct = NewInMemoryDbFactory(dbName);
var slow = new SlowDbFactory(NewInMemoryDbFactory(dbName));
var nodes = Enumerable.Range(1, NodeCount).Select(i => $"site-a-{i}:4053").ToArray();
Seed(direct, nodes, out var deploymentId);
var coordinator = Sys.ActorOf(ConfigPublishCoordinator.Props(
slow, NoTimeout, loadRetryMin: TimeSpan.FromMilliseconds(50), loadRetryMax: TimeSpan.FromMilliseconds(200)));
coordinator.Tell(new DispatchDeployment(deploymentId, Revision, CorrelationId.NewId()));
AwaitAssert(() =>
{
using var db = direct.CreateDbContext();
db.Deployments.Single().Status.ShouldBe(DeploymentStatus.AwaitingApplyAcks);
}, duration: PresenceBudget, cancellationToken: ct);
slow.Delay = PerCall;
foreach (var node in nodes)
coordinator.Tell(new ApplyAck(deploymentId, NodeId.Parse(node), ApplyAckOutcome.Applied, null, CorrelationId.NewId()));
var sw = Stopwatch.StartNew();
var identity = await coordinator.Ask<ActorIdentity>(new Identify("probe"), TimeSpan.FromSeconds(10), ct);
sw.Stop();
identity.Subject.ShouldBe(coordinator);
// Serialised on the actor thread this is >= 6 x 500 ms = 3 s; off-thread it is one scheduling hop.
sw.Elapsed.ShouldBeLessThan(TimeSpan.FromMilliseconds(1500),
"the coordinator mailbox must not wait on the ConfigDb writes of the acks");
AwaitAssert(() =>
{
using var db = direct.CreateDbContext();
db.Deployments.Single().Status.ShouldBe(DeploymentStatus.Sealed);
db.NodeDeploymentStates.Count(s => s.Status == NodeDeploymentStatus.Applied).ShouldBe(NodeCount);
}, duration: PresenceBudget, cancellationToken: ct);
}
private static void Seed(IDbContextFactory<OtOpcUaConfigDbContext> factory, string[] nodeIds, out DeploymentId id)
{
id = DeploymentId.NewId();
using var db = factory.CreateDbContext();
db.ServerClusters.Add(new ServerCluster
{
ClusterId = "SITE-A", Name = "Site A", Enterprise = "zb", Site = "site-a",
NodeCount = (byte)nodeIds.Length, RedundancyMode = RedundancyMode.None, CreatedBy = "test",
});
foreach (var nodeId in nodeIds)
db.ClusterNodes.Add(new ClusterNode
{
NodeId = nodeId, ClusterId = "SITE-A", Host = nodeId.Split(':')[0],
ApplicationUri = $"urn:OtOpcUa:{nodeId}", Enabled = true, CreatedBy = "test",
});
db.Deployments.Add(new Deployment
{
DeploymentId = id.Value, RevisionHash = Revision.Value, Status = DeploymentStatus.Dispatching, CreatedBy = "test",
});
db.SaveChanges();
}
/// <summary>A factory whose synchronous context creation takes <see cref="Delay"/> (a slow connect).</summary>
private sealed class SlowDbFactory(IDbContextFactory<OtOpcUaConfigDbContext> inner) : IDbContextFactory<OtOpcUaConfigDbContext>
{
public TimeSpan Delay { get => _delay; set => _delay = value; }
private TimeSpan _delay;
public OtOpcUaConfigDbContext CreateDbContext()
{
var delay = Delay;
if (delay > TimeSpan.Zero) Thread.Sleep(delay);
return inner.CreateDbContext();
}
}
}
@@ -348,6 +348,47 @@ public sealed class NodeManagerHistoryReadEventsPagingTests : IDisposable
await host.DisposeAsync();
}
// --- #996 (U-6): the server's own per-page event cap (ServerHistorian:MaxEventsPerRead) ------------------------
[Theory]
[InlineData(0u)] // "all values" is paged, never one shot
[InlineData(50u)] // a request above the cap is paged at the cap
public async Task Server_event_cap_pages_an_uncapped_or_oversized_request_and_bounds_the_backend_read(uint requested)
{
var (host, nm, node, src) = await SetupAsync(Distinct(25));
nm.MaxEventsPerRead = 10;
var first = ReadEvents(nm, node, requested, inboundCp: null);
first.Error.StatusCode.Code.ShouldBe(StatusCodes.Good.Code);
first.Ids.Count.ShouldBe(10, "a page never exceeds the server cap");
first.Cp.ShouldNotBeNull("the truncated page carries a continuation point");
src.MaxRequested.ShouldBeLessThanOrEqualTo(10, "the backend is never asked for more than the cap (no boundary skip on page 1)");
// Paging yields every event exactly once, in order.
var sizes = new List<int>();
DrainAsync(nm, node, requested, pageSizes: sizes).ShouldBe(src.All.Select(e => e.EventId));
sizes.ShouldAllBe(n => n <= 10);
sizes.Count.ShouldBe(3);
await host.DisposeAsync();
}
[Fact]
public async Task Server_event_cap_applies_to_reverse_reads_and_opting_out_restores_the_one_shot_answer()
{
var (host, nm, node, src) = await SetupAsync(Distinct(25));
nm.MaxEventsPerRead = 10;
DrainAsync(nm, node, max: 0, start: Epoch.AddSeconds(30), end: Epoch.AddSeconds(-1))
.ShouldBe(src.All.Select(e => e.EventId).Reverse());
ReadEvents(nm, node, 0, null, end: Epoch.AddSeconds(-1), start: Epoch.AddSeconds(30)).Ids.Count.ShouldBe(10);
// Positive control: the cap is what paged it. Opt out (<= 0) and the same read is one complete page.
nm.MaxEventsPerRead = 0;
var all = ReadEvents(nm, node, 0, null);
all.Ids.Count.ShouldBe(25);
all.Cp.ShouldBeNull();
await host.DisposeAsync();
}
private static readonly DateTime Early = Epoch.AddDays(-1);
private static readonly DateTime Late = Epoch.AddDays(1);
@@ -725,10 +766,14 @@ public sealed class NodeManagerHistoryReadEventsPagingTests : IDisposable
events.OrderBy(e => e.EventTimeUtc).ThenBy(e => e.EventId, StringComparer.Ordinal).ToList();
public int Calls { get; private set; }
/// <summary>The largest <c>maxEvents</c> any read asked this source for (#996: the server's cap must bound it).</summary>
public int MaxRequested { get; private set; }
public Task<HistoricalEventsResult> ReadEventsAsync(
string? sourceName, DateTime startUtc, DateTime endUtc, int maxEvents, CancellationToken ct)
{
Calls++;
MaxRequested = Math.Max(MaxRequested, maxEvents);
// Like the SQL backends: a reversed window is swapped, inputs truncate to the storage resolution.
if (startUtc > endUtc) (startUtc, endUtc) = (endUtc, startUtc);
startUtc = Trunc(startUtc);
@@ -746,6 +791,7 @@ public sealed class NodeManagerHistoryReadEventsPagingTests : IDisposable
{
if (!reverse) return ReadEventsAsync(sourceName, startUtc, endUtc, maxEvents, ct);
Calls++;
MaxRequested = Math.Max(MaxRequested, maxEvents);
var (lo, hi) = startUtc <= endUtc ? (startUtc, endUtc) : (endUtc, startUtc);
lo = Trunc(lo);
hi = Trunc(hi);
@@ -98,7 +98,8 @@ public sealed class NodeManagerHistoryReadEventsTests : IDisposable
/// <summary>OpcUaServer-002: a HistoryReadEvents with <c>NumValuesPerNode == 0</c> means "no limit —
/// return ALL values" per OPC UA Part 4/11, so the backend must receive an UNBOUNDED cap
/// (<see cref="int.MaxValue"/>), NOT the <c>maxEvents &lt;= 0</c> "use the default cap" sentinel that
/// would silently truncate a whole-window read.</summary>
/// would silently truncate a whole-window read. Since #996 that holds only with the server cap opted out
/// (<c>MaxEventsPerRead = 0</c>); by default the backend receives the cap (<see cref="Events_zero_count_request_is_bounded_by_the_server_cap_by_default"/>).</summary>
[Fact]
public async Task Events_unbounded_request_passes_int_max_to_backend()
{
@@ -106,6 +107,7 @@ public sealed class NodeManagerHistoryReadEventsTests : IDisposable
var nm = server.NodeManager!;
var fake = new RecordingHistorianDataSource();
nm.HistorianDataSource = fake;
nm.MaxEventsPerRead = 0; // opt out of the #996 server cap: the pre-#996 unbounded semantics
const string equipmentId = "eq-unbounded";
nm.EnsureFolder(equipmentId, parentNodeId: null, displayName: "Equipment", realm: AddressSpaceRealm.Uns);
@@ -133,6 +135,35 @@ public sealed class NodeManagerHistoryReadEventsTests : IDisposable
await host.DisposeAsync();
}
/// <summary>#996 (U-6): with the cap at its default, a <c>NumValuesPerNode == 0</c> read asks the backend for at most the
/// server cap — never <see cref="int.MaxValue"/> — and the advertised property is not required for that.</summary>
[Fact]
public async Task Events_zero_count_request_is_bounded_by_the_server_cap_by_default()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
var fake = new RecordingHistorianDataSource();
nm.HistorianDataSource = fake;
nm.MaxEventsPerRead.ShouldBe(OtOpcUaNodeManager.DefaultMaxEventsPerRead);
const string equipmentId = "eq-capped";
nm.EnsureFolder(equipmentId, parentNodeId: null, displayName: "Equipment", realm: AddressSpaceRealm.Uns);
nm.MaterialiseAlarmCondition("alarm-c", equipmentId, "Cond", "OffNormalAlarm", severity: 600, realm: AddressSpaceRealm.Uns);
var notifierNodeId = nm.TryGetFolder(equipmentId)!.NodeId;
fake.EventsResult = new HistoricalEventsResult(
new[] { new HistoricalEvent("evt-x", "Src", DateTime.UtcNow, DateTime.UtcNow, "msg", 600) }, null);
var details = new ReadEventDetails
{
StartTime = DateTime.UtcNow.AddHours(-1), EndTime = DateTime.UtcNow, NumValuesPerNode = 0, Filter = SelectFilter("EventId"),
};
var (_, errors) = InvokeHistoryRead(server, nm, details, notifierNodeId);
errors[0].StatusCode.Code.ShouldBe(StatusCodes.Good.Code);
fake.LastMaxEvents.ShouldBe(OtOpcUaNodeManager.DefaultMaxEventsPerRead);
await host.DisposeAsync();
}
/// <summary>An unsupported select operand (BrowsePath ["LocalTime"]) projects to Variant.Null — a field
/// the server can't supply is null (spec-conformant) — while supported siblings still project. (EventType used to
/// be such a field; it is projected now — see NodeManagerHistoryReadEventsProjectionTests.)</summary>