fix(admin-ui): distinguish deployment acceptance and application progress

This commit is contained in:
Joseph Doherty
2026-11-13 23:22:22 -05:00
parent 43a3512baf
commit f7bc69e9c3
49 changed files with 2530 additions and 69 deletions
@@ -16,6 +16,7 @@
@inject ZB.MOM.WW.OtOpcUa.AdminUI.Deployments.DeploymentDriftProbe DriftProbe
@inject ILogger<Deployments> Logger
@rendermode InteractiveServer
@implements IDisposable
<PageErrorBoundary>
<PageTitle>Deployments · OtOpcUa</PageTitle>
@@ -23,8 +24,13 @@
<div class="page-head"><h1>Deployments</h1></div>
<div class="d-flex flex-wrap align-items-center gap-3 mb-3">
<button class="btn btn-primary" @onclick="StartDeploymentAsync" disabled="@_busy">
@(_busy ? "Deploying…" : "Deploy current configuration")
<button type="button" class="btn btn-primary" data-testid="deployment-request" @onclick="StartDeploymentAsync"
disabled="@(_busy || _refreshing || _loading || !_hasLoaded)" aria-busy="@(_requestPending ? "true" : "false")">
@(_requestPending ? "Requesting…" : "Deploy current configuration")
</button>
<button type="button" class="btn btn-outline-secondary" data-testid="deployment-refresh" @onclick="RefreshStatusAsync"
disabled="@(_busy || _refreshing || _loading)" aria-busy="@(_refreshing ? "true" : "false")">
@(_refreshing ? "Refreshing…" : "Refresh status")
</button>
@* lmxopcua#903: the chip says nothing about sync until a composition taken after this page opened has
@@ -41,18 +47,35 @@
<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>
<span class="badge bg-secondary" data-testid="drift-chip">Drift check failed</span>
<span class="small text-muted">Refresh status to retry. See the host log for details.</span>
break;
}
</div>
@if (_lastMessage is not null)
<div class="d-flex flex-wrap align-items-center gap-3 mb-3">
<span class="small text-muted">Last fetched: <time data-testid="deployment-last-fetched" datetime="@(_lastFetchedUtc?.ToString("O"))">@(_lastFetchedUtc?.ToString("yyyy-MM-dd HH:mm:ss 'UTC'") ?? "not yet available")</time></span>
@if (_loading && _hasLoaded) { <span class="small text-muted">Reading deployment history…</span> }
<a href="/fleet">View per-node application status</a>
</div>
@if (_requestedDeploymentId is { } requested)
{
<div class="alert @(_lastSuccess ? "alert-success" : "alert-danger")">
@_lastMessage
</div>
<p class="small">Requested deployment: <code class="text-break">@requested</code></p>
@if (_requestedRevisionHash is not null) { <p class="small">Requested revision: <code class="text-break">@_requestedRevisionHash</code></p> }
}
<DeploymentFeedback RequestOutcome="@_requestOutcome" RequestPending="@_requestPending" RequestResultUnavailable="@_requestResultUnavailable"
RequestMessage="@_requestMessage" Status="@(FeedbackRow?.Status)" FailureReason="@(FeedbackRow?.FailureReason)"
InitialLoading="@(_loading && !_hasLoaded)" HistoryAvailable="@_hasLoaded"
ContextLabel="@(_requestOutcome == StartDeploymentOutcome.Accepted ? "Requested deployment" : "Most recent recorded deployment")" />
@if (_loadError is not null)
{
<section class="panel notice notice-alert p-3 mb-3" aria-label="History refresh error">
<p class="mb-2" role="alert">History refresh failed. @(_hasLoaded ? "Showing the last successful reading." : "No history reading is available.")</p>
<DiagnosticDetails Summary="History read error" Text="@_loadError" />
</section>
}
@if (_deployments.Count > 0)
{
<div class="table-wrap" role="region" aria-label="Deployment history" tabindex="0">
<table class="data-table">
<thead>
@@ -84,6 +107,7 @@
</tbody>
</table>
</div>
}
</PageErrorBoundary>
@code {
@@ -100,43 +124,49 @@
string? FailureReason);
private IReadOnlyList<DeploymentRow> _deployments = Array.Empty<DeploymentRow>();
private bool _busy;
private bool _lastSuccess;
private string? _lastMessage;
private bool _busy, _refreshing, _requestPending, _requestResultUnavailable;
private bool _loading = true, _hasLoaded, _disposed;
private bool _initialDriftPending = true;
private StartDeploymentOutcome? _requestOutcome;
private Guid? _requestedDeploymentId;
private string? _requestMessage, _loadError, _requestedRevisionHash;
private DateTime? _lastFetchedUtc;
private readonly CancellationTokenSource _reads = new();
private enum DriftState { None, Checking, Drift, InSync, Failed }
private DriftState _driftState;
protected override async Task OnInitializedAsync()
{
await ReloadAsync();
}
// A newly accepted request never borrows another historical deployment's terminal status.
private DeploymentRow? FeedbackRow => _requestOutcome == StartDeploymentOutcome.Accepted
? _deployments.FirstOrDefault(d => d.DeploymentId == _requestedDeploymentId)
: _deployments.FirstOrDefault();
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)
// Compose only after interactive attachment, as before; serialize it with user actions.
if (!_initialDriftPending || _disposed || !_hasLoaded || _busy || _refreshing) return;
_initialDriftPending = false;
_refreshing = true;
StateHasChanged();
try { await RefreshDriftAsync(); }
finally
{
await RefreshDriftAsync();
StateHasChanged();
_refreshing = false;
if (!_disposed) 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.
if (_disposed) return;
_initialDriftPending = false;
var latestSealed = _deployments.FirstOrDefault(d => d.Status == DeploymentStatus.Sealed);
if (latestSealed is null)
{
_driftState = DriftState.None;
return;
}
if (latestSealed is null) { _driftState = DriftState.None; return; }
try
{
var drift = await DriftProbe.GetDriftAsync(latestSealed.RevisionHash, CancellationToken.None);
var drift = await DriftProbe.GetDriftAsync(latestSealed.RevisionHash, _reads.Token);
if (_disposed) return;
_driftState = drift switch
{
true => DriftState.Drift,
@@ -144,67 +174,110 @@
null => DriftState.None,
};
}
catch (OperationCanceledException) when (_disposed) { }
catch (Exception ex)
{
if (_disposed) return;
Logger.LogWarning(ex, "Deployments: drift check against revision {RevisionHash} failed.", latestSealed.RevisionHash);
_driftState = DriftState.Failed;
}
}
private async Task ReloadAsync()
private async Task<bool> 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();
if (_disposed) return false;
var cancellation = _reads.Token;
_loading = true;
_loadError = null;
StateHasChanged();
try
{
await using var db = await DbFactory.CreateDbContextAsync(cancellation);
var rows = 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(cancellation);
if (_disposed) return false;
_deployments = rows;
_hasLoaded = true;
_lastFetchedUtc = DateTime.UtcNow;
// Only these successful rows establish the next drift check's context.
_driftState = rows.Any(d => d.Status == DeploymentStatus.Sealed) ? DriftState.Checking : DriftState.None;
return true;
}
catch (OperationCanceledException) when (_disposed) { return false; }
catch (Exception ex)
{
if (!_disposed)
{
_loadError = ex.Message;
Logger.LogWarning(ex, "Deployments: history refresh failed; preserving last successful rows.");
}
return false;
}
finally { _loading = false; }
}
// 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 RefreshStatusAsync()
{
if (_disposed || _busy || _refreshing || _loading) return;
_refreshing = true;
try { if (await ReloadAsync()) await RefreshDriftAsync(); }
finally { _refreshing = false; }
}
private async Task StartDeploymentAsync()
{
_busy = true;
_lastMessage = null;
if (_disposed || _busy || _refreshing || _loading || !_hasLoaded) return;
_busy = _requestPending = true;
_requestOutcome = null;
_requestedDeploymentId = null;
_requestedRevisionHash = null;
_requestMessage = null;
_requestResultUnavailable = false;
try
{
var auth = await AuthState.GetAuthenticationStateAsync();
if (_disposed) return;
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();
// A dispatched mutation continues if the view closes; only history reads use page cancellation.
var result = await AdminOps.StartDeploymentAsync(createdBy: createdBy, ct: CancellationToken.None);
if (_disposed) return;
_requestPending = false;
_requestOutcome = result.Outcome;
_requestMessage = result.Message;
_requestedDeploymentId = result.Outcome == StartDeploymentOutcome.Accepted ? result.DeploymentId?.Value : null;
_requestedRevisionHash = result.Outcome == StartDeploymentOutcome.Accepted ? result.RevisionHash?.Value : null;
// A failed follow-up read cannot retroactively turn an accepted request into rejection.
if (await ReloadAsync()) await RefreshDriftAsync();
}
catch (Exception ex)
{
_lastSuccess = false;
_lastMessage = $"Deploy failed: {ex.Message}";
}
finally
{
_busy = false;
if (_disposed) return;
_requestResultUnavailable = true;
_requestMessage = ex.Message;
Logger.LogWarning(ex, "Deployments: request result could not be confirmed.");
}
finally { _busy = _requestPending = false; }
}
private static string Short(Guid id) => id.ToString("N")[..8];
/// <summary>Stops view-owned reads without cancelling an already-dispatched deployment request.</summary>
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_reads.Cancel();
_reads.Dispose();
}
}
@@ -0,0 +1,108 @@
@using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin
@using ZB.MOM.WW.OtOpcUa.Configuration.Enums
<section class="panel p-3 mb-3" aria-label="Deployment feedback">
<div role="status" aria-live="polite" aria-atomic="true">
@if (InitialLoading)
{
<p class="mb-0">Loading deployment history…</p>
}
else
{
@if (RequestPending)
{
<p class="mb-2">Waiting for request acceptance…</p>
}
else if (RequestResultUnavailable)
{
<p class="mb-2">The request result could not be confirmed. Refresh status before retrying.</p>
}
else if (RequestOutcome == StartDeploymentOutcome.Accepted)
{
<p class="mb-2">@(Status is null or DeploymentStatus.Dispatching or DeploymentStatus.AwaitingApplyAcks ? "Request accepted — deployment in progress." : "Request accepted.")</p>
}
else if (RequestOutcome == StartDeploymentOutcome.NoChanges)
{
<p class="mb-2">No configuration changes; no new deployment was requested.</p>
}
else if (RequestOutcome == StartDeploymentOutcome.AnotherDeploymentInFlight)
{
<p class="mb-2">Another deployment is already in progress. This request was not started.</p>
}
else if (RequestOutcome == StartDeploymentOutcome.Rejected)
{
<p class="mb-2">Request rejected. @(string.IsNullOrEmpty(RequestMessage) ? "No reason was supplied." : "Open the request details below for the recorded reason.")</p>
}
@if (!HistoryAvailable)
{
<p class="mb-0">Deployment history is unavailable. Refresh to try again.</p>
}
else if (Status is not null)
{
<div>
@ContextLabel: <StatusPill State="@RecordedState">@(Status == DeploymentStatus.AwaitingApplyAcks ? "Awaiting acks" : RecordedLabel)</StatusPill>
@if (Status == DeploymentStatus.AwaitingApplyAcks)
{
<div class="small">Awaiting apply acknowledgements</div>
}
</div>
}
else if (RequestOutcome == StartDeploymentOutcome.Accepted)
{
<p class="mb-0">The requested deployment status is not yet observed in the loaded history. Refresh status to check application progress.</p>
}
else
{
<p class="mb-0">No deployment history recorded.</p>
}
}
</div>
@* Full diagnostics are outside the live region: opening one must not announce an entire payload. *@
@if (!string.IsNullOrEmpty(RequestMessage))
{
<div class="mt-2"><DiagnosticDetails Summary="Request details" Text="@RequestMessage" /></div>
}
@if (!string.IsNullOrEmpty(FailureReason))
{
<div class="mt-2"><DiagnosticDetails Summary="Application failure details" Text="@FailureReason" /></div>
}
</section>
@code {
/// <summary>The actual actor reply outcome, absent before a confirmed reply.</summary>
[Parameter] public StartDeploymentOutcome? RequestOutcome { get; set; }
/// <summary>True only while waiting for the request reply, not while application proceeds.</summary>
[Parameter] public bool RequestPending { get; set; }
/// <summary>A transport failure left the reply unknown; it does not establish server rejection.</summary>
[Parameter] public bool RequestResultUnavailable { get; set; }
/// <summary>Complete existing request metadata, disclosed outside the short live outcome.</summary>
[Parameter] public string? RequestMessage { get; set; }
/// <summary>The recorded status of the explicitly named loaded deployment.</summary>
[Parameter] public DeploymentStatus? Status { get; set; }
/// <summary>Complete recorded application failure metadata, including sealed degradation.</summary>
[Parameter] public string? FailureReason { get; set; }
/// <summary>The initial history query is still pending, distinct from a confirmed empty read.</summary>
[Parameter] public bool InitialLoading { get; set; }
/// <summary>Whether any history read has succeeded; false avoids inventing an empty history.</summary>
[Parameter] public bool HistoryAvailable { get; set; } = true;
/// <summary>Identifies whose recorded status is shown, e.g. the requested deployment.</summary>
[Parameter] public string ContextLabel { get; set; } = "Most recent recorded deployment";
private string RecordedLabel => Status switch
{
DeploymentStatus.Dispatching => "Dispatching",
DeploymentStatus.AwaitingApplyAcks => "Awaiting apply acknowledgements",
DeploymentStatus.Sealed when !string.IsNullOrEmpty(FailureReason) => "Sealed (degraded)",
DeploymentStatus.Sealed => "Sealed",
DeploymentStatus.PartiallyFailed => "Partially failed",
DeploymentStatus.TimedOut => "Timed out",
_ => $"Unknown status ({(int?)Status})",
};
private StatusState RecordedState => Status switch
{
DeploymentStatus.Sealed when string.IsNullOrEmpty(FailureReason) => StatusState.Ok,
DeploymentStatus.Sealed => StatusState.Warn,
DeploymentStatus.PartiallyFailed or DeploymentStatus.TimedOut => StatusState.Bad,
DeploymentStatus.Dispatching or DeploymentStatus.AwaitingApplyAcks => StatusState.Info,
_ => StatusState.Idle,
};
}