Skip to content
25 changes: 20 additions & 5 deletions src/EDNexus.Core/Discord/DiscordPresenceService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ public static string ResolveApplicationId(string? configured)
private readonly PresenceThrottle _throttle;
private readonly Func<bool> _isSuppressed;
private readonly Func<DateTimeOffset> _clock;
private readonly TimeProvider _time;
private readonly DateTimeOffset _sessionStartedAt;
private readonly object _gate = new();

Expand All @@ -73,6 +74,8 @@ public static string ResolveApplicationId(string? configured)
private DiscordPrivacyOptions _privacy;
private bool _clearedForSuppression;
private CancellationTokenSource? _pending;
/// <summary>The trailing send scheduled last (or a completed task). Test hook: see <see cref="PendingSend"/>.</summary>
private Task _pendingSend = Task.CompletedTask;
private bool _disposed;

/// <param name="state">The live commander picture to mirror. Never written to.</param>
Expand All @@ -94,17 +97,21 @@ public DiscordPresenceService(
DiscordPrivacyOptions? privacy = null)
: this(state, client, DefaultMinInterval, isSuppressed, null, privacy) { }

/// <summary>Test-only constructor: a shortened throttle window and/or a controllable clock.</summary>
/// <summary>
/// Test-only constructor: a shortened throttle window and/or a controllable clock.
/// <paramref name="time"/> drives the trailing send's wait, and the clock when <paramref name="clock"/> is null.
/// </summary>
internal DiscordPresenceService(
CommanderState state, IDiscordRpcClient client, TimeSpan minInterval,
Func<bool>? isSuppressed = null, Func<DateTimeOffset>? 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();
Expand Down Expand Up @@ -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)
Expand All @@ -253,6 +260,14 @@ private void SchedulePendingLocked(TimeSpan delay)
});
}

/// <summary>
/// Test hook: the trailing send scheduled last, which finishes once it has sent or stood down.
/// </summary>
internal Task PendingSend
{
get { lock (_gate) return _pendingSend; }
}

public void Dispose()
{
lock (_gate)
Expand Down
42 changes: 33 additions & 9 deletions src/EDNexus.Core/Reporting/InaraBridge.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<DateTimeOffset> _sendTimes = new(); // start time of recent requests (rolling window)
private readonly CancellationTokenSource _disposeCts = new();
Expand All @@ -64,9 +66,13 @@ public sealed class InaraBridge : IAsyncDisposable
public InaraBridge(JournalEventBus bus, AppSettings settings, InaraClient client, Func<bool>? isSuppressed = null, IReportingLog? log = null)
: this(bus, settings, client, SessionStartDebounce, MinInterval, isSuppressed, log) { }

/// <summary>Test-only constructor allowing the debounce/throttle windows to be shortened.</summary>
internal InaraBridge(JournalEventBus bus, AppSettings settings, InaraClient client, TimeSpan debounceDelay, TimeSpan minInterval, Func<bool>? isSuppressed = null, IReportingLog? log = null, TimeSpan? retryBackoff = null)
/// <summary>
/// Test-only constructor allowing the debounce/throttle windows to be shortened, and the clock that
/// drives them and the retry backoff to be replaced.
/// </summary>
internal InaraBridge(JournalEventBus bus, AppSettings settings, InaraClient client, TimeSpan debounceDelay, TimeSpan minInterval, Func<bool>? isSuppressed = null, IReportingLog? log = null, TimeSpan? retryBackoff = null, TimeProvider? time = null)
{
_time = time ?? TimeProvider.System;
_retryBackoff = retryBackoff ?? RetryBackoff;
_settings = settings;
_client = client;
Expand Down Expand Up @@ -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;
}

/// <summary>
/// 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.
/// </summary>
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()
Expand Down Expand Up @@ -267,11 +291,11 @@ private async Task SendAsync(Task previous, InaraIdentity identity, List<InaraEv
return;
}

try { await Task.Delay(wait, _disposing ? CancellationToken.None : _disposeCts.Token).ConfigureAwait(false); }
try { await Task.Delay(wait, _time, _disposing ? CancellationToken.None : _disposeCts.Token).ConfigureAwait(false); }
catch (OperationCanceledException) { } // dispose began: re-evaluate against the shutdown cap
}

