Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/DataConnections/DataConnectionsAppliedReadSqlServerTests.cs
T
Joseph Doherty ea976ffa81 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>
2026-12-03 10:58:50 -05:00

111 lines
5.9 KiB
C#

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());
}
}