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; /// /// lmxopcua#996 (review A-5): LoadAppliedAsync 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). /// [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> ReaderExecutingAsync(DbCommand command, CommandEventData data, InterceptionResult 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 { public OtOpcUaConfigDbContext CreateDbContext() => new(new DbContextOptionsBuilder().UseSqlServer(connectionString).AddInterceptors(counter).Options); public Task CreateDbContextAsync(CancellationToken cancellationToken = default) => Task.FromResult(CreateDbContext()); } private sealed class User : AuthenticationStateProvider { public override Task GetAuthenticationStateAsync() => Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity("test")))); } private sealed class Auth : IAuthorizationService { public Task AuthorizeAsync(ClaimsPrincipal user, object? resource, IEnumerable requirements) => Task.FromResult(AuthorizationResult.Success()); public Task AuthorizeAsync(ClaimsPrincipal user, object? resource, string policyName) => Task.FromResult(AuthorizationResult.Success()); } }