diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Deployments.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Deployments.razor index 01df5ffdd..63a08c867 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Deployments.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Deployments.razor @@ -1,6 +1,7 @@ @page "/deployments" @using Microsoft.AspNetCore.Components.Authorization @using Microsoft.EntityFrameworkCore +@using Microsoft.Extensions.Logging @using ZB.MOM.WW.OtOpcUa.Commons.Interfaces @using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin @using ZB.MOM.WW.OtOpcUa.Configuration @@ -13,6 +14,7 @@ @inject IAdminOperationsClient AdminOps @inject AuthenticationStateProvider AuthState @inject ZB.MOM.WW.OtOpcUa.AdminUI.Deployments.DeploymentDriftProbe DriftProbe +@inject ILogger Logger @rendermode InteractiveServer @@ -25,11 +27,22 @@ @(_busy ? "Deploying…" : "Deploy current configuration") - @if (_drift is not null) + @* lmxopcua#903: the chip says nothing about sync until a composition taken after this page opened has + answered — first render shows "Checking…", never a verdict carried over from an earlier load. *@ + @switch (_driftState) { - - @(_drift.Value ? "Configuration drift" : "In sync") - + case DriftState.Checking: + Checking for changes… + break; + case DriftState.Drift: + Configuration drift + break; + case DriftState.InSync: + In sync + break; + case DriftState.Failed: + Drift check failed + break; } @@ -85,13 +98,54 @@ private bool _busy; private bool _lastSuccess; private string? _lastMessage; - private bool? _drift; + private enum DriftState { None, Checking, Drift, InSync, Failed } + + private DriftState _driftState; protected override async Task OnInitializedAsync() { await ReloadAsync(); } + protected override async Task OnAfterRenderAsync(bool firstRender) + { + // Interactive render only (OnAfterRender never runs during prerender), so a page visit pays for one + // composition, after the table is already on screen. + if (firstRender) + { + await RefreshDriftAsync(); + StateHasChanged(); + } + } + + private async Task RefreshDriftAsync() + { + // Drift: if no sealed deployment yet, no drift to report. Otherwise the probe compares the latest sealed + // revision hash to a fresh composition of the live-edit state. + var latestSealed = _deployments.FirstOrDefault(d => d.Status == DeploymentStatus.Sealed); + if (latestSealed is null) + { + _driftState = DriftState.None; + return; + } + + try + { + var drift = await DriftProbe.GetDriftAsync(latestSealed.RevisionHash, CancellationToken.None); + _driftState = drift switch + { + true => DriftState.Drift, + false => DriftState.InSync, + null => DriftState.None, + }; + } + catch (Exception ex) + { + Logger.LogWarning(ex, "Deployments: drift check against revision {RevisionHash} failed.", latestSealed.RevisionHash); + _driftState = DriftState.Failed; + } + } + private async Task ReloadAsync() { await using var db = await DbFactory.CreateDbContextAsync(); @@ -109,13 +163,8 @@ .Take(50) .ToListAsync(); - // Drift: if no sealed deployment yet, no drift to report. Otherwise the probe compares the - // latest sealed revision hash to the live-edit state — recomposing only when the ConfigEdit - // audit watermark has moved, so a re-render of this page is not a full fleet snapshot. - var latestSealed = _deployments.FirstOrDefault(d => d.Status == DeploymentStatus.Sealed); - _drift = latestSealed is null - ? null - : await DriftProbe.GetDriftAsync(latestSealed.RevisionHash, CancellationToken.None); + // The verdict for these rows is not known yet; RefreshDriftAsync answers it. + _driftState = _deployments.Any(d => d.Status == DeploymentStatus.Sealed) ? DriftState.Checking : DriftState.None; } private async Task StartDeploymentAsync() @@ -139,6 +188,7 @@ _ => result.Message ?? "Deployment rejected.", }; await ReloadAsync(); + await RefreshDriftAsync(); } catch (Exception ex) { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Deployments/DeploymentDriftProbe.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Deployments/DeploymentDriftProbe.cs index cc7ab050c..1a733ce04 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Deployments/DeploymentDriftProbe.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Deployments/DeploymentDriftProbe.cs @@ -5,50 +5,35 @@ using ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations; namespace ZB.MOM.WW.OtOpcUa.AdminUI.Deployments; /// -/// Answers the /deployments page's "Configuration drift" chip without recomposing the whole -/// configuration on every page load. +/// Answers the /deployments page's "Configuration drift" chip: does the live-edit state still hash to the +/// latest sealed revision? /// /// /// -/// Why. The chip's question — "does the live-edit state still hash to the latest sealed -/// revision?" — was answered by calling ConfigComposer.SnapshotAndFlattenAsync on every -/// ReloadAsync: eighteen unfiltered table reads, a deterministic JSON serialisation of the -/// entire fleet configuration, a gzip pass and a SHA-256, all to render one badge. Opening -/// /deployments, deploying, or simply re-rendering the page paid for it again. +/// Always a fresh composition (lmxopcua#903). This probe used to cache its verdict until the +/// ConfigEdit audit watermark (MAX(EditedAtUtc), COUNT(*)) moved, on the premise that every +/// configuration write appends a ConfigEdit row. That premise was false: the AdminUI's own editors +/// (RawTreeService, UnsTreeService, ScriptEdit, the cluster/node/ACL pages) write the +/// configuration tables directly and append no audit row — only deployments and driver restart/reconnect do. +/// So after a draft change the chip kept serving the cached "In sync" until something unrelated moved the +/// watermark: an operator could believe there was nothing to deploy. There is no cheap, provider-neutral +/// signal that moves on every write to the ~18 composed tables, so every verdict is now computed from a +/// composition that read the configuration AFTER the request arrived. /// /// -/// The watermark. ConfigEdit is the append-only audit row that every mutating -/// live-edit operation writes (see the entity's remarks — AdminOperationsActor appends one -/// per mutation), so (MAX(EditedAtUtc), COUNT(*)) moves whenever the configuration could -/// have changed. That pair is one indexed aggregate (IX_ConfigEdit_EditedAt) against a -/// full recomposition. When neither the watermark nor the sealed revision hash has moved since -/// the last verdict, the cached verdict is returned unchanged. -/// -/// -/// Accepted staleness. An edit path that mutated a configuration table WITHOUT writing a -/// ConfigEdit row would not invalidate this cache, and the chip could then read "In sync" -/// over a genuinely drifted configuration until the next audited edit. That is acceptable -/// precisely because the chip is advisory: the authoritative comparison is -/// AdminOperationsActor's own recomposition at deploy time, which always reads live and -/// which reports NoChanges for a deploy that would be a no-op. Today every -/// AdminOperationsActor mutation writes the audit row, so the gap is theoretical — but a -/// future write path that skips the audit must not be relied on to move this chip. The -/// COUNT(*) half is what keeps a same-timestamp edit (two mutations inside one tick, or -/// an edit deleted and replaced) from hiding behind an unchanged maximum. -/// -/// -/// Concurrency. The cheap watermark read runs outside the gate, so concurrent circuits do -/// not serialise on it. Only the recompose path takes the , and it -/// double-checks the cache after acquiring it — so N circuits that miss at the same instant -/// share ONE recomposition rather than launching N. A throw leaves the previous verdict in -/// place and propagates to its caller alone. +/// Concurrency. Compositions are serialised behind a , so N circuits +/// opening the page at once never run N fleet snapshots in parallel. A caller queued behind a composition +/// reuses that verdict only when the composition started after the caller arrived (tracked by a +/// start sequence number) and was against the same sealed revision — such a composition has already seen +/// every edit committed before the caller asked, so sharing it is exact, not stale. A throw leaves the +/// previous verdict in place and propagates to its caller alone. /// /// /// Factory for the configuration database context. /// /// The compose seam — returns the revision hash of a fresh snapshot of the supplied context. /// Defaults to the real ConfigComposer.SnapshotAndFlattenAsync(...).RevisionHash; tests -/// inject a counting fake to prove the cache actually elides recompositions. +/// inject a counting fake. /// public sealed class DeploymentDriftProbe( IDbContextFactory dbFactory, @@ -57,11 +42,14 @@ public sealed class DeploymentDriftProbe( private readonly Func> _composeRevisionHash = composeRevisionHash ?? ComposeRevisionHashAsync; - private readonly SemaphoreSlim _recomposeGate = new(1, 1); + private readonly SemaphoreSlim _composeGate = new(1, 1); - /// The last computed verdict, or before the first one. Volatile: the - /// fast path reads it off the gate, so the publishing write must be visible to every circuit. - private volatile Verdict? _verdict; + /// How many compositions have started; incremented under the gate as each one begins. + private long _composesStarted; + + /// The last computed verdict, or before the first one. Read and written + /// only under the gate. + private Verdict? _verdict; /// /// Reports whether the live-edit configuration has drifted from the supplied sealed revision. @@ -80,66 +68,37 @@ public sealed class DeploymentDriftProbe( { if (string.IsNullOrEmpty(latestSealedRevisionHash)) return null; - await using var db = await dbFactory.CreateDbContextAsync(ct); - var watermark = await ReadWatermarkAsync(db, ct); + // Any composition numbered above this one starts after this point, so it reads every edit + // committed before this call. + var arrivedAfter = Interlocked.Read(ref _composesStarted); - // Fast path: no gate, because a hit reads one immutable record reference. - if (IsCurrent(_verdict, watermark, latestSealedRevisionHash, out var cached)) return cached; - - await _recomposeGate.WaitAsync(ct); + await _composeGate.WaitAsync(ct); try { - // Double-check: a caller ahead of us in the queue may have just recomposed the same state. - if (IsCurrent(_verdict, watermark, latestSealedRevisionHash, out cached)) return cached; + var shared = _verdict; + if (shared is not null + && shared.Sequence > arrivedAfter + && string.Equals(shared.SealedRevisionHash, latestSealedRevisionHash, StringComparison.Ordinal)) + { + return shared.Drift; + } + var sequence = Interlocked.Increment(ref _composesStarted); + await using var db = await dbFactory.CreateDbContextAsync(ct); var current = await _composeRevisionHash(db); var drift = !string.Equals(current, latestSealedRevisionHash, StringComparison.Ordinal); - _verdict = new Verdict(watermark, latestSealedRevisionHash, drift); + _verdict = new Verdict(sequence, latestSealedRevisionHash, drift); return drift; } finally { - _recomposeGate.Release(); + _composeGate.Release(); } } - private static bool IsCurrent( - Verdict? verdict, Watermark watermark, string sealedHash, out bool drift) - { - if (verdict is not null - && verdict.Watermark == watermark - && string.Equals(verdict.SealedRevisionHash, sealedHash, StringComparison.Ordinal)) - { - drift = verdict.Drift; - return true; - } - - drift = false; - return false; - } - - /// Reads the audit watermark as a single aggregate row (no rows at all ⇒ the empty watermark). - private static async Task ReadWatermarkAsync(OtOpcUaConfigDbContext db, CancellationToken ct) - { - // GroupBy(_ => 1) collapses the whole table to one aggregate row, so this is ONE round-trip for - // both scalars rather than two. An empty table produces no group at all, so FirstOrDefaultAsync - // lands on null and we return the default (never-edited) watermark; the Max is cast to nullable - // so the projection stays valid for the no-rows shape either way. - var row = await db.ConfigEdits - .AsNoTracking() - .GroupBy(_ => 1) - .Select(g => new { LastEditUtc = g.Max(e => (DateTime?)e.EditedAtUtc), EditCount = g.Count() }) - .FirstOrDefaultAsync(ct); - - return row is null ? default : new Watermark(row.LastEditUtc, row.EditCount); - } - private static async Task ComposeRevisionHashAsync(OtOpcUaConfigDbContext db) => (await ConfigComposer.SnapshotAndFlattenAsync(db)).RevisionHash; - /// The ConfigEdit audit watermark: newest edit timestamp plus the total edit count. - private readonly record struct Watermark(DateTime? LastEditUtc, int EditCount); - - /// A drift answer, valid only for the watermark and sealed revision it was computed against. - private sealed record Verdict(Watermark Watermark, string SealedRevisionHash, bool Drift); + /// A drift answer from the composition with start number . + private sealed record Verdict(long Sequence, string SealedRevisionHash, bool Drift); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/EndpointRouteBuilderExtensions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/EndpointRouteBuilderExtensions.cs index faa797df2..3b9415b7d 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/EndpointRouteBuilderExtensions.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/EndpointRouteBuilderExtensions.cs @@ -121,8 +121,8 @@ public static class EndpointRouteBuilderExtensions // TryAdd so a host that already bound a clock (test harness, future fused-host registration) wins. services.TryAddSingleton(TimeProvider.System); - // /deployments drift chip. A singleton so its ConfigEdit-watermark cache is shared across - // circuits — otherwise every page load would recompose the whole fleet configuration. + // /deployments drift chip. A singleton so concurrent circuits share one composition gate (and a + // composition that started after they asked) instead of running N fleet snapshots at once. // Constructed explicitly rather than by ctor scan: the compose seam is an optional parameter // that only tests supply, and production must always get the real ConfigComposer default. services.AddSingleton(sp => new Deployments.DeploymentDriftProbe( diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/AdminUiSqlServerFixture.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/AdminUiSqlServerFixture.cs index 424f2cfe4..48024ca42 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/AdminUiSqlServerFixture.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/AdminUiSqlServerFixture.cs @@ -56,7 +56,7 @@ public sealed class AdminUiSqlServerFixture : IDisposable /// /// Gets a context factory pointed at the migrated test database — the seam the services under test - /// (DeploymentDriftProbe, RawTreeService) take. Throws when + /// (RawTreeService, CredentialReferencePreflight) take. Throws when /// is set; guard with . /// public IDbContextFactory Factory => diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Deployments/DeploymentDriftProbeTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Deployments/DeploymentDriftProbeTests.cs index 41b1f2328..4771bf844 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Deployments/DeploymentDriftProbeTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Deployments/DeploymentDriftProbeTests.cs @@ -4,80 +4,123 @@ using ZB.MOM.WW.OtOpcUa.AdminUI.Deployments; using ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Uns; 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.AdminOperations; namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Deployments; /// -/// Pins the watermark contract: the expensive -/// ConfigComposer recomposition runs only when the ConfigEdit audit watermark (or the -/// sealed revision hash) has moved, and it definitely still runs when it has. +/// Pins the freshness contract (lmxopcua#903): every verdict comes from a +/// composition that started after the caller asked, so a draft change made by a path that writes no +/// ConfigEdit audit row (every AdminUI editor) is never hidden behind an earlier "In sync"; concurrent +/// callers still share one composition when that composition is fresh for all of them. /// +[Trait("Category", "Unit")] public sealed class DeploymentDriftProbeTests { private const string SealedHash = "sealed-hash-aaaa"; [Fact] - public async Task An_unchanged_watermark_reuses_the_cached_verdict() + public async Task A_draft_change_without_an_audit_row_is_reported_as_drift() { + // The real composer over a real (InMemory) configuration: seal the current state, then edit the draft the + // way RawTreeService/UnsTreeService/ClusterEdit do — straight into the table, no ConfigEdit row. var name = $"drift-{Guid.NewGuid():N}"; var factory = UnsTreeTestDb.Factory(name); - var compose = new CountingCompose(SealedHash); - var probe = new DeploymentDriftProbe(factory, compose.ComposeAsync); + await using (var db = UnsTreeTestDb.CreateNamed(name)) + { + UnsTreeTestDb.Seed(db); + } - var first = await probe.GetDriftAsync(SealedHash, CancellationToken.None); - var second = await probe.GetDriftAsync(SealedHash, CancellationToken.None); + var sealedHash = await CurrentHashAsync(name); + var probe = new DeploymentDriftProbe(factory); - // Nothing mutated between the calls, so the second call must be served from the cache. - compose.Count.ShouldBe(1); - first.ShouldBe(false); - second.ShouldBe(false); + (await probe.GetDriftAsync(sealedHash, TestContext.Current.CancellationToken)).ShouldBe(false); + + await using (var db = UnsTreeTestDb.CreateNamed(name)) + { + db.ServerClusters.Add(new ServerCluster + { + ClusterId = "NEW-1", Name = "New", Enterprise = "zb", Site = "s9", + RedundancyMode = RedundancyMode.None, CreatedBy = "test", + }); + await db.SaveChangesAsync(TestContext.Current.CancellationToken); + db.ConfigEdits.Any().ShouldBeFalse(); // the precondition the old watermark cache missed + } + + (await probe.GetDriftAsync(sealedHash, TestContext.Current.CancellationToken)).ShouldBe(true); } [Fact] - public async Task A_new_config_edit_recomposes() + public async Task Sequential_calls_each_compose() { - var name = $"drift-{Guid.NewGuid():N}"; - var factory = UnsTreeTestDb.Factory(name); - var compose = new CountingCompose(SealedHash); - var probe = new DeploymentDriftProbe(factory, compose.ComposeAsync); - - var before = await probe.GetDriftAsync(SealedHash, CancellationToken.None); - before.ShouldBe(false); - - // An edit lands: the audit row moves the watermark, and the (faked) composer now reports a - // different revision — the probe must recompose and flip the verdict. - await using (var db = UnsTreeTestDb.CreateNamed(name)) - { - db.ConfigEdits.Add(new ConfigEdit - { - EntityType = "Equipment", - EntityId = Guid.NewGuid(), - FieldsJson = "{}", - EditedBy = "test", - SourceNode = "node-1", - EditedAtUtc = DateTime.UtcNow, - }); - await db.SaveChangesAsync(TestContext.Current.CancellationToken); - } + var compose = new GatedCompose(SealedHash, gated: false); + var probe = new DeploymentDriftProbe(UnsTreeTestDb.Factory($"drift-{Guid.NewGuid():N}"), compose.ComposeAsync); + (await probe.GetDriftAsync(SealedHash, TestContext.Current.CancellationToken)).ShouldBe(false); compose.Result = "a-different-hash"; - var after = await probe.GetDriftAsync(SealedHash, CancellationToken.None); + (await probe.GetDriftAsync(SealedHash, TestContext.Current.CancellationToken)).ShouldBe(true); compose.Count.ShouldBe(2); - after.ShouldBe(true); } - /// Stand-in for the ConfigComposer seam that counts how often it was invoked. - private sealed class CountingCompose(string result) + [Fact] + public async Task Callers_queued_behind_an_older_composition_do_not_reuse_it_but_share_a_fresh_one() { + var compose = new GatedCompose(SealedHash, gated: true); + var probe = new DeploymentDriftProbe(UnsTreeTestDb.Factory($"drift-{Guid.NewGuid():N}"), compose.ComposeAsync); + + // A starts composing and blocks inside the composer. + var a = probe.GetDriftAsync(SealedHash, TestContext.Current.CancellationToken); + await compose.WaitForStartAsync(1); + + // B and C ask while A's composition (which may predate their edits) is in flight. + compose.Result = "a-different-hash"; + var b = probe.GetDriftAsync(SealedHash, TestContext.Current.CancellationToken); + var c = probe.GetDriftAsync(SealedHash, TestContext.Current.CancellationToken); + + compose.Release(); + (await a).ShouldBe(false); + (await b).ShouldBe(true); // not A's stale answer + (await c).ShouldBe(true); + + compose.Count.ShouldBe(2); // A's, then ONE fresh composition shared by B and C + } + + private static async Task CurrentHashAsync(string name) + { + await using var db = UnsTreeTestDb.CreateNamed(name); + return (await ConfigComposer.SnapshotAndFlattenAsync(db)).RevisionHash; + } + + /// Stand-in for the ConfigComposer seam that counts calls and can hold them open. + private sealed class GatedCompose(string result, bool gated) + { + private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously); + private int _count; + public string Result { get; set; } = result; - public int Count { get; private set; } + public int Count => Volatile.Read(ref _count); - public Task ComposeAsync(OtOpcUaConfigDbContext db) + public void Release() => _release.TrySetResult(); + + public async Task WaitForStartAsync(int n) { - Count++; - return Task.FromResult(Result); + var deadline = DateTime.UtcNow.AddSeconds(10); + while (Count < n) + { + if (DateTime.UtcNow > deadline) throw new TimeoutException("composition never started"); + await Task.Delay(5); + } + } + + public async Task ComposeAsync(OtOpcUaConfigDbContext db) + { + var snapshot = Result; // what the configuration looked like when this composition read it + Interlocked.Increment(ref _count); + if (gated) await _release.Task; + return snapshot; } } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Deployments/DeploymentsPageDriftRenderTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Deployments/DeploymentsPageDriftRenderTests.cs new file mode 100644 index 000000000..fcb24795c --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Deployments/DeploymentsPageDriftRenderTests.cs @@ -0,0 +1,122 @@ +using Bunit; +using Microsoft.AspNetCore.Components.Authorization; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; +using Xunit; +using DeploymentsPage = ZB.MOM.WW.OtOpcUa.AdminUI.Components.Pages.Deployments; +using ZB.MOM.WW.OtOpcUa.AdminUI.Deployments; +using ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Uns; +using ZB.MOM.WW.OtOpcUa.Commons.Interfaces; +using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin; +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.AdminOperations; + +namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Deployments; + +/// +/// lmxopcua#903: after a draft change, /deployments sometimes said "In sync" on its first load and only showed +/// the drift after a refresh. The probe (a singleton shared by every circuit) served a verdict cached against a +/// ConfigEdit watermark that the AdminUI's own editors never move. The page must report the drift on the +/// load that follows the change, and must show a neutral "Checking" state — never a verdict — until it knows. +/// +[Trait("Category", "Unit")] +public sealed class DeploymentsPageDriftRenderTests : BunitContext +{ + private const string Chip = "[data-testid=drift-chip]"; + + private string Seed() + { + var name = $"deploy-page-{Guid.NewGuid():N}"; + using (var db = UnsTreeTestDb.CreateNamed(name)) + { + UnsTreeTestDb.Seed(db); + } + + string hash; + using (var db = UnsTreeTestDb.CreateNamed(name)) + { + hash = ConfigComposer.SnapshotAndFlattenAsync(db).GetAwaiter().GetResult().RevisionHash; + db.Deployments.Add(new Deployment + { + RevisionHash = hash, + Status = DeploymentStatus.Sealed, + CreatedBy = "test", + SealedAtUtc = DateTime.UtcNow, + }); + db.SaveChanges(); + } + + Services.AddSingleton(UnsTreeTestDb.Factory(name)); + Services.AddSingleton(new FakeAuth()); + Services.AddSingleton(new UnusedAdminOps()); + return name; + } + + [Fact] + public void A_draft_change_is_reported_on_the_next_page_load() + { + var name = Seed(); + Services.AddSingleton(sp => new DeploymentDriftProbe(sp.GetRequiredService>())); + + // Load 1: draft == sealed. + var first = Render(); + first.WaitForAssertion(() => first.Find(Chip).TextContent.ShouldBe("In sync")); + + // Edit the draft the way the AdminUI editors do: directly, with no ConfigEdit audit row. + using (var db = UnsTreeTestDb.CreateNamed(name)) + { + db.ServerClusters.Add(new ServerCluster + { + ClusterId = "NEW-1", Name = "New", Enterprise = "zb", Site = "s9", + RedundancyMode = RedundancyMode.None, CreatedBy = "test", + }); + db.SaveChanges(); + } + + // Load 2 (a new circuit, same singleton probe): must say drift, not the earlier verdict. + var second = Render(); + second.WaitForAssertion(() => second.Find(Chip).TextContent.ShouldBe("Configuration drift")); + } + + [Fact] + public void First_render_shows_checking_until_the_comparison_answers() + { + Seed(); + var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + Services.AddSingleton(sp => new DeploymentDriftProbe( + sp.GetRequiredService>(), + async _ => { await gate.Task; return "a-different-hash"; })); + + var cut = Render(); + + cut.Find(Chip).TextContent.ShouldStartWith("Checking"); + cut.Markup.ShouldNotContain("In sync"); + + gate.SetResult(); + cut.WaitForAssertion(() => cut.Find(Chip).TextContent.ShouldBe("Configuration drift")); + } + + private sealed class FakeAuth : AuthenticationStateProvider + { + public override Task GetAuthenticationStateAsync() => + Task.FromResult(new AuthenticationState(new System.Security.Claims.ClaimsPrincipal( + new System.Security.Claims.ClaimsIdentity("test")))); + } + + private sealed class UnusedAdminOps : IAdminOperationsClient + { + public Task StartDeploymentAsync(string createdBy, CancellationToken ct) => + throw new NotSupportedException(); + + public Task AcknowledgeAlarmAsync(string alarmId, string user, string? comment, CancellationToken ct) => + throw new NotSupportedException(); + + public Task ShelveAlarmAsync(string alarmId, string user, ShelveKind kind, DateTime? unshelveAtUtc, + string? comment, CancellationToken ct) => throw new NotSupportedException(); + + public Task AskAsync(object message, CancellationToken ct) => throw new NotSupportedException(); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ZB.MOM.WW.OtOpcUa.AdminUI.Tests.csproj b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ZB.MOM.WW.OtOpcUa.AdminUI.Tests.csproj index e23b45d82..fc150a1f5 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ZB.MOM.WW.OtOpcUa.AdminUI.Tests.csproj +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ZB.MOM.WW.OtOpcUa.AdminUI.Tests.csproj @@ -15,7 +15,7 @@ (TypeLoadException), so the advisory is suppressed here rather than overriding the version. --> -