From ee557ab532728f1e9728fa36c53ebcb44b0025b3 Mon Sep 17 00:00:00 2001 From: poli0981 <127664709+poli0981@users.noreply.github.com> Date: Wed, 21 Oct 2026 21:21:25 +0700 Subject: [PATCH] perf(logging): refresh the Log Viewer once per burst, not per event Every log event made the Log Viewer and Debug panel rebuild up to 1000 rows on the UI thread. The in-memory store now raises EntriesChanged once, 150 ms after the first event of a burst; Clear still notifies at once. Co-Authored-By: Claude Opus 5.5 --- .../Logging/InMemoryLogStore.cs | 43 ++++++++++++++- .../InMemoryLogStoreTests.cs | 52 ++++++++++++++++--- 2 files changed, 86 insertions(+), 9 deletions(-) diff --git a/src/CommandForge.Infrastructure/Logging/InMemoryLogStore.cs b/src/CommandForge.Infrastructure/Logging/InMemoryLogStore.cs index 4904c2e..333b33b 100644 --- a/src/CommandForge.Infrastructure/Logging/InMemoryLogStore.cs +++ b/src/CommandForge.Infrastructure/Logging/InMemoryLogStore.cs @@ -12,10 +12,31 @@ namespace CommandForge.Infrastructure.Logging; /// and the DI container. may fire off the UI thread — /// consumers must marshal to the UI thread before touching UI state. /// -public sealed class InMemoryLogStore : ILogEventSink, ILogReader +/// +/// A burst of log events raises once, shortly after the burst starts, +/// so the Log Viewer re-reads the buffer a few times a second instead of once per event. +/// +public sealed class InMemoryLogStore : ILogEventSink, ILogReader, IDisposable { private const int Capacity = 1000; + private static readonly TimeSpan DefaultNotifyDelay = TimeSpan.FromMilliseconds(150); + private readonly ConcurrentQueue _entries = new(); + private readonly Timer _notifyTimer; + private readonly TimeSpan _notifyDelay; + private int _notifyPending; + private volatile bool _disposed; + + public InMemoryLogStore() + : this(DefaultNotifyDelay) + { + } + + internal InMemoryLogStore(TimeSpan notifyDelay) + { + _notifyDelay = notifyDelay; + _notifyTimer = new Timer(_ => RaiseEntriesChanged(), null, Timeout.Infinite, Timeout.Infinite); + } /// public event EventHandler? EntriesChanged; @@ -29,7 +50,11 @@ public sealed class InMemoryLogStore : ILogEventSink, ILogReader TrimTo(Capacity); - EntriesChanged?.Invoke(this, EventArgs.Empty); + // The first event of a burst arms the timer; the rest ride along with that notification. + if (!_disposed && Interlocked.Exchange(ref _notifyPending, 1) == 0) + { + _notifyTimer.Change(_notifyDelay, Timeout.InfiniteTimeSpan); + } } /// @@ -43,6 +68,20 @@ public sealed class InMemoryLogStore : ILogEventSink, ILogReader EntriesChanged?.Invoke(this, EventArgs.Empty); } + /// + public void Dispose() + { + _disposed = true; + _notifyTimer.Dispose(); + } + + private void RaiseEntriesChanged() + { + // Reset before notifying: an event that lands while handlers read the buffer arms a new round. + Volatile.Write(ref _notifyPending, 0); + EntriesChanged?.Invoke(this, EventArgs.Empty); + } + private void TrimTo(int capacity) { var removed = true; diff --git a/tests/CommandForge.Tests/InMemoryLogStoreTests.cs b/tests/CommandForge.Tests/InMemoryLogStoreTests.cs index b70edf2..ff5c162 100644 --- a/tests/CommandForge.Tests/InMemoryLogStoreTests.cs +++ b/tests/CommandForge.Tests/InMemoryLogStoreTests.cs @@ -11,7 +11,7 @@ public sealed class InMemoryLogStoreTests [Fact] public void Emit_StoresStructuredEntry_WithMappedLevelAndMessage() { - var store = new InMemoryLogStore(); + using var store = new InMemoryLogStore(); store.Emit(Event(LogEventLevel.Warning, "hello")); var entries = store.GetRecentEntries(); @@ -23,7 +23,7 @@ public sealed class InMemoryLogStoreTests [Fact] public void Emit_RespectsCapacity() { - var store = new InMemoryLogStore(); + using var store = new InMemoryLogStore(); for (var i = 0; i < 1100; i++) { store.Emit(Event(LogEventLevel.Information, $"line {i}")); @@ -41,25 +41,63 @@ public sealed class InMemoryLogStoreTests [InlineData(LogEventLevel.Fatal, LogLevel.Fatal)] public void Emit_MapsSerilogLevel(LogEventLevel serilogLevel, LogLevel expected) { - var store = new InMemoryLogStore(); + using var store = new InMemoryLogStore(); store.Emit(Event(serilogLevel, "x")); Assert.Equal(expected, store.GetRecentEntries()[0].Level); } [Fact] - public void EntriesChanged_FiresOnEmitAndClear_AndClearEmpties() + public void Clear_NotifiesImmediately_AndEmpties() { - var store = new InMemoryLogStore(); + using var store = new InMemoryLogStore(Timeout.InfiniteTimeSpan); // only Clear can notify var notifications = 0; + store.Emit(Event(LogEventLevel.Information, "x")); store.EntriesChanged += (_, _) => notifications++; - store.Emit(Event(LogEventLevel.Information, "x")); store.Clear(); - Assert.Equal(2, notifications); + Assert.Equal(1, notifications); Assert.Empty(store.GetRecentEntries()); } + [Fact] + public async Task EntriesChanged_CoalescesABurstIntoFewNotifications() + { + using var store = new InMemoryLogStore(TimeSpan.FromMilliseconds(100)); + var notifications = 0; + var notified = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + store.EntriesChanged += (_, _) => + { + Interlocked.Increment(ref notifications); + notified.TrySetResult(); + }; + + for (var i = 0; i < 500; i++) + { + store.Emit(Event(LogEventLevel.Information, $"line {i}")); + } + + await notified.Task.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); + + // One notification per 100 ms window, not one per event (the bound allows for a slow agent). + Assert.InRange(Volatile.Read(ref notifications), 1, 50); + Assert.Equal(500, store.GetRecentEntries().Count); + } + + [Fact] + public async Task EntriesChanged_FiresAgainForEventsAfterANotification() + { + using var store = new InMemoryLogStore(TimeSpan.FromMilliseconds(10)); + using var notifications = new SemaphoreSlim(0); + store.EntriesChanged += (_, _) => notifications.Release(); + + store.Emit(Event(LogEventLevel.Information, "first")); + Assert.True(await notifications.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken)); + + store.Emit(Event(LogEventLevel.Information, "second")); + Assert.True(await notifications.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken)); + } + private static LogEvent Event(LogEventLevel level, string message) => new(DateTimeOffset.Now, level, exception: null, new MessageTemplateParser().Parse(message), []); }