perf(adminui): coalesce /script-log and /alerts renders with a ring buffer (R04 P7)

Each received event used to Insert(0) into a List and render the full page.
LiveTailBuffer queues events from the bridge thread into a bounded newest-first
ring; CoalescingRenderScheduler (TimeProvider-driven, drained on dispose)
flushes and renders at most once per 200 ms window. ScriptLog's filtered rows
are recomputed on flush/filter change instead of three times per render.

Refs #745
Claude-Session: https://claude.ai/code/session_01Ub9hGmYLQvn9XETzw7CMsT
This commit is contained in:
Joseph Doherty
2026-10-22 17:28:23 -04:00
parent 348ffaec1c
commit 8e69118200
5 changed files with 426 additions and 47 deletions
@@ -0,0 +1,79 @@
namespace ZB.MOM.WW.OtOpcUa.AdminUI.LiveTail;
/// <summary>
/// Coalesces bursts of "please re-render" requests into at most one flush per window. The first
/// <see cref="Schedule"/> after a flush arms a one-shot timer; further calls inside the window are
/// no-ops; when the timer fires the flush callback runs once (the page marshals it onto its render
/// context with <c>InvokeAsync</c>). Disposal drains an in-flight callback and suppresses later ones.
/// </summary>
public sealed class CoalescingRenderScheduler : IAsyncDisposable
{
/// <summary>The default coalescing window for live-tail pages.</summary>
public static readonly TimeSpan DefaultWindow = TimeSpan.FromMilliseconds(200);
private readonly TimeSpan _window;
private readonly Func<Task> _flush;
private readonly ITimer _timer;
private int _armed;
private volatile bool _disposed;
/// <summary>Creates the scheduler.</summary>
/// <param name="window">The coalescing window.</param>
/// <param name="flush">The callback run once per window; exceptions are swallowed (the page is the
/// only consumer, and a throw here would surface as an unobserved timer-thread exception).</param>
/// <param name="timeProvider">The time source; <see cref="TimeProvider.System"/> when null.</param>
public CoalescingRenderScheduler(TimeSpan window, Func<Task> flush, TimeProvider? timeProvider = null)
{
_window = window;
_flush = flush;
_timer = (timeProvider ?? TimeProvider.System)
.CreateTimer(OnFire, null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
}
/// <summary>Requests a flush within one window. Safe from any thread.</summary>
public void Schedule()
{
if (_disposed) return;
if (Interlocked.CompareExchange(ref _armed, 1, 0) != 0) return;
try
{
_timer.Change(_window, Timeout.InfiniteTimeSpan);
}
catch (ObjectDisposedException)
{
// Raced DisposeAsync — nothing left to render to.
}
}
private void OnFire(object? state)
{
// Disarm BEFORE flushing: an item arriving during the flush schedules the next window rather
// than being stranded until some later item happens to arrive.
Volatile.Write(ref _armed, 0);
if (_disposed) return;
// Not async void: a fault is observed on the returned task, never thrown onto the timer thread.
// The circuit going away mid-flush (ObjectDisposedException and friends) is the expected fault,
// and a live-tail render failure is never worth an unhandled exception.
Task task;
try
{
task = _flush();
}
catch
{
return;
}
_ = task.ContinueWith(static t => _ = t.Exception, CancellationToken.None,
TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default);
}
/// <inheritdoc />
public async ValueTask DisposeAsync()
{
_disposed = true;
await _timer.DisposeAsync().ConfigureAwait(false);
}
}
@@ -0,0 +1,94 @@
namespace ZB.MOM.WW.OtOpcUa.AdminUI.LiveTail;
/// <summary>
/// A bounded, newest-first buffer for a live event tail (the <c>/script-log</c> and <c>/alerts</c>
/// pages). Producers call <see cref="Add"/> from the bridge actor's thread; it only queues the item.
/// The page drains the queue into a fixed-capacity ring on its render context (<see cref="Flush"/>),
/// once per coalescing window, so a chatty feed costs one render per window instead of one per event,
/// and no <c>List.Insert(0, …)</c> memmove per event.
/// </summary>
/// <typeparam name="T">The event type.</typeparam>
public sealed class LiveTailBuffer<T>
{
private readonly object _gate = new();
private readonly T[] _ring;
private readonly List<T> _pending = new();
private int _head; // index the next item is written to
private int _count;
private IReadOnlyList<T> _snapshot = Array.Empty<T>();
/// <summary>Creates a buffer that keeps the most recent <paramref name="capacity"/> items.</summary>
/// <param name="capacity">Maximum retained items; must be positive.</param>
public LiveTailBuffer(int capacity)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(capacity);
_ring = new T[capacity];
}
/// <summary>The maximum number of retained items.</summary>
public int Capacity => _ring.Length;
/// <summary>Retained items, newest first, as of the last <see cref="Flush"/> or <see cref="Clear"/>.</summary>
public IReadOnlyList<T> Items => Volatile.Read(ref _snapshot);
/// <summary>Queues an item. Safe from any thread; does not change <see cref="Items"/> until the next flush.</summary>
/// <param name="item">The item to queue.</param>
/// <returns><see langword="true"/> when the queue was empty before this call, i.e. the caller should
/// schedule a flush.</returns>
public bool Add(T item)
{
lock (_gate)
{
// A burst larger than the ring would be evicted at flush anyway; dropping the oldest pending
// now keeps the queue bounded when no flush runs (e.g. a stalled circuit).
if (_pending.Count >= _ring.Length) _pending.RemoveAt(0);
_pending.Add(item);
return _pending.Count == 1;
}
}
/// <summary>Moves the queued items into the ring (evicting the oldest past capacity) and refreshes <see cref="Items"/>.</summary>
/// <returns><see langword="true"/> when anything was queued, i.e. a render is worthwhile.</returns>
public bool Flush()
{
lock (_gate)
{
if (_pending.Count == 0) return false;
foreach (var item in _pending)
{
_ring[_head] = item;
_head = (_head + 1) % _ring.Length;
if (_count < _ring.Length) _count++;
}
_pending.Clear();
Volatile.Write(ref _snapshot, BuildNewestFirst());
return true;
}
}
/// <summary>Drops every retained and queued item.</summary>
public void Clear()
{
lock (_gate)
{
_pending.Clear();
Array.Clear(_ring);
_head = 0;
_count = 0;
Volatile.Write(ref _snapshot, Array.Empty<T>());
}
}
private T[] BuildNewestFirst()
{
var result = new T[_count];
for (var i = 0; i < _count; i++)
{
var idx = (_head - 1 - i + _ring.Length) % _ring.Length;
result[i] = _ring[idx];
}
return result;
}
}