lock (_gate) _sendTimes.Enqueue(DateTimeOffset.UtcNow);
lock (_gate) _sendTimes.Enqueue(_time.GetUtcNow());
var response = await _client.SendAsync(identity, batch).ConfigureAwait(false);

LogUpload(batch, response);
Expand All @@ -297,7 +321,7 @@ private async Task SendAsync(Task previous, InaraIdentity identity, List<InaraEv
private void TrackRateLimit(InaraResponse response)
{
DateTimeOffset? next;
if (response.IsRateLimited) next = DateTimeOffset.UtcNow;
if (response.IsRateLimited) next = _time.GetUtcNow();
else if (response.IsOk) next = null;
else return; // some other failure says nothing about the limit either way

Expand All @@ -314,7 +338,7 @@ private void TrackRateLimit(InaraResponse response)
private TimeSpan TimeUntilSendAllowed()
{
var window = _minInterval * MaxSendsPerWindow;
var now = DateTimeOffset.UtcNow;
var now = _time.GetUtcNow();
lock (_gate)
{
while (_sendTimes.Count > 0 && now - _sendTimes.Peek() >= window) _sendTimes.Dequeue();
Expand Down Expand Up @@ -378,7 +402,7 @@ private void LogUpload(List<InaraEvent> 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"),
Expand Down
97 changes: 88 additions & 9 deletions src/EDNexus.Core/Twitch/TwitchStreamCardService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ public sealed class TwitchStreamCardService : IDisposable
private readonly Func<StreamCardVisibility> _visibility;
private readonly Func<bool> _isSuppressed;
private readonly Func<DateTimeOffset> _clock;
private readonly TimeProvider _time;
private readonly EbsCleanupQueue? _cleanup;
private readonly TimeSpan _minInterval;
private readonly CancellationTokenSource _cts = new();
Expand Down Expand Up @@ -154,7 +155,11 @@ public TwitchStreamCardService(
EbsCleanupQueue? cleanup = null)
: this(state, sources, client, updateStateEndpoint, token, visibility, isSuppressed, DefaultMinInterval, null, null, cleanup) { }

/// <summary>Test-only constructor: a shortened publish interval and/or a controllable clock.</summary>
/// <summary>
/// Test-only constructor: a shortened publish interval and/or a controllable clock.
/// <paramref name="time"/> drives the pump's waits (the rate-limit floor and the heartbeat) as well
/// as the clock when <paramref name="clock"/> is null.
/// </summary>
internal TwitchStreamCardService(
CommanderState state,
StreamCardSources sources,
Expand All @@ -166,9 +171,11 @@ internal TwitchStreamCardService(
TimeSpan minInterval,
Func<DateTimeOffset>? 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;
Expand All @@ -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;
Expand Down Expand Up @@ -265,7 +272,8 @@ private void OnStateChanged(object? sender, PropertyChangedEventArgs e)

/// <summary>
/// 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.
/// </summary>
private void MarkDirty()
{
Expand All @@ -276,17 +284,23 @@ 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)
{
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; }

Expand Down Expand Up @@ -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,
Expand All @@ -350,6 +364,71 @@ private async Task PumpAsync(CancellationToken ct)
}
}

/// <summary>
/// Waits for <see cref="MarkDirty"/> or for <paramref name="timeout"/> to pass on <see cref="_time"/>,
/// whichever comes first. True when the card was marked dirty.
/// </summary>
private async Task<bool> 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;

/// <summary>
/// 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.
/// </summary>
internal Task WhenIdleAsync()
{
lock (_idleGate)
{
if (_parked && _dirty.CurrentCount == 0) return Task.CompletedTask;
Comment thread
demortes marked this conversation as resolved.
Resolved
_idle ??= new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
if (_idle.Task.IsCompleted) _idle = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
return _idle.Task;
}
}

/// <summary>
/// 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.
Expand Down
7 changes: 3 additions & 4 deletions tests/EDNexus.Tests/Discord/DiscordPresenceServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
17 changes: 10 additions & 7 deletions tests/EDNexus.Tests/Discord/DiscordPrivacyTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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")));
Expand Down
2 changes: 1 addition & 1 deletion tests/EDNexus.Tests/EliteBgs/EliteBgsClientTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
Loading
Loading