using System.Collections.Concurrent; using Titano.App.Jobs; using Titano.Core.Model; using Titano.Data.Jobs; using Titano.Testing; namespace Titano.App.Tests.Jobs; public sealed class JobUpdateBufferTests { [Test] public void ThousandsOfEventsCoalesceToTheLatestPerJob() { var buffer = new JobUpdateBuffer(); var ids = Enumerable.Range(0, 3).Select(_ => Guid.CreateVersion7()).ToArray(); Parallel.For(0, 3000, i => { var id = ids[i % 3]; buffer.Post(new JobProgressInfo(id, JobKind.Render, null, i, 3000, null, null, null)); }); Assert.Equal(3000, buffer.Posted); var (jobs, progress) = buffer.Drain(); Assert.Empty(jobs); Assert.Equal(3, progress.Count); Assert.True(buffer.IsEmpty); Assert.Empty(buffer.Drain().Progress); } [Test] public void AStateChangeSupersedesEarlierProgress() { var buffer = new JobUpdateBuffer(); var job = new Job { Id = Guid.CreateVersion7(), Kind = JobKind.Verify, State = JobState.Running }; Assert.True(buffer.Post(new JobProgressInfo(job.Id, job.Kind, null, 5, 10, null, null, null))); Assert.False(buffer.Post(job with { State = JobState.Done })); var (jobs, progress) = buffer.Drain(); Assert.Equal(JobState.Done, jobs.Single().State); Assert.Empty(progress); // Progress after the snapshot is kept: it is newer. buffer.Post(job); buffer.Post(new JobProgressInfo(job.Id, job.Kind, null, 7, 10, null, null, null)); (jobs, progress) = buffer.Drain(); Assert.Equal(1, jobs.Count); Assert.Equal(7, progress.Single().Done); } [Test] public async Task TheThrottleFlushesAtMostOncePerInterval() { var flushes = new ConcurrentQueue(); var clock = System.Diagnostics.Stopwatch.StartNew(); using var throttle = new CoalescingThrottle(TimeSpan.FromMilliseconds(100), null, () => flushes.Enqueue(clock.ElapsedMilliseconds)); // A burst of signals from several threads for about 550 ms. var stop = DateTime.UtcNow.AddMilliseconds(550); await Task.WhenAll(Enumerable.Range(0, 4).Select(_ => Task.Run(async () => { while (DateTime.UtcNow < stop) { throttle.Signal(); await Task.Delay(1); } }))); await Task.Delay(250); var times = flushes.ToArray(); Assert.InRange(times.Length, 3, 8); for (var i = 1; i < times.Length; i++) Assert.GreaterOrEqual(times[i] - times[i - 1], 80, $"flush {i} came too early"); Assert.Equal(times.Length, throttle.Flushes); } [Test] public async Task TheFirstSignalFlushesWithoutWaiting() { var flushed = new TaskCompletionSource(); using var throttle = new CoalescingThrottle(TimeSpan.FromSeconds(30), null, () => flushed.TrySetResult()); throttle.Signal(); await flushed.Task.WaitAsync(TimeSpan.FromSeconds(5)); Assert.Equal(1, throttle.Flushes); } [Test] public async Task FlushesRunOnTheGivenContext() { var context = new RecordingContext(); var flushed = new TaskCompletionSource(); using var throttle = new CoalescingThrottle(TimeSpan.FromMilliseconds(10), context, () => flushed.TrySetResult()); throttle.Signal(); await flushed.Task.WaitAsync(TimeSpan.FromSeconds(5)); Assert.Equal(1, context.Posts); } private sealed class RecordingContext : SynchronizationContext { private int _posts; public int Posts => Volatile.Read(ref _posts); public override void Post(SendOrPostCallback d, object? state) { Interlocked.Increment(ref _posts); ThreadPool.QueueUserWorkItem(_ => d(state)); } } }