Files
lmxopcua/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Deployments.razor
T
Joseph Doherty 35576485b1
v2-ci / unit-tests (push) Has been cancelled
fix(adminui): deployments drift chip never serves a stale "In sync" (#903)
Root cause: DeploymentDriftProbe (a singleton shared by every circuit) cached its verdict until
the ConfigEdit audit watermark (MAX(EditedAtUtc), COUNT(*)) moved, assuming every configuration
write appends a ConfigEdit row. Only deployments and driver restart/reconnect do; the AdminUI
editors (RawTreeService, UnsTreeService, ScriptEdit, cluster/node/ACL pages) write the config
tables directly. So after a draft change the page kept showing the cached "In sync" until
something unrelated moved the watermark.

- DeploymentDriftProbe: the watermark cache is gone; every verdict comes from a composition that
  started after the caller asked. Compositions stay serialised behind the gate, and callers queued
  behind one share a verdict only when that composition started after they arrived (start
  sequence number) for the same sealed hash, so sharing is exact, never stale.
- Deployments page: the drift check runs in OnAfterRenderAsync (interactive render only, so a
  visit costs one composition, not two with prerender); the first render shows a neutral
  "Checking for changes..." chip, never a verdict; a failed check shows "Drift check failed" and
  logs a warning instead of crashing the page. A deploy re-runs the check.
- Tests: probe tests for an un-audited draft change (real ConfigComposer over InMemory), fresh
  composition per call, and queued callers not reusing an older composition; bUnit page tests that
  a second page load after a direct draft change shows "Configuration drift" and that the first
  render shows "Checking" until the comparison answers. All fail against the previous code.
  DeploymentDriftProbeSqlServerTests is removed: it pinned the SQL translation of the watermark
  query, which no longer exists.

Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
2026-11-13 01:50:37 -05:00

206 lines
7.4 KiB
Plaintext

@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
@using ZB.MOM.WW.OtOpcUa.Configuration.Entities
@using ZB.MOM.WW.OtOpcUa.Configuration.Enums
@attribute [Authorize(Policy = AdminUiPolicies.ConfigEditor)]
@inject IDbContextFactory<OtOpcUaConfigDbContext> DbFactory
@inject IAdminOperationsClient AdminOps
@inject AuthenticationStateProvider AuthState
@inject ZB.MOM.WW.OtOpcUa.AdminUI.Deployments.DeploymentDriftProbe DriftProbe
@inject ILogger<Deployments> Logger
@rendermode InteractiveServer
<PageErrorBoundary>
<PageTitle>Deployments</PageTitle>
<h1>Deployments</h1>
<div class="d-flex align-items-center gap-3 mb-3">
<button class="btn btn-primary" @onclick="StartDeploymentAsync" disabled="@_busy">
@(_busy ? "Deploying…" : "Deploy current configuration")
</button>
@* 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)
{
case DriftState.Checking:
<span class="badge bg-secondary" data-testid="drift-chip" role="status">Checking for changes…</span>
break;
case DriftState.Drift:
<span class="badge bg-warning text-dark" data-testid="drift-chip">Configuration drift</span>
break;
case DriftState.InSync:
<span class="badge bg-success" data-testid="drift-chip">In sync</span>
break;
case DriftState.Failed:
<span class="badge bg-secondary" data-testid="drift-chip" title="See the host log">Drift check failed</span>
break;
}
</div>
@if (_lastMessage is not null)
{
<div class="alert @(_lastSuccess ? "alert-success" : "alert-danger")">
@_lastMessage
</div>
}
<table class="table table-striped table-sm">
<thead>
<tr>
<th>Deployment</th>
<th>Revision</th>
<th>Status</th>
<th>Created by</th>
<th>Created (UTC)</th>
<th>Sealed (UTC)</th>
</tr>
</thead>
<tbody>
@foreach (var d in _deployments)
{
<tr>
<td><code>@Short(d.DeploymentId)</code></td>
<td><code>@DisplayText.Abbreviate(d.RevisionHash, 12)</code></td>
@* #601: Sealed + a reason = sealed with a degraded address-space apply on some node(s). *@
<td title="@(d.FailureReason ?? "")">@(d.Status == DeploymentStatus.Sealed && !string.IsNullOrEmpty(d.FailureReason) ? "Sealed (degraded)" : d.Status.ToString())</td>
<td>@d.CreatedBy</td>
<td>@d.CreatedAtUtc.ToString("u")</td>
<td>@(d.SealedAtUtc?.ToString("u") ?? "—")</td>
</tr>
}
</tbody>
</table>
</PageErrorBoundary>
@code {
// Blob-free projection: the Deployment entity carries a varbinary(max) ArtifactBlob (a whole-fleet
// gzip config snapshot), which materialising the full entity would drag across the wire 50 times
// over just to render six scalar columns.
private sealed record DeploymentRow(
Guid DeploymentId,
string RevisionHash,
DeploymentStatus Status,
string CreatedBy,
DateTime CreatedAtUtc,
DateTime? SealedAtUtc,
string? FailureReason);
private IReadOnlyList<DeploymentRow> _deployments = Array.Empty<DeploymentRow>();
private bool _busy;
private bool _lastSuccess;
private string? _lastMessage;
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();
_deployments = await db.Deployments
.AsNoTracking()
.OrderByDescending(d => d.CreatedAtUtc)
.Select(d => new DeploymentRow(
d.DeploymentId,
d.RevisionHash,
d.Status,
d.CreatedBy,
d.CreatedAtUtc,
d.SealedAtUtc,
d.FailureReason))
.Take(50)
.ToListAsync();
// 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()
{
_busy = true;
_lastMessage = null;
try
{
var auth = await AuthState.GetAuthenticationStateAsync();
var createdBy = auth.User.Identity?.Name ?? "(anonymous)";
var result = await AdminOps.StartDeploymentAsync(
createdBy: createdBy,
ct: CancellationToken.None);
_lastSuccess = result.Outcome == StartDeploymentOutcome.Accepted;
_lastMessage = result.Outcome switch
{
StartDeploymentOutcome.Accepted => $"Deployment {Short(result.DeploymentId!.Value.Value)} dispatched (rev {DisplayText.Abbreviate(result.RevisionHash!.Value.Value, 12)}).",
StartDeploymentOutcome.AnotherDeploymentInFlight => result.Message ?? "Another deployment is already in flight.",
StartDeploymentOutcome.NoChanges => "No changes detected since the last sealed deployment.",
_ => result.Message ?? "Deployment rejected.",
};
await ReloadAsync();
await RefreshDriftAsync();
}
catch (Exception ex)
{
_lastSuccess = false;
_lastMessage = $"Deploy failed: {ex.Message}";
}
finally
{
_busy = false;
}
}
private static string Short(Guid id) => id.ToString("N")[..8];
}