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

196 lines
8.9 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
@page "/script-log"
@* Live script-log tail via SignalR. Subscribes to /hubs/script-log and shows entries from
VirtualTagActor / ScriptedAlarmActor script execution. Engine emit lands with F8 + F9. *@
@attribute [Authorize(Policy = AdminUiPolicies.AuthenticatedRead)]
@rendermode RenderMode.InteractiveServer
@using ZB.MOM.WW.OtOpcUa.AdminUI.Hubs
@using ZB.MOM.WW.OtOpcUa.Commons.Messages.Logging
@inject IInProcessBroadcaster<ScriptLogEntry> ScriptLogs
@using ZB.MOM.WW.OtOpcUa.AdminUI.LiveTail
@implements IAsyncDisposable
<PageErrorBoundary>
<PageTitle>Script log · OtOpcUa</PageTitle>
<div class="page-head">
<h1>Script log</h1>
<span class="spacer"></span>
<div class="ot-toolbar d-flex flex-wrap align-items-end gap-2" style="max-width:100%;min-width:0">
<div><label class="form-label small mb-1" for="@(_filterScope + "-level")">Log level</label>
<select id="@(_filterScope + "-level")" class="form-select form-select-sm" style="width:auto" @bind="_levelFilter" @bind:after="RecomputeVisible">
<option value="">All levels</option>
<option value="Trace">Trace+</option>
<option value="Debug">Debug+</option>
<option value="Information">Information+</option>
<option value="Warning">Warning+</option>
<option value="Error">Error+</option>
</select></div>
<div style="max-width:100%;min-width:0"><label class="form-label small mb-1" for="@(_filterScope + "-script")">Script ID</label>
<input id="@(_filterScope + "-script")" type="text" class="form-control form-control-sm" style="width:200px;max-width:100%"
placeholder="Filter script ID…" @bind="_scriptFilter" @bind:event="oninput" @bind:after="RecomputeVisible" /></div>
<span class="conn-pill" data-state="@(_connected ? "connected" : "disconnected")">
<span class="dot"></span><span>@(_connected ? "live" : "disconnected")</span>
</span>
<button type="button" class="btn btn-sm btn-outline-secondary" data-testid="tail-pause" aria-pressed="@(_paused ? "true" : "false")" @onclick="TogglePause">@(_paused ? "Resume" : "Pause")</button>
<button type="button" class="btn btn-sm btn-outline-secondary" data-testid="tail-clear" @onclick="ClearAsync">Clear visible log</button>
</div>
</div>
<p role="status" aria-live="polite" aria-atomic="true" data-testid="tail-status">@(_connected ? "Connected" : "Disconnected") · @(_paused ? "Paused — displayed rows are frozen." : "Live — showing the latest retained entries.")</p>
<p class="small text-muted"><span data-testid="tail-retained-count">@_tail.Items.Count</span> retained (maximum @Capacity). @(_paused ? "New arrivals continue replacing the oldest retained entries. Resume to see the latest window." : "Only this page’s current window is shown.") Clear affects this visible window, not historian records.</p>
@if (_visible.Count == 0)
{
<section class="panel notice rise mt-3" style="animation-delay:.08s">
@if (_displayed.Count == 0)
{
<span>@(_paused ? "No entries in the paused snapshot. Resume to show retained entries." : "No script-log entries yet.")</span>
}
else
{
<span>No entries match the current filter (@_displayed.Count entries in the displayed snapshot).</span>
}
</section>
}
else
{
<section class="panel rise mt-3" style="animation-delay:.08s">
<h2 class="panel-head">Showing @_visible.Count of @_displayed.Count displayed entries</h2>
<div class="table-wrap" role="region" aria-label="Script log entries" tabindex="0">
<table class="data-table">
<thead>
<tr>
<th scope="col">Time</th>
<th scope="col">Level</th>
<th scope="col">Script</th>
<th scope="col">Context</th>
<th scope="col">Message</th>
</tr>
</thead>
<tbody>
@foreach (var e in _visible)
{
<tr>
<td><span class="mono small">@e.TimestampUtc.ToString("yyyy-MM-dd HH:mm:ss.fff 'UTC'")</span></td>
<td><span class="chip @LevelChipClass(e.Level)">@e.Level</span></td>
<td><span class="mono small">@e.ScriptId</span></td>
<td class="text-muted small">
@if (!string.IsNullOrEmpty(e.VirtualTagId)) { <span>vtag=@e.VirtualTagId</span> }
@if (!string.IsNullOrEmpty(e.AlarmId)) { <span class="ms-1">alarm=@e.AlarmId</span> }
@if (!string.IsNullOrEmpty(e.EquipmentId)) { <span class="ms-1">eq=@e.EquipmentId</span> }
</td>
<td><DiagnosticDetails Summary="@(DisplayText.Abbreviate(e.Message, 120))" Text="@e.Message" /></td>
</tr>
}
</tbody>
</table>
</div>
</section>
}
</PageErrorBoundary>
@code {
private readonly string _filterScope = "script-log-" + Guid.NewGuid().ToString("N");
private const int Capacity = 500;
// Newest-first ring, filled from the bridge thread and drained once per coalescing window (R04 P7).
private readonly LiveTailBuffer<ScriptLogEntry> _tail = new(Capacity);
private CoalescingRenderScheduler? _render;
// The filtered rows, recomputed on flush / filter change — not on every render.
private IReadOnlyList<ScriptLogEntry> _visible = Array.Empty<ScriptLogEntry>();
private bool _connected;
private bool _paused;
private IReadOnlyList<ScriptLogEntry> _displayed = Array.Empty<ScriptLogEntry>();
private string _levelFilter = "";
private string _scriptFilter = "";
private static readonly Dictionary<string, int> LevelRank = new(StringComparer.OrdinalIgnoreCase)
{
["Trace"] = 0, ["Debug"] = 1, ["Information"] = 2, ["Warning"] = 3, ["Error"] = 4, ["Critical"] = 5,
};
private void RecomputeVisible()
{
IEnumerable<ScriptLogEntry> q = _displayed;
if (!string.IsNullOrWhiteSpace(_levelFilter)
&& LevelRank.TryGetValue(_levelFilter, out var minRank))
{
q = q.Where(e => LevelRank.TryGetValue(e.Level, out var r) && r >= minRank);
}
if (!string.IsNullOrWhiteSpace(_scriptFilter))
{
q = q.Where(e => e.ScriptId.Contains(_scriptFilter, StringComparison.OrdinalIgnoreCase));
}
_visible = q.ToList();
}
protected override void OnInitialized()
{
// Live tail straight from the in-process broadcaster (fed by ScriptLogSignalRBridge off the
// 'script-logs' DPS topic). Blazor Server can't self-connect a SignalR HubConnection behind
// a reverse proxy — see IInProcessBroadcaster — so we subscribe in-process instead.
// Subscribe the state-change event BEFORE reading IsConnected so no transition is missed.
_render = new CoalescingRenderScheduler(CoalescingRenderScheduler.DefaultWindow,
() => InvokeAsync(FlushTail));
ScriptLogs.ConnectionStateChanged += OnConnectionStateChanged;
ScriptLogs.Received += OnEntry;
_connected = ScriptLogs.IsConnected;
}
private void OnConnectionStateChanged(bool connected) =>
InvokeAsync(() => { _connected = connected; StateHasChanged(); });
// Bridge-actor thread: queue only. The first entry of a window arms one render ~200 ms later, so
// a chatty script costs one render per window per tab instead of one per log line.
private void OnEntry(ScriptLogEntry entry)
{
if (_tail.Add(entry)) _render?.Schedule();
}
// Render context: drain the queue into the ring and render once.
private void FlushTail()
{
if (!_tail.Flush()) return;
if (!_paused)
{
_displayed = _tail.Items;
RecomputeVisible();
}
StateHasChanged();
}
private void TogglePause()
{
FlushTail();
_paused = !_paused;
if (!_paused)
{
_displayed = _tail.Items;
RecomputeVisible();
}
}
private async Task ClearAsync()
{
_tail.Clear();
_displayed = Array.Empty<ScriptLogEntry>();
RecomputeVisible();
await InvokeAsync(StateHasChanged);
}
private static string LevelChipClass(string level) => level switch
{
"Critical" or "Error" => "chip-bad",
"Warning" => "chip-warn",
"Information" => "chip-idle",
_ => "chip-idle",
};
public async ValueTask DisposeAsync()
{
ScriptLogs.ConnectionStateChanged -= OnConnectionStateChanged;
ScriptLogs.Received -= OnEntry;
// Drains an in-flight window and suppresses later ones, so no flush renders a gone component.
if (_render is not null) await _render.DisposeAsync();
}
}