Files
ScadaBridge/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Deployment/DebugView.razor
T
Joseph Doherty d160c7f694 test(communication): M2.11 review nits — bridge-actor not-found test + dead-letter comment + toast wording (#24)
- Add DebugStreamBridgeActorTests: On_InstanceNotFound_Snapshot_Forwards_To_OnEvent_Does_Not_Open_Stream_And_Terminates — asserts _onEvent receives the not-found snapshot, SubscribeCalls remains empty, and the actor terminates cleanly via Watch/ExpectTerminated.
- Add comment in DebugStreamBridgeActor near Context.Stop(Self) explaining that the subsequent StopDebugStream Tell from DebugStreamService.StopStream produces a benign expected dead-letter.
- Reword not-found toast in DebugView.razor to "Instance not found on the selected site — check the deployment target." (accurate when the instance may be deployed to a different site).
2026-06-16 06:15:26 -04:00

690 lines
31 KiB
Plaintext

@page "/deployment/debug-view"
@using ZB.MOM.WW.ScadaBridge.Security
@using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances
@using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites
@using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories
@using ZB.MOM.WW.ScadaBridge.Commons.Messages.DebugView
@using ZB.MOM.WW.ScadaBridge.Commons.Messages.Streaming
@using ZB.MOM.WW.ScadaBridge.Commons.Types
@using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums
@using ZB.MOM.WW.ScadaBridge.Communication
@attribute [Authorize(Policy = AuthorizationPolicies.RequireDeployment)]
@inject ITemplateEngineRepository TemplateEngineRepository
@inject ISiteRepository SiteRepository
@inject ZB.MOM.WW.ScadaBridge.CentralUI.Auth.SiteScopeService SiteScope
@inject DebugStreamService DebugStreamService
@inject IJSRuntime JS
@implements IDisposable
<div class="container-fluid mt-3">
<h4 class="mb-3">Debug View</h4>
<ToastNotification @ref="_toast" />
@if (_loading)
{
<LoadingSpinner IsLoading="true" />
}
else
{
@* Status strip — connection state, instance, last snapshot. *@
<div class="alert alert-light py-2 mb-3 d-flex justify-content-between align-items-center small flex-wrap gap-2">
<div class="d-flex align-items-center gap-2">
<strong>
@if (_connected)
{
var inst = _siteInstances.FirstOrDefault(i => i.Id == _selectedInstanceId);
@(inst?.UniqueName ?? "Connected")
}
else
{
<span class="text-muted">Not connected</span>
}
</strong>
@if (_connected)
{
<span class="badge bg-success" aria-label="Connection state: Live">
<span class="spinner-grow spinner-grow-sm me-1" style="width: 0.5rem; height: 0.5rem;" aria-hidden="true"></span>
Live
</span>
}
else
{
<span class="badge bg-secondary" aria-label="Connection state: Disconnected">Disconnected</span>
}
</div>
<div class="d-flex align-items-center gap-2">
@if (_snapshot != null)
{
<span class="text-muted">
Last snapshot: @_snapshot.SnapshotTimestamp.LocalDateTime.ToString("HH:mm:ss")
</span>
}
@if (_connected && _connectedFromStorage)
{
<button class="btn btn-outline-secondary btn-sm" @onclick="StartFresh"
aria-label="Clear persisted selection and disconnect">Start fresh</button>
}
</div>
</div>
<div class="row mb-3 g-2">
<div class="col-md-3">
<label class="form-label small">Site</label>
<select class="form-select form-select-sm" data-test="debug-site-select"
@bind="_selectedSiteId" @bind:after="LoadInstancesForSite" disabled="@_connected">
<option value="0">Select site...</option>
@foreach (var site in _sites)
{
<option value="@site.Id">@site.Name (@site.SiteIdentifier)</option>
}
</select>
</div>
<div class="col-md-4">
<label class="form-label small">Instance</label>
<select class="form-select form-select-sm" data-test="debug-instance-select"
@bind="_selectedInstanceId" @bind:after="OnInstanceSelectionChanged" disabled="@_connected">
<option value="0">Select instance...</option>
@foreach (var inst in _siteInstances)
{
<option value="@inst.Id">@inst.UniqueName (@inst.State)</option>
}
</select>
</div>
<div class="col-md-3 d-flex align-items-end gap-2">
@if (!_connected)
{
<button class="btn btn-primary btn-sm" @onclick="Connect"
disabled="@(_selectedInstanceId == 0 || _selectedSiteId == 0 || _connecting)">
@if (_connecting) { <span class="spinner-border spinner-border-sm me-1" role="status" aria-label="Connecting"></span> }
Connect
</button>
}
else
{
<button class="btn btn-outline-danger btn-sm" @onclick="Disconnect">Disconnect</button>
}
</div>
</div>
@if (_connected && _snapshot != null)
{
<div class="row">
@* Attribute Values *@
<div class="col-md-7">
<div class="card">
<div class="card-header py-2 d-flex justify-content-between align-items-center flex-wrap gap-2">
<div class="d-flex align-items-center gap-2">
<strong>Attribute Values</strong>
<small class="text-muted">@FilteredAttributeValues.Count latest (cap @MaxRows)</small>
</div>
<div class="d-flex align-items-center gap-2">
<input type="text" class="form-control form-control-sm"
style="max-width: 240px;"
placeholder="Filter by attribute…"
@bind="_attrFilter" @bind:event="oninput" aria-label="Filter attributes" />
<button class="btn btn-link btn-sm py-0" type="button"
@onclick="() => _attrScrollLocked = !_attrScrollLocked"
aria-pressed="@(_attrScrollLocked ? "true" : "false")"
aria-label="@(_attrScrollLocked ? "Scroll locked" : "Auto-scroll enabled")">
@(_attrScrollLocked ? "🔒 Locked" : "🔓 Auto-scroll")
</button>
<button class="btn btn-outline-secondary btn-sm" type="button"
@onclick="ClearAttributes" aria-label="Clear attribute table">Clear</button>
</div>
</div>
<div class="card-body p-0" style="max-height: 500px; overflow-y: auto;">
<table class="table table-sm table-striped mb-0">
<thead class="table-light sticky-top">
<tr>
<th>Attribute</th>
<th>Value</th>
<th>Quality</th>
<th>Timestamp</th>
</tr>
</thead>
<tbody aria-live="polite" aria-atomic="false">
@foreach (var av in FilteredAttributeValues)
{
<tr>
<td class="small">@av.AttributeName</td>
<td class="small font-monospace"><strong>@ValueFormatter.FormatDisplayValue(av.Value)</strong></td>
<td>
<span class="badge @GetQualityBadge(av.Quality)"
aria-label="@($"Quality: {av.Quality}")">@av.Quality</span>
</td>
<td class="small text-muted"
title="@av.Timestamp.LocalDateTime.ToString("HH:mm:ss.fff")">
@av.Timestamp.LocalDateTime.ToString("HH:mm:ss")
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</div>
@* Alarm States *@
<div class="col-md-5">
<div class="card">
<div class="card-header py-2 d-flex justify-content-between align-items-center flex-wrap gap-2">
<div class="d-flex align-items-center gap-2">
<strong>Alarm States</strong>
<small class="text-muted">@FilteredAlarmStates.Count latest (cap @MaxRows)</small>
</div>
<div class="d-flex align-items-center gap-2">
<input type="text" class="form-control form-control-sm"
style="max-width: 240px;"
placeholder="Filter by alarm…"
@bind="_alarmFilter" @bind:event="oninput" aria-label="Filter alarms" />
<button class="btn btn-link btn-sm py-0" type="button"
@onclick="() => _alarmScrollLocked = !_alarmScrollLocked"
aria-pressed="@(_alarmScrollLocked ? "true" : "false")"
aria-label="@(_alarmScrollLocked ? "Scroll locked" : "Auto-scroll enabled")">
@(_alarmScrollLocked ? "🔒 Locked" : "🔓 Auto-scroll")
</button>
<button class="btn btn-outline-secondary btn-sm" type="button"
@onclick="ClearAlarms" aria-label="Clear alarm table">Clear</button>
</div>
</div>
<div class="card-body p-0" style="max-height: 500px; overflow-y: auto;">
<table class="table table-sm table-striped mb-0">
<thead class="table-light sticky-top">
<tr>
<th>Alarm</th>
<th>Kind</th>
<th>State</th>
<th>Sev</th>
<th>Level</th>
<th>Timestamp</th>
</tr>
</thead>
<tbody aria-live="polite" aria-atomic="false">
@foreach (var alarm in FilteredAlarmStates)
{
<tr class="@GetAlarmRowClass(alarm.State)"
title="@BuildAlarmTooltip(alarm)">
<td class="small">
@alarm.AlarmName
@if (!string.IsNullOrEmpty(alarm.Message))
{
<span class="ms-1 text-info" aria-label="Has operator message">💬</span>
}
@if (!string.IsNullOrEmpty(alarm.SourceReference))
{
<div class="text-muted font-monospace text-truncate" style="font-size: .7rem; max-width: 180px;"
title="@alarm.SourceReference">@alarm.SourceReference</div>
}
</td>
<td>
<span class="badge @GetKindBadge(alarm.Kind)"
aria-label="@($"Alarm kind: {alarm.Kind}")">@FormatKind(alarm.Kind)</span>
</td>
<td>
<span class="badge @GetAlarmStateBadge(alarm.State)"
aria-label="@($"Alarm state: {alarm.State}")">@alarm.State</span>
@if (alarm.Kind != AlarmKind.Computed)
{
@if (alarm.Condition.Active && !alarm.Condition.Acknowledged)
{
<span class="badge bg-warning text-dark ms-1" aria-label="Unacknowledged">Unacked</span>
}
@if (alarm.Condition.Shelve != AlarmShelveState.Unshelved)
{
<span class="badge bg-info text-dark ms-1" title="@alarm.Condition.Shelve"
aria-label="@($"Shelved: {alarm.Condition.Shelve}")">Shelved</span>
}
@if (alarm.Condition.Suppressed)
{
<span class="badge bg-info text-dark ms-1" aria-label="Suppressed">Suppressed</span>
}
}
</td>
<td class="small font-monospace">@alarm.Condition.Severity</td>
<td>
@if (alarm.Level != AlarmLevel.None)
{
<span class="badge @GetAlarmLevelBadge(alarm.Level)"
aria-label="@($"Alarm level: {alarm.Level}")">@FormatLevel(alarm.Level)</span>
}
else
{
<span class="text-muted small">—</span>
}
</td>
<td class="small text-muted"
title="@alarm.Timestamp.LocalDateTime.ToString("HH:mm:ss.fff")">
@alarm.Timestamp.LocalDateTime.ToString("HH:mm:ss")
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</div>
</div>
}
else if (_connected)
{
<LoadingSpinner IsLoading="true" Message="Waiting for snapshot..." />
}
}
</div>
@code {
private const int MaxRows = 200;
[SupplyParameterFromQuery] public int? SiteId { get; set; }
[SupplyParameterFromQuery] public int? InstanceId { get; set; }
private List<Site> _sites = new();
private List<Instance> _siteInstances = new();
private int _selectedSiteId;
private int _selectedInstanceId;
private bool _loading = true;
private bool _connected;
private bool _connecting;
private bool _connectedFromStorage;
private DebugViewSnapshot? _snapshot;
// Keyed dictionaries hold the latest value per attribute/alarm; insertion order
// is preserved so we can trim the oldest when the count exceeds MaxRows.
private Dictionary<string, AttributeValueChanged> _attributeValues = new();
private Dictionary<string, AlarmStateChanged> _alarmStates = new();
// Filters and scroll-lock state per table.
private string _attrFilter = string.Empty;
private string _alarmFilter = string.Empty;
private bool _attrScrollLocked;
private bool _alarmScrollLocked;
private IReadOnlyList<AttributeValueChanged> FilteredAttributeValues =>
string.IsNullOrWhiteSpace(_attrFilter)
? _attributeValues.Values.OrderBy(a => a.AttributeName).ToList()
: _attributeValues.Values
.Where(a => a.AttributeName.Contains(_attrFilter, StringComparison.OrdinalIgnoreCase))
.OrderBy(a => a.AttributeName)
.ToList();
private IReadOnlyList<AlarmStateChanged> FilteredAlarmStates =>
string.IsNullOrWhiteSpace(_alarmFilter)
? _alarmStates.Values.OrderBy(a => a.AlarmName).ToList()
: _alarmStates.Values
.Where(a => a.AlarmName.Contains(_alarmFilter, StringComparison.OrdinalIgnoreCase)
|| a.SourceReference.Contains(_alarmFilter, StringComparison.OrdinalIgnoreCase))
.OrderBy(a => a.AlarmName)
.ToList();
private DebugStreamSession? _session;
private ToastNotification _toast = default!;
private string? _initError;
// CentralUI-009: the stream callbacks (onEvent/onTerminated) run on an
// Akka/gRPC thread and capture `this` and `_toast`. Once the component is
// disposed, an in-flight callback must no-op rather than touch a disposed
// component (InvokeAsync would throw ObjectDisposedException) or a disposed
// ToastNotification.
private volatile bool _disposed;
protected override async Task OnInitializedAsync()
{
try
{
// Site scoping (CentralUI-002): a scoped Deployment user may only
// debug sites they are permitted on.
_sites = await SiteScope.FilterSitesAsync(await SiteRepository.GetAllSitesAsync());
}
catch (Exception ex)
{
_initError = $"Failed to load sites: {ex.Message}";
}
_loading = false;
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (!firstRender) return;
if (_initError != null)
{
_toast.ShowError(_initError);
_initError = null;
}
if (SiteId is > 0 && InstanceId is > 0)
{
_selectedSiteId = SiteId.Value;
await LoadInstancesForSite();
if (_siteInstances.Any(i => i.Id == InstanceId.Value))
{
_selectedInstanceId = InstanceId.Value;
await Connect();
}
else
{
_toast.ShowError("Requested instance is not available for debug streaming.");
}
StateHasChanged();
return;
}
var storedSiteId = await JS.InvokeAsync<string>("localStorage.getItem", "debugView.siteId");
var storedInstanceId = await JS.InvokeAsync<string>("localStorage.getItem", "debugView.instanceId");
if (!string.IsNullOrEmpty(storedSiteId) && int.TryParse(storedSiteId, out var siteId)
&& !string.IsNullOrEmpty(storedInstanceId) && int.TryParse(storedInstanceId, out var instanceId))
{
_selectedSiteId = siteId;
await LoadInstancesForSite();
_selectedInstanceId = instanceId;
_connectedFromStorage = true;
StateHasChanged();
await Connect();
// Auto-reconnect notice — the user didn't initiate this connection.
var inst = _siteInstances.FirstOrDefault(i => i.Id == instanceId);
_toast.ShowInfo(
$"Auto-reconnected to {inst?.UniqueName ?? "instance"} from previous session.",
autoDismissMs: 8000);
}
}
private async Task LoadInstancesForSite()
{
_siteInstances.Clear();
_selectedInstanceId = 0;
if (_selectedSiteId == 0) return;
// Site scoping (CentralUI-002): re-check the claim server-side — a query
// string or stale localStorage value could name a site outside the grant.
if (!await SiteScope.IsSiteAllowedAsync(_selectedSiteId))
{
_selectedSiteId = 0;
_toast.ShowError("You are not permitted to debug instances on that site.");
return;
}
try
{
_siteInstances = (await TemplateEngineRepository.GetInstancesBySiteIdAsync(_selectedSiteId))
.Where(i => i.State == InstanceState.Enabled)
.ToList();
}
catch (Exception ex)
{
_toast.ShowError($"Failed to load instances: {ex.Message}");
}
}
private void OnInstanceSelectionChanged()
{
// No-op; selection is tracked via _selectedInstanceId binding
}
private async Task Connect()
{
if (_selectedInstanceId == 0 || _selectedSiteId == 0) return;
_connecting = true;
try
{
var session = await DebugStreamService.StartStreamAsync(
_selectedInstanceId,
onEvent: HandleStreamEvent,
onTerminated: () =>
{
_connected = false;
_session = null;
// CentralUI-009: skip the toast/render if already disposed.
if (_disposed) return;
_ = SafeInvokeAsync(() =>
{
if (_disposed) return;
_toast.ShowError("Debug stream terminated (site disconnected).");
StateHasChanged();
});
});
// M2.11: the site returns InstanceNotFound=true when the instance is
// not deployed there (e.g. deployment not yet pushed, or wrong site).
if (session.InitialSnapshot.InstanceNotFound)
{
DebugStreamService.StopStream(session.SessionId);
_toast.ShowError(
"Instance not found on the selected site — check the deployment target.");
_connecting = false;
return;
}
_session = session;
// Populate initial state from snapshot
_attributeValues.Clear();
foreach (var av in session.InitialSnapshot.AttributeValues)
_attributeValues[av.AttributeName] = av;
_alarmStates.Clear();
foreach (var al in session.InitialSnapshot.AlarmStates)
_alarmStates[al.AlarmName] = al;
_snapshot = session.InitialSnapshot;
_connected = true;
// Persist selection to localStorage for auto-reconnect on refresh
await JS.InvokeVoidAsync("localStorage.setItem", "debugView.siteId", _selectedSiteId.ToString());
await JS.InvokeVoidAsync("localStorage.setItem", "debugView.instanceId", _selectedInstanceId.ToString());
var instance = _siteInstances.FirstOrDefault(i => i.Id == _selectedInstanceId);
_toast.ShowSuccess($"Streaming {instance?.UniqueName ?? "instance"}");
}
catch (Exception ex)
{
_toast.ShowError($"Connect failed: {ex.Message}");
}
_connecting = false;
}
private async Task Disconnect()
{
if (_session != null)
{
DebugStreamService.StopStream(_session.SessionId);
_session = null;
}
// Clear persisted selection — user explicitly disconnected
await JS.InvokeVoidAsync("localStorage.removeItem", "debugView.siteId");
await JS.InvokeVoidAsync("localStorage.removeItem", "debugView.instanceId");
_connected = false;
_connectedFromStorage = false;
_snapshot = null;
_attributeValues.Clear();
_alarmStates.Clear();
}
/// <summary>
/// Disconnect and forget the persisted selection. Surfaces in the status
/// strip whenever the page auto-reconnects from localStorage so the user
/// can opt out of the carry-over session.
/// </summary>
private async Task StartFresh()
{
await Disconnect();
_selectedSiteId = 0;
_selectedInstanceId = 0;
_siteInstances.Clear();
_toast.ShowInfo("Cleared previous session — select a site and instance to begin.", autoDismissMs: 5000);
}
private void ClearAttributes()
{
_attributeValues.Clear();
}
private void ClearAlarms()
{
_alarmStates.Clear();
}
/// <summary>
/// Handles one debug-stream event. The callback is invoked on an Akka/gRPC
/// thread, but <see cref="_attributeValues"/>/<see cref="_alarmStates"/> are
/// <see cref="Dictionary{TKey,TValue}"/> instances also enumerated by the
/// render thread via <see cref="FilteredAttributeValues"/>/
/// <see cref="FilteredAlarmStates"/>. <c>Dictionary</c> is not thread-safe
/// (CentralUI-021): a write racing an enumeration can throw or corrupt the
/// buckets. The mutation (<see cref="UpsertWithCap"/>) is therefore
/// marshalled onto the renderer's dispatcher via <see cref="SafeInvokeAsync"/>
/// so every access to the dictionaries — read and write — happens on the
/// render thread.
/// </summary>
private void HandleStreamEvent(object evt)
{
// CentralUI-009: the component may have been disposed while this event
// was in flight on the Akka/gRPC thread.
if (_disposed) return;
_ = SafeInvokeAsync(() =>
{
if (_disposed) return;
switch (evt)
{
case AttributeValueChanged av:
UpsertWithCap(_attributeValues, av.AttributeName, av);
break;
case AlarmStateChanged al:
UpsertWithCap(_alarmStates, al.AlarmName, al);
break;
default:
return;
}
StateHasChanged();
});
}
/// <summary>
/// Replace or insert a value keyed by name, then trim the oldest entries
/// (queue-style) so the table size never exceeds MaxRows. Dictionary
/// preserves insertion order, so the first key is always the oldest.
/// <para>
/// Must be called on the render thread only (CentralUI-021) — see
/// <see cref="HandleStreamEvent"/>. The cap-trim loop is in the same
/// critical section as the upsert so the dictionary is never observed
/// over-capacity.
/// </para>
/// </summary>
private static void UpsertWithCap<T>(Dictionary<string, T> map, string key, T value)
{
map[key] = value;
while (map.Count > MaxRows)
{
var oldest = map.Keys.First();
map.Remove(oldest);
}
}
private static string GetQualityBadge(string quality) => quality switch
{
"Good" => "bg-success",
"Bad" => "bg-danger",
"Uncertain" => "bg-warning text-dark",
_ => "bg-secondary"
};
private static string GetAlarmStateBadge(AlarmState state) => state switch
{
AlarmState.Active => "bg-danger",
AlarmState.Normal => "bg-success",
_ => "bg-secondary"
};
private static string GetAlarmRowClass(AlarmState state) => state switch
{
AlarmState.Active => "table-danger",
_ => ""
};
/// <summary>
/// Severity-tinted badge class for HiLo alarm levels. The critical bands
/// (HighHigh / LowLow) get the danger class; warning bands get amber.
/// </summary>
private static string GetAlarmLevelBadge(AlarmLevel level) => level switch
{
AlarmLevel.HighHigh or AlarmLevel.LowLow => "bg-danger",
AlarmLevel.High or AlarmLevel.Low => "bg-warning text-dark",
_ => "bg-secondary"
};
/// <summary>Badge class distinguishing computed (neutral) from native (info) alarms.</summary>
private static string GetKindBadge(AlarmKind kind) => kind switch
{
AlarmKind.Computed => "bg-secondary",
_ => "bg-info text-dark"
};
/// <summary>Short display label for the alarm kind.</summary>
private static string FormatKind(AlarmKind kind) => kind switch
{
AlarmKind.NativeOpcUa => "OPC UA",
AlarmKind.NativeMxAccess => "MxAccess",
_ => "Computed"
};
/// <summary>
/// Builds the row tooltip from the alarm's operator message plus native
/// metadata (type, category, operator, raise time, current/limit value).
/// Returns null when there is nothing extra to show.
/// </summary>
private static string? BuildAlarmTooltip(AlarmStateChanged a)
{
var parts = new List<string>();
if (!string.IsNullOrEmpty(a.Message)) parts.Add(a.Message);
if (!string.IsNullOrEmpty(a.AlarmTypeName)) parts.Add($"Type: {a.AlarmTypeName}");
if (!string.IsNullOrEmpty(a.Category)) parts.Add($"Category: {a.Category}");
if (!string.IsNullOrEmpty(a.OperatorUser)) parts.Add($"By: {a.OperatorUser}");
if (!string.IsNullOrEmpty(a.OperatorComment)) parts.Add($"Comment: {a.OperatorComment}");
if (a.OriginalRaiseTime.HasValue) parts.Add($"Raised: {a.OriginalRaiseTime.Value.LocalDateTime:HH:mm:ss}");
if (!string.IsNullOrEmpty(a.CurrentValue)) parts.Add($"Value: {a.CurrentValue}");
if (!string.IsNullOrEmpty(a.LimitValue)) parts.Add($"Limit: {a.LimitValue}");
return parts.Count == 0 ? null : string.Join(" · ", parts);
}
private static string FormatLevel(AlarmLevel level) => level switch
{
AlarmLevel.HighHigh => "HiHi",
AlarmLevel.High => "Hi",
AlarmLevel.Low => "Lo",
AlarmLevel.LowLow => "LoLo",
_ => "—"
};
/// <summary>
/// Runs <paramref name="action"/> on the render thread, guarded against the
/// component being disposed mid-flight (CentralUI-009): <c>InvokeAsync</c>
/// throws <see cref="ObjectDisposedException"/> once the circuit is gone.
/// </summary>
private async Task SafeInvokeAsync(Action action)
{
if (_disposed) return;
try
{
await InvokeAsync(action);
}
catch (ObjectDisposedException)
{
// Component disposed between the guard and the dispatch — ignore.
}
}
public void Dispose()
{
// CentralUI-009: mark disposed first so any in-flight stream callback
// sees the flag and no-ops, then stop the stream synchronously.
_disposed = true;
if (_session != null)
{
DebugStreamService.StopStream(_session.SessionId);
}
}
}