diff --git a/src/EDNexus.Core/Discord/DiscordPresenceService.cs b/src/EDNexus.Core/Discord/DiscordPresenceService.cs index 34999f8..d8fc1eb 100644 --- a/src/EDNexus.Core/Discord/DiscordPresenceService.cs +++ b/src/EDNexus.Core/Discord/DiscordPresenceService.cs @@ -64,6 +64,7 @@ public static string ResolveApplicationId(string? configured) private readonly PresenceThrottle _throttle; private readonly Func _isSuppressed; private readonly Func _clock; + private readonly TimeProvider _time; private readonly DateTimeOffset _sessionStartedAt; private readonly object _gate = new(); @@ -73,6 +74,8 @@ public static string ResolveApplicationId(string? configured) private DiscordPrivacyOptions _privacy; private bool _clearedForSuppression; private CancellationTokenSource? _pending; + /// The trailing send scheduled last (or a completed task). Test hook: see . + private Task _pendingSend = Task.CompletedTask; private bool _disposed; /// The live commander picture to mirror. Never written to. @@ -94,17 +97,21 @@ public DiscordPresenceService( DiscordPrivacyOptions? privacy = null) : this(state, client, DefaultMinInterval, isSuppressed, null, privacy) { } - /// Test-only constructor: a shortened throttle window and/or a controllable clock. + /// + /// Test-only constructor: a shortened throttle window and/or a controllable clock. + /// drives the trailing send's wait, and the clock when is null. + /// internal DiscordPresenceService( CommanderState state, IDiscordRpcClient client, TimeSpan minInterval, Func? isSuppressed = null, Func? clock = null, - DiscordPrivacyOptions? privacy = null) + DiscordPrivacyOptions? privacy = null, TimeProvider? time = null) { + _time = time ?? TimeProvider.System; _state = state; _client = client; _privacy = privacy ?? DiscordPrivacyOptions.Default; _isSuppressed = isSuppressed ?? (static () => false); - _clock = clock ?? (static () => DateTimeOffset.UtcNow); + _clock = clock ?? _time.GetUtcNow; _throttle = new PresenceThrottle(minInterval, _clock); _sessionStartedAt = _clock(); @@ -240,9 +247,9 @@ private void SchedulePendingLocked(TimeSpan delay) var cts = new CancellationTokenSource(); _pending = cts; - _ = Task.Run(async () => + _pendingSend = Task.Run(async () => { - try { await Task.Delay(delay, cts.Token).ConfigureAwait(false); } + try { await Task.Delay(delay, _time, cts.Token).ConfigureAwait(false); } catch (TaskCanceledException) { return; } lock (_gate) @@ -253,6 +260,14 @@ private void SchedulePendingLocked(TimeSpan delay) }); } + /// + /// Test hook: the trailing send scheduled last, which finishes once it has sent or stood down. + /// + internal Task PendingSend + { + get { lock (_gate) return _pendingSend; } + } + public void Dispose() { lock (_gate) diff --git a/src/EDNexus.Core/Reporting/InaraBridge.cs b/src/EDNexus.Core/Reporting/InaraBridge.cs index a11e8ea..b5830d9 100644 --- a/src/EDNexus.Core/Reporting/InaraBridge.cs +++ b/src/EDNexus.Core/Reporting/InaraBridge.cs @@ -54,6 +54,8 @@ public sealed class InaraBridge : IAsyncDisposable private Task _tail = Task.CompletedTask; private CancellationTokenSource? _debounce; + private Task _debounceTask = Task.CompletedTask; + private readonly TimeProvider _time; private DateTimeOffset? _rateLimitedAt; // when Inara last refused us for rate limiting; null once a send is accepted private readonly Queue _sendTimes = new(); // start time of recent requests (rolling window) private readonly CancellationTokenSource _disposeCts = new(); @@ -64,9 +66,13 @@ public sealed class InaraBridge : IAsyncDisposable public InaraBridge(JournalEventBus bus, AppSettings settings, InaraClient client, Func? isSuppressed = null, IReportingLog? log = null) : this(bus, settings, client, SessionStartDebounce, MinInterval, isSuppressed, log) { } - /// Test-only constructor allowing the debounce/throttle windows to be shortened. - internal InaraBridge(JournalEventBus bus, AppSettings settings, InaraClient client, TimeSpan debounceDelay, TimeSpan minInterval, Func? isSuppressed = null, IReportingLog? log = null, TimeSpan? retryBackoff = null) + /// + /// Test-only constructor allowing the debounce/throttle windows to be shortened, and the clock that + /// drives them and the retry backoff to be replaced. + /// + internal InaraBridge(JournalEventBus bus, AppSettings settings, InaraClient client, TimeSpan debounceDelay, TimeSpan minInterval, Func? isSuppressed = null, IReportingLog? log = null, TimeSpan? retryBackoff = null, TimeProvider? time = null) { + _time = time ?? TimeProvider.System; _retryBackoff = retryBackoff ?? RetryBackoff; _settings = settings; _client = client; @@ -209,12 +215,30 @@ private void ScheduleFlush(TimeSpan delay) _debounce?.Cancel(); var cts = new CancellationTokenSource(); _debounce = cts; - _ = Task.Run(async () => + var flush = Task.Run(async () => { - try { await Task.Delay(delay, cts.Token).ConfigureAwait(false); } + try { await Task.Delay(delay, _time, cts.Token).ConfigureAwait(false); } catch (TaskCanceledException) { return; } FlushNow(); }); + lock (_gate) _debounceTask = flush; + } + + /// + /// Test hook: completes once no debounced or retry flush is waiting and the send chain has finished, + /// i.e. the bridge will send nothing more until a new journal event arrives. + /// + internal async Task WhenSettledAsync() + { + while (true) + { + Task debounce, tail; + lock (_gate) (debounce, tail) = (_debounceTask, _tail); + try { await debounce.ConfigureAwait(false); } catch { } + try { await tail.ConfigureAwait(false); } catch { } + lock (_gate) + if (debounce == _debounceTask && tail == _tail) return; + } } private void FlushImmediate() @@ -267,11 +291,11 @@ private async Task SendAsync(Task previous, InaraIdentity identity, List 0 && now - _sendTimes.Peek() >= window) _sendTimes.Dequeue(); @@ -378,7 +402,7 @@ private void LogUpload(List batch, InaraResponse response) var payload = _settings.Reporting.LogPayloads ? SerializeEvents(batch) : null; _log.Record(new ReportingUpload( - DateTimeOffset.UtcNow, ReportingTarget.Inara, summary, response.IsOk, status, + _time.GetUtcNow(), ReportingTarget.Inara, summary, response.IsOk, status, Error: response.IsOk ? null : response.IsRateLimited ? $"{response.StatusText}. {RateLimitAdvice}" : (response.StatusText ?? "error"), diff --git a/src/EDNexus.Core/Twitch/TwitchStreamCardService.cs b/src/EDNexus.Core/Twitch/TwitchStreamCardService.cs index 9c48c0d..0963172 100644 --- a/src/EDNexus.Core/Twitch/TwitchStreamCardService.cs +++ b/src/EDNexus.Core/Twitch/TwitchStreamCardService.cs @@ -89,6 +89,7 @@ public sealed class TwitchStreamCardService : IDisposable private readonly Func _visibility; private readonly Func _isSuppressed; private readonly Func _clock; + private readonly TimeProvider _time; private readonly EbsCleanupQueue? _cleanup; private readonly TimeSpan _minInterval; private readonly CancellationTokenSource _cts = new(); @@ -154,7 +155,11 @@ public TwitchStreamCardService( EbsCleanupQueue? cleanup = null) : this(state, sources, client, updateStateEndpoint, token, visibility, isSuppressed, DefaultMinInterval, null, null, cleanup) { } - /// Test-only constructor: a shortened publish interval and/or a controllable clock. + /// + /// Test-only constructor: a shortened publish interval and/or a controllable clock. + /// drives the pump's waits (the rate-limit floor and the heartbeat) as well + /// as the clock when is null. + /// internal TwitchStreamCardService( CommanderState state, StreamCardSources sources, @@ -166,9 +171,11 @@ internal TwitchStreamCardService( TimeSpan minInterval, Func? clock, TimeSpan? refreshInterval = null, - EbsCleanupQueue? cleanup = null) + EbsCleanupQueue? cleanup = null, + TimeProvider? time = null) { _cleanup = cleanup; + _time = time ?? TimeProvider.System; _refreshInterval = refreshInterval ?? DefaultRefreshInterval; _state = state; _sources = sources; @@ -177,7 +184,7 @@ internal TwitchStreamCardService( _token = token; _visibility = visibility ?? (static () => StreamCardVisibility.Default); _isSuppressed = isSuppressed ?? (static () => false); - _clock = clock ?? (static () => DateTimeOffset.UtcNow); + _clock = clock ?? _time.GetUtcNow; _minInterval = minInterval; _state.PropertyChanged += OnStateChanged; @@ -265,7 +272,8 @@ private void OnStateChanged(object? sender, PropertyChangedEventArgs e) /// /// Marks the card as needing a republish. Called from journal-processing threads, so it does no - /// work beyond releasing the pump's signal — never any I/O, and never a lock the bus could contend. + /// work beyond releasing the pump's signal — never any I/O, and no lock but one held only to set a + /// flag alongside that release. /// private void MarkDirty() { @@ -276,9 +284,15 @@ private void MarkDirty() // publish; reacting to those would put a half-warmed card (and, with the game closed, its last // location) on the air. if (Volatile.Read(ref _armed) == 0) return; - try { _dirty.Release(); } - catch (SemaphoreFullException) { /* already dirty — the pump will pick up the newest state */ } - catch (ObjectDisposedException) { /* raced with Dispose */ } + // A parked pump handed this signal is no longer idle, even though the semaphore count reads 0 + // until its continuation runs. The gate is only ever held for a flag and this release. + lock (_idleGate) + { + _parked = false; + try { _dirty.Release(); } + catch (SemaphoreFullException) { /* already dirty — the pump will pick up the newest state */ } + catch (ObjectDisposedException) { /* raced with Dispose */ } + } } private async Task PumpAsync(CancellationToken ct) @@ -286,7 +300,7 @@ private async Task PumpAsync(CancellationToken ct) while (!ct.IsCancellationRequested) { bool changed; - try { changed = await _dirty.WaitAsync(NextHeartbeatIn(), ct).ConfigureAwait(false); } + try { changed = await WaitForChangeAsync(NextHeartbeatIn(), ct).ConfigureAwait(false); } catch (OperationCanceledException) { return; } catch (ObjectDisposedException) { return; } @@ -341,7 +355,7 @@ private async Task PumpAsync(CancellationToken ct) // Rate-limit floor. Any change arriving during this wait has already re-armed the signal, // so the next iteration publishes the newest state immediately after it elapses. - try { await Task.Delay(backoff, ct).ConfigureAwait(false); } + try { await Task.Delay(backoff, _time, ct).ConfigureAwait(false); } catch (OperationCanceledException) { return; } // Nothing else will wake the pump for a retry: MarkDirty only fires on journal activity, @@ -350,6 +364,71 @@ private async Task PumpAsync(CancellationToken ct) } } + /// + /// Waits for or for to pass on , + /// whichever comes first. True when the card was marked dirty. + /// + private async Task WaitForChangeAsync(TimeSpan timeout, CancellationToken ct) + { + try + { + // The heartbeat timer exists before the pump reports itself idle, so a test that advances + // the clock once idle is reported always reaches it. + using var heartbeat = new CancellationTokenSource(timeout, _time); + using var either = CancellationTokenSource.CreateLinkedTokenSource(ct, heartbeat.Token); + // Like MarkDirty, a heartbeat falling due ends the idle state at once, not when the pump's + // continuation gets to run. + using var unpark = heartbeat.Token.Register(static s => ((TwitchStreamCardService)s!).Unpark(), this); + lock (_idleGate) + { + // A heartbeat that fell due before this point has already run Unpark; parking now + // would report idle with that heartbeat still to be handled. + if (!heartbeat.IsCancellationRequested) + { + _parked = true; + if (_dirty.CurrentCount == 0) _idle?.TrySetResult(); + } + } + try + { + await _dirty.WaitAsync(either.Token).ConfigureAwait(false); + return true; + } + catch (OperationCanceledException) when (!ct.IsCancellationRequested) + { + return false; // the heartbeat fell due + } + } + finally + { + lock (_idleGate) _parked = false; + } + } + + private void Unpark() + { + lock (_idleGate) _parked = false; + } + + private readonly Lock _idleGate = new(); + private bool _parked; + private TaskCompletionSource? _idle; + + /// + /// Test hook: completes once the pump is parked waiting for a change with none pending, i.e. it + /// will do nothing more until something marks the card dirty or the heartbeat falls due. + /// + internal Task WhenIdleAsync() + { + lock (_idleGate) + { + if (_parked && _dirty.CurrentCount == 0) return Task.CompletedTask; + _idle ??= new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + if (_idle.Task.IsCompleted) _idle = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + return _idle.Task; + } + } + /// /// How long the pump may sleep before the card is due a heartbeat. Measured from the last publish /// rather than from the last wake, so an unrelated wake-up cannot keep pushing the heartbeat out. diff --git a/tests/EDNexus.Tests/Discord/DiscordPresenceServiceTests.cs b/tests/EDNexus.Tests/Discord/DiscordPresenceServiceTests.cs index 78aa63e..4143f05 100644 --- a/tests/EDNexus.Tests/Discord/DiscordPresenceServiceTests.cs +++ b/tests/EDNexus.Tests/Discord/DiscordPresenceServiceTests.cs @@ -39,13 +39,12 @@ public void Construction_immediately_pushes_whatever_state_is_already_known() [Fact] public void A_relevant_change_outside_the_throttle_window_sends_immediately() { + var now = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); var state = new CommanderState(); var client = new FakeDiscordRpcClient(); - // A near-zero window so the very first change (which follows the constructor's own send) - // isn't itself throttled by the earlier push. - using var service = new DiscordPresenceService(state, client, TimeSpan.FromMilliseconds(1)); + using var service = new DiscordPresenceService(state, client, TimeSpan.FromSeconds(15), clock: () => now); - System.Threading.Thread.Sleep(5); // clear the 1ms window from the constructor's initial send + now = now.AddMinutes(1); // past the window opened by the constructor's initial send state.StarSystem = "Colonia"; var last = Assert.Single(client.Sent, p => p.State == "Exploring Colonia"); diff --git a/tests/EDNexus.Tests/Discord/DiscordPrivacyTests.cs b/tests/EDNexus.Tests/Discord/DiscordPrivacyTests.cs index 0dc5542..9dd776d 100644 --- a/tests/EDNexus.Tests/Discord/DiscordPrivacyTests.cs +++ b/tests/EDNexus.Tests/Discord/DiscordPrivacyTests.cs @@ -238,23 +238,26 @@ public void Later_state_changes_keep_honouring_the_updated_privacy() [Fact] public async Task A_system_change_queued_in_the_throttle_window_never_leaks_after_hiding_the_system() { - // A frozen clock guarantees the system change lands inside the throttle window however slow + // A manual clock guarantees the system change lands inside the throttle window however slow // the machine is, so it is always queued rather than sent. - var now = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); + var time = new ManualTimeProvider(); var state = new CommanderState { StarSystem = "Sol" }; var client = new FakeDiscordRpcClient(); using var service = new DiscordPresenceService( - state, client, TimeSpan.FromMilliseconds(50), clock: () => now); + state, client, TimeSpan.FromMilliseconds(50), time: time); + var scheduled = time.NextTimerCreated; state.StarSystem = "Colonia"; Assert.DoesNotContain(client.Sent, p => p.State?.Contains("Colonia") == true); // queued, not sent + var queued = service.PendingSend; + await scheduled.WaitAsync(TimeSpan.FromSeconds(10)); // its wait has started service.UpdatePrivacy(new DiscordPrivacyOptions(ShowSystem: false, ShowCommander: true)); - // Open the throttle so the queued send would be allowed through if it hadn't been superseded, - // then give its (real, 50 ms) delay ample time to fire. - now = now.AddMinutes(1); - await Task.Delay(300); + // Open the throttle and let the queued send's wait run out, so it would go through if it hadn't + // been superseded, then wait for it to finish either way. + time.Advance(TimeSpan.FromMinutes(1)); + await queued.WaitAsync(TimeSpan.FromSeconds(10)); Assert.DoesNotContain(client.Sent, p => p.State?.Contains("Colonia") == true || p.Buttons.Any(b => b.Url.Contains("Colonia"))); diff --git a/tests/EDNexus.Tests/EliteBgs/EliteBgsClientTests.cs b/tests/EDNexus.Tests/EliteBgs/EliteBgsClientTests.cs index 17df88f..3778540 100644 --- a/tests/EDNexus.Tests/EliteBgs/EliteBgsClientTests.cs +++ b/tests/EDNexus.Tests/EliteBgs/EliteBgsClientTests.cs @@ -209,8 +209,8 @@ public async Task Concurrent_lookups_of_one_name_share_a_single_request() var handler = new CountingGateHandler(gate.Task, () => Interlocked.Increment(ref calls)); using var client = NewClient(null!, http: new HttpClient(handler)); + // Each call joins the in-flight request before it returns, so all eight share it by now. var tasks = Enumerable.Range(0, 8).Select(_ => client.GetSystemAsync("Sol")).ToArray(); - await Task.Delay(100); gate.SetResult(); var results = await Task.WhenAll(tasks); diff --git a/tests/EDNexus.Tests/ManualTimeProvider.cs b/tests/EDNexus.Tests/ManualTimeProvider.cs new file mode 100644 index 0000000..80b538c --- /dev/null +++ b/tests/EDNexus.Tests/ManualTimeProvider.cs @@ -0,0 +1,118 @@ +namespace EDNexus.Tests; + +/// +/// A whose clock only moves when a test calls . +/// Timers fire on the advancing thread, in due-time order, so "let the backoff elapse" is one call +/// instead of a sleep, and "an hour passed" costs nothing. +/// +internal sealed class ManualTimeProvider : TimeProvider +{ + private readonly Lock _gate = new(); + private readonly List _timers = new(); + private DateTimeOffset _now; + private TaskCompletionSource _timerCreated = NewSignal(); + + public ManualTimeProvider(DateTimeOffset? start = null) => + _now = start ?? new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); + + public override DateTimeOffset GetUtcNow() + { + lock (_gate) return _now; + } + + public override TimeZoneInfo LocalTimeZone => TimeZoneInfo.Utc; + + public override long TimestampFrequency => TimeSpan.TicksPerSecond; + + public override long GetTimestamp() + { + lock (_gate) return _now.UtcTicks; + } + + /// Completes the next time any code creates a timer on this provider. + public Task NextTimerCreated + { + get { lock (_gate) return _timerCreated.Task; } + } + + public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period) + { + var timer = new ManualTimer(this, callback, state); + timer.Change(dueTime, period); + + TaskCompletionSource created; + lock (_gate) + { + created = _timerCreated; + _timerCreated = NewSignal(); + } + created.TrySetResult(); + return timer; + } + + /// Moves the clock forward, firing every timer that falls due on the way. + public void Advance(TimeSpan by) + { + if (by < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(by)); + + DateTimeOffset target; + lock (_gate) target = _now + by; + + while (true) + { + ManualTimer? next = null; + lock (_gate) + { + foreach (var t in _timers) + if (t.Due <= target && (next is null || t.Due < next.Due)) next = t; + + if (next is null) + { + _now = target; + return; + } + + if (next.Due > _now) _now = next.Due; + if (next.Period > TimeSpan.Zero) next.Due = _now + next.Period; + else _timers.Remove(next); + } + + next.Fire(); // outside the lock: the callback may create or change timers + } + } + + private static TaskCompletionSource NewSignal() => new(TaskCreationOptions.RunContinuationsAsynchronously); + + private sealed class ManualTimer(ManualTimeProvider owner, TimerCallback callback, object? state) : ITimer + { + public DateTimeOffset Due { get; set; } + public TimeSpan Period { get; private set; } + + public void Fire() => callback(state); + + public bool Change(TimeSpan dueTime, TimeSpan period) + { + lock (owner._gate) + { + owner._timers.Remove(this); + if (dueTime == Timeout.InfiniteTimeSpan) return true; + + Due = owner._now + dueTime; + Period = period == Timeout.InfiniteTimeSpan ? TimeSpan.Zero : period; + owner._timers.Add(this); + return true; + } + } + + public void Dispose() + { + lock (owner._gate) owner._timers.Remove(this); + } + + public ValueTask DisposeAsync() + { + Dispose(); + return ValueTask.CompletedTask; + } + } +} diff --git a/tests/EDNexus.Tests/Radio/RadioEngineStartTests.cs b/tests/EDNexus.Tests/Radio/RadioEngineStartTests.cs index f43f6c7..e4a9ffc 100644 --- a/tests/EDNexus.Tests/Radio/RadioEngineStartTests.cs +++ b/tests/EDNexus.Tests/Radio/RadioEngineStartTests.cs @@ -35,9 +35,12 @@ public async Task The_snapshot_stays_readable_while_the_engine_is_starting() try { // This is what the UI thread does every 250 ms; it must not wait for the native start. - var read = Task.Run(() => radio.Snapshot); - var finished = await Task.WhenAny(read, Task.Delay(TimeSpan.FromSeconds(2))); - Assert.Same(read, finished); + // Read on a dedicated thread, not the pool: the blocked start already holds a pool thread, + // and on a busy CI runner a pooled read can sit queued for seconds without ever touching + // the lock. The start is held for 30 s, so a read blocked on it cannot finish inside 10. + var read = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + new Thread(() => { _ = radio.Snapshot; read.SetResult(); }) { IsBackground = true }.Start(); + await read.Task.WaitAsync(TimeSpan.FromSeconds(10)); } finally { diff --git a/tests/EDNexus.Tests/Reporting/EddnBridgeBatchingTests.cs b/tests/EDNexus.Tests/Reporting/EddnBridgeBatchingTests.cs index 473bc2a..bf8e044 100644 --- a/tests/EDNexus.Tests/Reporting/EddnBridgeBatchingTests.cs +++ b/tests/EDNexus.Tests/Reporting/EddnBridgeBatchingTests.cs @@ -94,7 +94,7 @@ public async Task Historical_signals_are_never_uploaded() bus.Publish(Entry(Jump, historical: true)); bus.Publish(Entry(Signal("A"), historical: true)); bus.Publish(Entry("""{ "timestamp": "2020-01-01T00:00:06Z", "event": "Music", "MusicTrack": "x" }""", historical: true)); - await Task.Delay(100); + // Disposing flushes a trailing run and waits for the upload, so anything buffered would be sent here. await bridge.DisposeAsync(); Assert.Equal(0, handler.CallCount); diff --git a/tests/EDNexus.Tests/Reporting/EddnUploaderHandOffTests.cs b/tests/EDNexus.Tests/Reporting/EddnUploaderHandOffTests.cs index 9823423..2f0166c 100644 --- a/tests/EDNexus.Tests/Reporting/EddnUploaderHandOffTests.cs +++ b/tests/EDNexus.Tests/Reporting/EddnUploaderHandOffTests.cs @@ -23,6 +23,12 @@ public class EddnUploaderHandOffTests SoftwareName = "T", SoftwareVersion = "1", RetryDelay = TimeSpan.Zero, + // Dispose only waits DisposeGrace for the queue to drain before cancelling. These tests count + // what was sent after dispose, so a drain cut short by a starved thread pool (16-way parallel on + // a small CI runner) would look exactly like a stranded message. A generous grace removes that + // false positive; dispose still returns as soon as the worker finishes, so a stranded message + // (the worker exiting without it) is still caught. + DisposeGrace = TimeSpan.FromMinutes(1), }; /// diff --git a/tests/EDNexus.Tests/Reporting/EddnUploaderResilienceTests.cs b/tests/EDNexus.Tests/Reporting/EddnUploaderResilienceTests.cs index ef5b578..edc26c1 100644 --- a/tests/EDNexus.Tests/Reporting/EddnUploaderResilienceTests.cs +++ b/tests/EDNexus.Tests/Reporting/EddnUploaderResilienceTests.cs @@ -59,8 +59,10 @@ protected override Task SendAsync(HttpRequestMessage reques public async Task Queue_is_bounded_and_drops_the_oldest_queued_messages() { var gate = new TaskCompletionSource(); + var inFlight = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var handler = new ScriptedHandler(async (_, _) => { + inFlight.TrySetResult(); await gate.Task; return new HttpResponseMessage(HttpStatusCode.OK); }); @@ -70,7 +72,7 @@ public async Task Queue_is_bounded_and_drops_the_oldest_queued_messages() var messages = Enumerable.Range(0, 10).Select(Message).ToList(); uploader.Enqueue(messages[0]); - while (handler.Calls == 0) await Task.Delay(5); // message 0 is now in flight, queue empty + await inFlight.Task.WaitAsync(TimeSpan.FromSeconds(10)); // message 0 is now in flight, queue empty foreach (var m in messages.Skip(1)) uploader.Enqueue(m); gate.SetResult(); @@ -104,11 +106,16 @@ public async Task Messages_that_waited_too_long_are_dropped_unsent() [Fact] public async Task Dispose_cancels_a_pending_retry_wait_promptly() { - var handler = new ScriptedHandler((_, _) => Task.FromResult(new HttpResponseMessage(HttpStatusCode.InternalServerError))); + var attempted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var handler = new ScriptedHandler((_, _) => + { + attempted.TrySetResult(); + return Task.FromResult(new HttpResponseMessage(HttpStatusCode.InternalServerError)); + }); var uploader = new EddnUploader(Options(o => o.RetryDelay = TimeSpan.FromHours(1)), new HttpClient(handler)); uploader.Enqueue(Message(1)); - while (handler.Calls == 0) await Task.Delay(5); // first attempt failed; now sleeping the retry delay + await attempted.Task.WaitAsync(TimeSpan.FromSeconds(10)); // the first attempt is failing; the retry waits an hour var sw = Stopwatch.StartNew(); await uploader.DisposeAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(10)); diff --git a/tests/EDNexus.Tests/Reporting/InaraBridgeResilienceTests.cs b/tests/EDNexus.Tests/Reporting/InaraBridgeResilienceTests.cs index 1afd506..1004d61 100644 --- a/tests/EDNexus.Tests/Reporting/InaraBridgeResilienceTests.cs +++ b/tests/EDNexus.Tests/Reporting/InaraBridgeResilienceTests.cs @@ -28,9 +28,26 @@ private static JournalEntry Entry(string json, bool historical = false) return e; } - private static InaraBridge NewBridge(JournalEventBus bus, HttpMessageHandler handler, TimeSpan minInterval, TimeSpan retryBackoff) + private static InaraBridge NewBridge(JournalEventBus bus, HttpMessageHandler handler, TimeSpan minInterval, TimeSpan retryBackoff, TimeProvider? time = null) => new(bus, EnabledSettings(), new InaraClient(ClientOptions, new HttpClient(handler)), TimeSpan.Zero, minInterval, - isSuppressed: null, log: null, retryBackoff: retryBackoff); + isSuppressed: null, log: null, retryBackoff: retryBackoff, time: time); + + /// + /// Lets every scheduled retry play out on the manual clock, and returns once the bridge has nothing + /// left to send: no flush waiting, the send chain finished. A test can then assert on the final + /// call count without waiting on the wall clock. + /// + private static async Task SettleAsync(InaraBridge bridge, ManualTimeProvider time) + { + for (var i = 0; i < 100; i++) + { + var settled = bridge.WhenSettledAsync(); + var timer = time.NextTimerCreated; + time.Advance(TimeSpan.FromMinutes(10)); // the longest backoff the bridge will use + if (await Task.WhenAny(settled, timer).WaitAsync(TimeSpan.FromSeconds(10)) == settled) return; + } + Assert.Fail("The bridge never settled."); + } private static async Task WaitForAsync(Func condition, int timeoutMs = 3000) { @@ -63,12 +80,12 @@ public async Task Retries_are_bounded_and_the_batch_is_eventually_dropped() { var bus = new JournalEventBus(); var handler = new RecordingHandler(HttpStatusCode.InternalServerError, ""); - await using var bridge = NewBridge(bus, handler, TimeSpan.Zero, TimeSpan.FromMilliseconds(5)); + var time = new ManualTimeProvider(); + await using var bridge = NewBridge(bus, handler, TimeSpan.Zero, TimeSpan.FromMilliseconds(5), time); bus.Publish(Entry(Commander)); bus.Publish(Entry(Dock)); - await WaitForAsync(() => handler.CallCount >= 4); - await Task.Delay(300); + await SettleAsync(bridge, time); Assert.Equal(4, handler.CallCount); // the original attempt plus three retries, then given up } @@ -78,12 +95,12 @@ public async Task A_hard_error_is_not_retried() { var bus = new JournalEventBus(); var handler = new RecordingHandler(HttpStatusCode.OK, """{ "header": { "eventStatus": 400, "eventStatusText": "Invalid API key" } }"""); - await using var bridge = NewBridge(bus, handler, TimeSpan.Zero, TimeSpan.FromMilliseconds(5)); + var time = new ManualTimeProvider(); + await using var bridge = NewBridge(bus, handler, TimeSpan.Zero, TimeSpan.FromMilliseconds(5), time); bus.Publish(Entry(Commander)); bus.Publish(Entry(Dock)); - await WaitForAsync(() => handler.CallCount >= 1); - await Task.Delay(150); + await SettleAsync(bridge, time); Assert.Equal(1, handler.CallCount); } @@ -102,7 +119,8 @@ public async Task Replayed_history_including_shutdown_uploads_nothing() bus.Publish(Entry("""{ "timestamp": "2020-01-01T00:00:03Z", "event": "Loadout", "Ship": "python", "ShipID": 7 }""", historical: true)); bus.Publish(Entry("""{ "timestamp": "2020-01-01T00:00:04Z", "event": "Reputation", "Empire": 10.0 }""", historical: true)); bus.Publish(Entry("""{ "timestamp": "2020-01-01T00:20:00Z", "event": "Shutdown" }""", historical: true)); - await Task.Delay(150); + // Disposing flushes whatever is pending and waits for the send chain, so anything the history + // had queued would be sent here. await bridge.DisposeAsync(); Assert.Equal(0, handler.CallCount); diff --git a/tests/EDNexus.Tests/Reporting/InaraBridgeTests.cs b/tests/EDNexus.Tests/Reporting/InaraBridgeTests.cs index e9a2084..2df4a29 100644 --- a/tests/EDNexus.Tests/Reporting/InaraBridgeTests.cs +++ b/tests/EDNexus.Tests/Reporting/InaraBridgeTests.cs @@ -59,8 +59,20 @@ public async Task Accumulating_events_do_not_send_without_a_trigger() bus.Publish(Live("""{ "timestamp": "2020-01-01T00:00:01Z", "event": "Loadout", "Ship": "python", "ShipID": 7 }""")); bus.Publish(Live("""{ "timestamp": "2020-01-01T00:00:02Z", "event": "Rank", "Combat": 3 }""")); - await Task.Delay(150); + // Let any flush those events might have scheduled run first, so a dock cannot cancel it unseen. + await bridge.WhenSettledAsync().WaitAsync(TimeSpan.FromSeconds(10)); Assert.Equal(0, handler.CallCount); // nothing sent — no trigger occurred + + // A dock is a trigger, and flushes synchronously on this thread. Had any of the events above + // sent on its own, it would have gone out first and taken its event out of the batch; instead + // the first and only request carries all of them together with the dock. + bus.Publish(Live("""{ "timestamp": "2020-01-01T00:10:00Z", "event": "Docked", "StarSystem": "Sol", "StationName": "X", "MarketID": 1 }""")); + await bridge.DisposeAsync(); // waits for the send chain + + var body = Assert.Single(handler.Bodies); + Assert.Contains("setCommanderShip", body); + Assert.Contains("setCommanderRankPilot", body); + Assert.Contains("addCommanderTravelDock", body); } [Fact] @@ -110,7 +122,9 @@ public async Task Suppressed_reporter_never_sends_even_when_enabled() bus.Publish(Live("""{ "timestamp": "2020-01-01T00:00:00Z", "event": "LoadGame", "Commander": "Jameson", "FID": "F1", "Credits": 100 }""")); bus.Publish(Live("""{ "timestamp": "2020-01-01T00:10:00Z", "event": "Docked", "StarSystem": "Sol", "StationName": "X", "MarketID": 1 }""")); - await Task.Delay(150); + // The dock flushes synchronously, and disposing flushes again and waits for the send chain, so + // anything that was going to go out has gone out by now. + await bridge.DisposeAsync(); Assert.Equal(0, handler.CallCount); } @@ -125,7 +139,9 @@ public async Task Disabled_reporter_never_sends() bus.Publish(Live("""{ "timestamp": "2020-01-01T00:00:00Z", "event": "LoadGame", "Commander": "Jameson", "FID": "F1", "Credits": 100 }""")); bus.Publish(Live("""{ "timestamp": "2020-01-01T00:10:00Z", "event": "Docked", "StarSystem": "Sol", "StationName": "X", "MarketID": 1 }""")); - await Task.Delay(150); + // The dock flushes synchronously, and disposing flushes again and waits for the send chain, so + // anything that was going to go out has gone out by now. + await bridge.DisposeAsync(); Assert.Equal(0, handler.CallCount); } diff --git a/tests/EDNexus.Tests/Settings/SettingsStorePersistenceTests.cs b/tests/EDNexus.Tests/Settings/SettingsStorePersistenceTests.cs index 51b9cbd..05dad76 100644 --- a/tests/EDNexus.Tests/Settings/SettingsStorePersistenceTests.cs +++ b/tests/EDNexus.Tests/Settings/SettingsStorePersistenceTests.cs @@ -149,16 +149,20 @@ public void A_file_that_could_not_be_read_at_startup_is_not_overwritten_by_a_lat } [Fact] - public async Task A_brief_lock_on_startup_is_waited_out() + public void A_brief_lock_on_startup_is_waited_out() { Directory.CreateDirectory(Dir); File.WriteAllText(SettingsPath, """{"Reporting":{"Inara":{"ApiKey":"keep-me"}}}"""); + // The 150 ms lock is the scenario itself, well inside the store's ~600 ms of retries. It is + // released from a dedicated thread rather than a pool timer, so a busy thread pool on a loaded + // CI runner cannot stretch it past the retry budget. var locked = new FileStream(SettingsPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None); - var release = Task.Run(async () => { await Task.Delay(150); locked.Dispose(); }); + var release = new Thread(() => { Thread.Sleep(150); locked.Dispose(); }) { IsBackground = true }; + release.Start(); var loaded = NewStore().Load(); - await release; + release.Join(); Assert.Equal("keep-me", loaded.Reporting.Inara.ApiKey); } diff --git a/tests/EDNexus.Tests/Twitch/TwitchStreamCardServiceTests.cs b/tests/EDNexus.Tests/Twitch/TwitchStreamCardServiceTests.cs index 58e9d2d..f68ae37 100644 --- a/tests/EDNexus.Tests/Twitch/TwitchStreamCardServiceTests.cs +++ b/tests/EDNexus.Tests/Twitch/TwitchStreamCardServiceTests.cs @@ -20,7 +20,8 @@ private static TwitchStreamCardService Create( FakeStreamStateApiClient client, Func? token = null, Func? visibility = null, - Func? isSuppressed = null) => + Func? isSuppressed = null, + TimeProvider? time = null) => new( state, StreamCardSources.Empty, @@ -30,7 +31,27 @@ private static TwitchStreamCardService Create( visibility, isSuppressed, FastInterval, - clock: null); + clock: null, + time: time); + + /// + /// Lets the pump run to rest on the manual clock: each rate-limit wait it starts is advanced past, + /// and this returns once it is parked with nothing marked dirty. From then on it does nothing + /// until the card is marked dirty again or the heartbeat falls due, so a test can assert that + /// nothing (more) was published without waiting on the wall clock. + /// + private static async Task SettleAsync(TwitchStreamCardService service, ManualTimeProvider time, TimeSpan? step = null) + { + for (var i = 0; i < 100; i++) + { + var idle = service.WhenIdleAsync(); + if (idle.IsCompleted) return; + var timer = time.NextTimerCreated; + time.Advance(step ?? FastInterval * 2); + await Task.WhenAny(idle, timer).WaitAsync(TimeSpan.FromSeconds(10)); + } + Assert.Fail("The pump never came to rest."); + } [Fact] public async Task Nothing_is_published_until_the_host_has_replayed_the_journal() @@ -39,9 +60,10 @@ public async Task Nothing_is_published_until_the_host_has_replayed_the_journal() // Built inside EngineHost's constructor, before the replay. Publishing here would send an // empty card and leave that as the EBS's initial state until the warm one follows. - using var service = Create(new CommanderState(), client); + var time = new ManualTimeProvider(); + using var service = Create(new CommanderState(), client, time: time); - Assert.False(await client.WaitForPublishAsync(TimeSpan.FromMilliseconds(300))); + await SettleAsync(service, time); Assert.Empty(client.Snapshots); } @@ -66,9 +88,11 @@ public async Task Nothing_is_published_until_the_commander_has_logged_in() var state = new CommanderState { StarSystem = "Nervi" }; var client = new FakeStreamStateApiClient(); - using var service = Create(state, client, token: static () => null); + var time = new ManualTimeProvider(); + using var service = Create(state, client, token: static () => null, time: time); + service.RequestPublish(); - Assert.False(await client.WaitForPublishAsync(TimeSpan.FromMilliseconds(300))); + await SettleAsync(service, time); Assert.Empty(client.Snapshots); } @@ -80,9 +104,11 @@ public async Task Nothing_is_published_while_suppressed() // Developer mode feeds fabricated journal events through the real bus; they must never reach // a live audience. - using var service = Create(state, client, isSuppressed: static () => true); + var time = new ManualTimeProvider(); + using var service = Create(state, client, isSuppressed: static () => true, time: time); + service.RequestPublish(); - Assert.False(await client.WaitForPublishAsync(TimeSpan.FromMilliseconds(300))); + await SettleAsync(service, time); Assert.Empty(client.Snapshots); } @@ -92,15 +118,16 @@ public async Task A_change_that_viewers_cannot_see_does_not_spend_a_publish() var state = new CommanderState { StarSystem = "Nervi" }; var client = new FakeStreamStateApiClient(); - using var service = Create(state, client); + var time = new ManualTimeProvider(); + using var service = Create(state, client, time: time); service.RequestPublish(); Assert.True(await client.WaitForPublishAsync()); // LastUpdated ticks on virtually every journal line but changes nothing on the card. for (var i = 0; i < 5; i++) { - state.LastUpdated = DateTimeOffset.UtcNow; - await Task.Delay(FastInterval); + state.LastUpdated = time.GetUtcNow(); + await SettleAsync(service, time); } Assert.Single(client.Snapshots); @@ -128,20 +155,21 @@ public async Task A_burst_of_changes_is_coalesced_into_the_newest_state() var state = new CommanderState { StarSystem = "Nervi" }; var client = new FakeStreamStateApiClient(); - using var service = Create(state, client); + var time = new ManualTimeProvider(); + using var service = Create(state, client, time: time); service.RequestPublish(); Assert.True(await client.WaitForPublishAsync()); // A single hyperspace jump touches several properties at once; viewers only need the result. + // The clock stands still, so the whole burst lands inside the rate-limit wait. state.StarSystem = "Colonia"; state.Body = "Colonia 2 a"; state.FuelMain = 18.2; state.CargoTons = 24; - Assert.True(await client.WaitForPublishAsync()); - await Task.Delay(FastInterval * 4); + await SettleAsync(service, time); - Assert.True(client.Snapshots.Count < 5, $"Expected a coalesced burst, saw {client.Snapshots.Count} publishes."); + Assert.Equal(2, client.Snapshots.Count); // the first card, then ONE for the whole burst Assert.Equal("Colonia", client.Snapshots[^1].Location!.System); } @@ -154,7 +182,8 @@ public async Task A_rejected_token_stops_publishing_and_asks_for_a_new_login() Respond = _ => new StreamStatePublishResult(StreamStatePublishStatus.Unauthorized, "revoked"), }; - using var service = Create(state, client); + var time = new ManualTimeProvider(); + using var service = Create(state, client, time: time); // Subscribe before asking for the publish: the pump can answer the 401 and raise the event // before the next line runs, and an event raised with no handler attached is lost for good. var reauth = new TaskCompletionSource(); @@ -167,7 +196,7 @@ public async Task A_rejected_token_stops_publishing_and_asks_for_a_new_login() var attempts = client.Snapshots.Count; state.StarSystem = "Colonia"; - await Task.Delay(FastInterval * 4); + await SettleAsync(service, time); // Retrying a revoked grant can only ever earn a rate-limit, so publishing stays stopped. Assert.Equal(attempts, client.Snapshots.Count); @@ -214,8 +243,10 @@ public async Task Switching_the_card_on_publishes_without_waiting_for_a_journal_ var enabled = false; // How the app wires it: the card being off reads through as "no token". - using var service = Create(state, client, token: () => enabled ? "ebs-token" : null); - Assert.False(await client.WaitForPublishAsync(TimeSpan.FromMilliseconds(300))); + var time = new ManualTimeProvider(); + using var service = Create(state, client, token: () => enabled ? "ebs-token" : null, time: time); + await SettleAsync(service, time); + Assert.Empty(client.Snapshots); // The commander ticks "Show my session to viewers". Nothing about the commander picture has // changed, and with the game closed no journal event is ever coming — so the settings dialog @@ -233,7 +264,8 @@ public async Task Requesting_a_publish_that_changes_nothing_is_still_deduplicate var state = new CommanderState { StarSystem = "Nervi" }; var client = new FakeStreamStateApiClient(); - using var service = Create(state, client); + var time = new ManualTimeProvider(); + using var service = Create(state, client, time: time); service.RequestPublish(); Assert.True(await client.WaitForPublishAsync()); @@ -242,7 +274,7 @@ public async Task Requesting_a_publish_that_changes_nothing_is_still_deduplicate for (var i = 0; i < 3; i++) { service.RequestPublish(); - await Task.Delay(FastInterval * 2); + await SettleAsync(service, time); } Assert.Single(client.Snapshots); @@ -279,14 +311,15 @@ public async Task Turning_the_card_off_stops_publishing_without_rebuilding_the_s // How EngineHost wires it: "card switched off" reads through as "no token". var enabled = true; - using var service = Create(state, client, token: () => enabled ? "ebs-token" : null); + var time = new ManualTimeProvider(); + using var service = Create(state, client, token: () => enabled ? "ebs-token" : null, time: time); service.RequestPublish(); Assert.True(await client.WaitForPublishAsync()); enabled = false; var attempts = client.Snapshots.Count; state.StarSystem = "Colonia"; - await Task.Delay(FastInterval * 4); + await SettleAsync(service, time); Assert.Equal(attempts, client.Snapshots.Count); } @@ -313,11 +346,15 @@ public async Task The_refresh_does_not_publish_before_the_host_has_replayed_the_ { var client = new FakeStreamStateApiClient(); + var time = new ManualTimeProvider(); using var service = new TwitchStreamCardService( new CommanderState(), StreamCardSources.Empty, client, static () => Endpoint, static () => "ebs-token", - null, null, FastInterval, clock: null, refreshInterval: TimeSpan.FromMilliseconds(50)); + null, null, FastInterval, clock: null, refreshInterval: TimeSpan.FromMilliseconds(50), time: time); - Assert.False(await client.WaitForPublishAsync(TimeSpan.FromMilliseconds(400))); + await SettleAsync(service, time); + time.Advance(TimeSpan.FromMilliseconds(50) * 8); // eight heartbeats' worth + await SettleAsync(service, time); + Assert.Empty(client.Snapshots); } [Fact] @@ -548,11 +585,19 @@ public async Task A_backend_fault_does_not_stop_publishing_the_way_a_revoked_tok }; using var service = Create(state, client); - service.ReauthRequired += () => reauth++; + service.ReauthRequired += () => Interlocked.Increment(ref reauth); + // ReauthRequired is raised before PublishCompleted for the same attempt, so once the fault + // has been reported, any reauth it was going to cause has already happened. + var faulted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + service.PublishCompleted += r => + { + if (r.Status == StreamStatePublishStatus.BackendRejectedByTwitch) faulted.TrySetResult(); + }; service.RequestPublish(); - await Task.Delay(FastInterval * 6); + await faulted.Task.WaitAsync(TimeSpan.FromSeconds(5)); - Assert.Equal(0, reauth); // the commander's sign-in is not the problem + Assert.Equal(0, Volatile.Read(ref reauth)); // the commander's sign-in is not the problem + Assert.False(service.StoppedForReauth); } [Fact] @@ -564,14 +609,15 @@ public async Task Retries_are_bounded_so_a_dead_ebs_is_not_polled_forever() Respond = _ => new StreamStatePublishResult(StreamStatePublishStatus.Failed, "connection refused"), }; - using var service = Create(state, client); + var time = new ManualTimeProvider(); + using var service = Create(state, client, time: time); service.RequestPublish(); - await Task.Delay(FastInterval * (TwitchStreamCardService.MaxPublishRetries + 6) * 2); + await SettleAsync(service, time); - // One initial attempt plus at most MaxPublishRetries, then the pump sleeps until something - // really changes. - Assert.InRange(client.Snapshots.Count, 1, TwitchStreamCardService.MaxPublishRetries + 1); + // One initial attempt plus MaxPublishRetries, then the pump sleeps until something really + // changes. + Assert.Equal(TwitchStreamCardService.MaxPublishRetries + 1, client.Snapshots.Count); } [Fact] @@ -643,14 +689,16 @@ public async Task State_changes_during_the_replay_publish_nothing_until_the_host var state = new CommanderState(); var client = new FakeStreamStateApiClient(); - using var service = Create(state, client); + var time = new ManualTimeProvider(); + using var service = Create(state, client, time: time); // The journal replay warms the picture property by property. state.Name = "CMDR Jameson"; state.StarSystem = "Nervi"; state.Docked = true; - Assert.False(await client.WaitForPublishAsync(TimeSpan.FromMilliseconds(300))); + await SettleAsync(service, time); + Assert.Empty(client.Snapshots); service.RequestPublish(); Assert.True(await client.WaitForPublishAsync()); @@ -662,18 +710,19 @@ public async Task The_card_comes_down_when_the_game_exits_and_stays_down() var state = new CommanderState { StarSystem = "Nervi" }; var client = new FakeStreamStateApiClient(); - using var service = Create(state, client); + var time = new ManualTimeProvider(); + using var service = Create(state, client, time: time); service.RequestPublish(); Assert.True(await client.WaitForPublishAsync()); service.GameExited(); - await WaitUntilAsync(() => client.Clears.Count == 1); + await SettleAsync(service, time); Assert.Equal(new[] { "ebs-token" }, client.Clears.ToArray()); // Journal chatter and further state changes after the Shutdown must not put it back. state.StarSystem = "Colonia"; - await Task.Delay(FastInterval * 4); + await SettleAsync(service, time); Assert.Single(client.Snapshots); Assert.Single(client.Clears); } @@ -718,15 +767,18 @@ public async Task A_closed_game_is_not_given_a_heartbeat() var state = new CommanderState { StarSystem = "Nervi" }; var client = new FakeStreamStateApiClient(); + var time = new ManualTimeProvider(); using var service = new TwitchStreamCardService( state, StreamCardSources.Empty, client, static () => Endpoint, static () => "ebs-token", - null, null, FastInterval, clock: null, refreshInterval: TimeSpan.FromMilliseconds(100)); + null, null, FastInterval, clock: null, refreshInterval: TimeSpan.FromMilliseconds(100), time: time); service.RequestPublish(); Assert.True(await client.WaitForPublishAsync()); service.GameExited(); - await WaitUntilAsync(() => client.Clears.Count == 1); + await SettleAsync(service, time); + Assert.Single(client.Clears); - await Task.Delay(TimeSpan.FromMilliseconds(500)); + time.Advance(TimeSpan.FromMilliseconds(100) * 5); // five heartbeats' worth + await SettleAsync(service, time); Assert.Single(client.Snapshots); Assert.Single(client.Clears); @@ -739,13 +791,14 @@ public async Task A_shutdown_during_developer_mode_does_not_touch_the_real_card( var client = new FakeStreamStateApiClient(); var dev = false; - using var service = Create(state, client, isSuppressed: () => dev); + var time = new ManualTimeProvider(); + using var service = Create(state, client, isSuppressed: () => dev, time: time); service.RequestPublish(); Assert.True(await client.WaitForPublishAsync()); dev = true; service.GameExited(); - await Task.Delay(FastInterval * 4); + await SettleAsync(service, time); Assert.Empty(client.Clears); } @@ -928,12 +981,13 @@ public async Task Preview_reports_what_would_be_published_without_sending_it() var state = new CommanderState { StarSystem = "Nervi" }; var client = new FakeStreamStateApiClient(); - using var service = Create(state, client, token: static () => null); + var time = new ManualTimeProvider(); + using var service = Create(state, client, token: static () => null, time: time); var preview = service.Preview(); Assert.Equal("Nervi", preview.Location!.System); + await SettleAsync(service, time); Assert.Empty(client.Snapshots); - Assert.False(await client.WaitForPublishAsync(TimeSpan.FromMilliseconds(200))); } }