|
| 1 | +using System.Diagnostics; |
| 2 | +using Serilog; |
| 3 | +using SquidStd.Abstractions.Interfaces.Services; |
| 4 | +using SquidStd.Core.Data.EventLoop; |
| 5 | +using SquidStd.Core.Data.Metrics; |
| 6 | +using SquidStd.Core.Interfaces.Metrics; |
| 7 | +using SquidStd.Core.Interfaces.Threading; |
| 8 | +using SquidStd.Core.Interfaces.Timing; |
| 9 | +using SquidStd.Core.Types.Metrics; |
| 10 | + |
| 11 | +namespace SquidStd.Services.Core.Services.EventLoop; |
| 12 | + |
| 13 | +/// <summary> |
| 14 | +/// General-purpose event loop. Owns a dedicated background thread that each frame drains the |
| 15 | +/// <see cref="IMainThreadDispatcher" /> and advances the timer wheel (<see cref="ITimerService" />), |
| 16 | +/// sleeps when idle, and exposes tick metrics. Mutually exclusive with the timer-wheel pump. |
| 17 | +/// </summary> |
| 18 | +public sealed class EventLoopService : IEventLoopService, ISquidStdService, IMetricProvider, ITimerWheelDriver, IDisposable |
| 19 | +{ |
| 20 | + private readonly IMainThreadDispatcher _dispatcher; |
| 21 | + private readonly ITimerService _timer; |
| 22 | + private readonly EventLoopConfig _config; |
| 23 | + private readonly CancellationTokenSource _cts = new(); |
| 24 | + private readonly ILogger _logger = Log.ForContext<EventLoopService>(); |
| 25 | + private readonly Lock _metricsSync = new(); |
| 26 | + private double _averageTickMs; |
| 27 | + private long _idleSleepCount; |
| 28 | + private double _maxTickMs; |
| 29 | + private Thread? _thread; |
| 30 | + private long _tickCount; |
| 31 | + |
| 32 | + /// <inheritdoc /> |
| 33 | + public long TickCount => Interlocked.Read(ref _tickCount); |
| 34 | + |
| 35 | + /// <inheritdoc /> |
| 36 | + public double AverageTickMs |
| 37 | + { |
| 38 | + get |
| 39 | + { |
| 40 | + lock (_metricsSync) |
| 41 | + { |
| 42 | + return _averageTickMs; |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + /// <inheritdoc /> |
| 48 | + public double MaxTickMs |
| 49 | + { |
| 50 | + get |
| 51 | + { |
| 52 | + lock (_metricsSync) |
| 53 | + { |
| 54 | + return _maxTickMs; |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + /// <inheritdoc /> |
| 60 | + public string ProviderName => "eventloop"; |
| 61 | + |
| 62 | + public EventLoopService(IMainThreadDispatcher dispatcher, ITimerService timer, EventLoopConfig config) |
| 63 | + { |
| 64 | + _dispatcher = dispatcher; |
| 65 | + _timer = timer; |
| 66 | + _config = config; |
| 67 | + } |
| 68 | + |
| 69 | + /// <inheritdoc /> |
| 70 | + public ValueTask StartAsync(CancellationToken cancellationToken = default) |
| 71 | + { |
| 72 | + _thread = new Thread(RunLoop) |
| 73 | + { |
| 74 | + IsBackground = true, |
| 75 | + Name = "SquidStd-EventLoop" |
| 76 | + }; |
| 77 | + _thread.Start(); |
| 78 | + |
| 79 | + return ValueTask.CompletedTask; |
| 80 | + } |
| 81 | + |
| 82 | + /// <inheritdoc /> |
| 83 | + public ValueTask StopAsync(CancellationToken cancellationToken = default) |
| 84 | + { |
| 85 | + _cts.Cancel(); |
| 86 | + _thread?.Join(TimeSpan.FromSeconds(5)); |
| 87 | + |
| 88 | + return ValueTask.CompletedTask; |
| 89 | + } |
| 90 | + |
| 91 | + /// <inheritdoc /> |
| 92 | + public ValueTask<IReadOnlyList<MetricSample>> CollectAsync(CancellationToken cancellationToken = default) |
| 93 | + { |
| 94 | + double avg; |
| 95 | + double max; |
| 96 | + |
| 97 | + lock (_metricsSync) |
| 98 | + { |
| 99 | + avg = _averageTickMs; |
| 100 | + max = _maxTickMs; |
| 101 | + } |
| 102 | + |
| 103 | + IReadOnlyList<MetricSample> samples = |
| 104 | + [ |
| 105 | + new("tick_count", Interlocked.Read(ref _tickCount), Type: MetricType.Counter, Help: "Total event loop iterations"), |
| 106 | + new("tick_avg_ms", avg, Help: "EMA tick elapsed in ms"), |
| 107 | + new("tick_max_ms", max, Help: "Worst tick elapsed in ms"), |
| 108 | + new("idle_sleeps_total", Interlocked.Read(ref _idleSleepCount), Type: MetricType.Counter, Help: "Total idle sleeps") |
| 109 | + ]; |
| 110 | + |
| 111 | + return new ValueTask<IReadOnlyList<MetricSample>>(samples); |
| 112 | + } |
| 113 | + |
| 114 | + internal int Tick() |
| 115 | + { |
| 116 | + var start = Stopwatch.GetTimestamp(); |
| 117 | + var work = _dispatcher.DrainPending(); |
| 118 | + var nowMs = (long)Math.Floor(Stopwatch.GetTimestamp() * 1000.0 / Stopwatch.Frequency); |
| 119 | + work += _timer.UpdateTicksDelta(nowMs); |
| 120 | + var elapsed = Stopwatch.GetElapsedTime(start); |
| 121 | + |
| 122 | + UpdateMetrics(elapsed); |
| 123 | + |
| 124 | + if (elapsed.TotalMilliseconds >= _config.SlowTickThresholdMs) |
| 125 | + { |
| 126 | + _logger.Warning( |
| 127 | + "Slow tick: {Elapsed:0.###}ms work={Work} pending={Pending}", |
| 128 | + elapsed.TotalMilliseconds, |
| 129 | + work, |
| 130 | + _dispatcher.PendingCount |
| 131 | + ); |
| 132 | + } |
| 133 | + |
| 134 | + return work; |
| 135 | + } |
| 136 | + |
| 137 | + private void RunLoop() |
| 138 | + { |
| 139 | + while (!_cts.IsCancellationRequested) |
| 140 | + { |
| 141 | + var work = Tick(); |
| 142 | + |
| 143 | + if (_config.IdleCpuEnabled && work == 0) |
| 144 | + { |
| 145 | + Thread.Sleep(_config.IdleSleepMs); |
| 146 | + Interlocked.Increment(ref _idleSleepCount); |
| 147 | + } |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | + private void UpdateMetrics(TimeSpan elapsed) |
| 152 | + { |
| 153 | + Interlocked.Increment(ref _tickCount); |
| 154 | + |
| 155 | + lock (_metricsSync) |
| 156 | + { |
| 157 | + // Exponential moving average: 0.95 weight to history, 0.05 to current sample. |
| 158 | + _averageTickMs = _averageTickMs * 0.95 + elapsed.TotalMilliseconds * 0.05; |
| 159 | + _maxTickMs = Math.Max(_maxTickMs, elapsed.TotalMilliseconds); |
| 160 | + } |
| 161 | + } |
| 162 | + |
| 163 | + /// <inheritdoc /> |
| 164 | + public void Dispose() |
| 165 | + { |
| 166 | + _cts.Dispose(); |
| 167 | + GC.SuppressFinalize(this); |
| 168 | + } |
| 169 | +} |
0 commit comments