Files
lmxopcua/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Deployments.razor
T

284 lines
12 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
@implements IDisposable
<PageErrorBoundary>
<PageTitle>Deployments · OtOpcUa</PageTitle>
<div class="page-head"><h1>Deployments</h1></div>
<div class="d-flex flex-wrap align-items-center gap-3 mb-3">
<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
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">Drift check failed</span>
<span class="small text-muted">Refresh status to retry. See the host log for details.</span>
break;
}
</div>
<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)
{
<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>
<tr>
<th scope="col">Deployment</th>
<th scope="col">Revision</th>
<th scope="col">Status</th>
<th scope="col">Created by</th>
<th scope="col">Created (UTC)</th>
<th scope="col">Sealed (UTC)</th>
</tr>
</thead>
<tbody>
@foreach (var d in _deployments)
{
<tr>
<th scope="row"><code>@Short(d.DeploymentId)</code></th>
<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>
@(d.Status == DeploymentStatus.Sealed && !string.IsNullOrEmpty(d.FailureReason) ? "Sealed (degraded)" : d.Status.ToString())
@if (!string.IsNullOrEmpty(d.FailureReason)) { <DiagnosticDetails Summary="Failure reason" Text="@d.FailureReason" /> }
</td>
<td>@d.CreatedBy</td>
<td>@d.CreatedAtUtc.ToString("u")</td>
<td>@(d.SealedAtUtc?.ToString("u") ?? "—")</td>
</tr>
}
</tbody>
</table>
</div>
}
</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, _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;
// 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)
{
// 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
{
_refreshing = false;
if (!_disposed) StateHasChanged();
}
}
private async Task RefreshDriftAsync()
{
if (_disposed) return;
_initialDriftPending = false;
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, _reads.Token);
if (_disposed) return;
_driftState = drift switch
{
true => DriftState.Drift,
false => DriftState.InSync,
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<bool> ReloadAsync()
{
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; }
}
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()
{
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)";
// 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)
{
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();
}
}