using Febe.Core.Abstractions; using Febe.Core.Domain; using Febe.Core.Pacing; using Febe.Core.Storage; namespace Febe.Core.Engine; /// Outcome of «Controlla ora» (spec §7.8). public enum CheckNowStatus { /// Put on top of the queue. Queued, /// Outside the active window: Alberto must confirm with . NeedsConfirmation, /// Not possible now (budget exhausted, engine stopped, account not contactable); the message says why. Refused, } /// Answer to «Controlla ora»: an Italian message for the interface and, when needed, a confirmation token. public sealed record CheckNowResult(CheckNowStatus Status, string Message, string? ConfirmationToken = null, DateTimeOffset? ExpectedAround = null); /// Answer to «Riprendi». public sealed record ResumeResult(bool Resumed, string Message); /// /// The engine (spec §7): a background loop that plans the day, opens sessions inside the active window, composes them /// and rests between them. It only uses for time and for chance, so the /// same code runs under the virtual clock of the simulation. /// /// /// Commands from the interface (pause, resume, «Controlla ora», settings) are thread-safe and wake the loop. /// While Alberto uses the browser, during a pause and during a stop of the breaker the engine opens nothing. /// public sealed class EngineHost : IAsyncDisposable { private static readonly TimeSpan LongWait = TimeSpan.FromHours(6); private readonly EngineServices _s; private readonly IRecipeRunner _runner; private readonly RecipeHealth _health; private readonly RecentActions _recent = new(); private readonly SessionComposer _composer; private readonly Lock _gate = new(); private readonly Dictionary _confirmations = new(StringComparer.Ordinal); private readonly Dictionary _outsideWindowAllowed = []; private CancellationTokenSource _wake = new(); private CancellationTokenSource? _sessionCts; private CancellationTokenSource? _loopCts; private Task? _loop; private bool _initialized; private bool _manualWaiting; private DateTimeOffset? _plannedAfterStop; public EngineHost(EngineServices services, IRecipeRunner runner) { _s = services ?? throw new ArgumentNullException(nameof(services)); _runner = runner ?? throw new ArgumentNullException(nameof(runner)); _health = new RecipeHealth(services.Storage.Settings, services.Options.ConsecutiveFailuresToSuspend); _composer = new SessionComposer(services, runner, _health, _recent, ManualDone); Monitor = new EngineMonitor(services, this); _s.Breaker.StateChanged += OnBreakerChanged; } public EngineServices Services => _s; /// What the interface shows of the engine (Attività, sidebar, account settings panel). public IEngineMonitor Monitor { get; } /// Recipes suspended after repeated unrecognized formats, with when. public IReadOnlyDictionary SuspendedRecipes => _health.Suspended; internal IReadOnlyList RecentActions(int limit) => _recent.Snapshot(limit); /// Starts the background loop. public Task StartAsync(CancellationToken ct = default) { lock (_gate) { if (_loop is not null) { return Task.CompletedTask; } _loopCts = CancellationTokenSource.CreateLinkedTokenSource(ct); var token = _loopCts.Token; _loop = Task.Run(() => RunAsync(token), CancellationToken.None); } return Task.CompletedTask; } /// Stops the loop; a session in progress ends as interrupted and the browser goes to rest. public async Task StopAsync() { Task? loop; lock (_gate) { loop = _loop; _loopCts?.Cancel(); } if (loop is not null) { try { await loop.ConfigureAwait(false); } catch (OperationCanceledException) { } } lock (_gate) { _loop = null; _loopCts?.Dispose(); _loopCts = null; } } public async ValueTask DisposeAsync() { _s.Breaker.StateChanged -= OnBreakerChanged; await StopAsync().ConfigureAwait(false); _wake.Dispose(); } /// /// The loop of the engine, until is cancelled. runs it in the /// background; the simulation awaits it directly under the virtual clock. /// public async Task RunAsync(CancellationToken ct) { _s.Runtime.IsRunning = true; try { await InitializeAsync(ct).ConfigureAwait(false); while (true) { ct.ThrowIfCancellationRequested(); CancellationToken wake; lock (_gate) { wake = _wake.Token; } var wait = await StepAsync(ct).ConfigureAwait(false); if (wait is { } delay && delay > TimeSpan.Zero) { await WaitAsync(delay, wake, ct).ConfigureAwait(false); } } } finally { _s.Runtime.IsRunning = false; _s.Events.Publish(EngineNotificationKind.StateChanged); } } /// «Metti in pausa»: stops the engine until «Riprendi»; a session in progress ends now. public async Task PauseAsync(CancellationToken ct = default) { if (_s.Runtime.IsPaused) { return; } _s.Runtime.IsPaused = true; await _s.Storage.Settings.SetBoolAsync(EngineSettingKeys.Paused, true, ct).ConfigureAwait(false); CancelSession(); Wake(); await _s.Events.WriteAsync(EventSeverity.Info, EngineEventCodes.Paused, "Messo in pausa da te: Febe non apre nulla finché non premi «Riprendi».", ct: ct).ConfigureAwait(false); _s.Events.Publish(EngineNotificationKind.StateChanged); } /// /// «Riprendi»: ends a pause and, after a verification or a disconnection that Alberto fixed in the browser, reopens /// the breaker (with the gradual start). A throttle stop has a fixed length and is not shortened. /// public async Task ResumeAsync(CancellationToken ct = default) { var messages = new List(); var resumed = false; var breaker = _s.Breaker.State; if (breaker.Status is BreakerStatus.Challenge or BreakerStatus.Disconnected) { resumed |= await _s.Breaker.ResumeAsync(ct).ConfigureAwait(false); messages.Add(_s.Runtime.Profile.GradualStart ? "Ripreso dopo il fermo: i tetti ripartono dalla metà." : "Ripreso dopo il fermo."); } if (_s.Runtime.IsPaused) { _s.Runtime.IsPaused = false; await _s.Storage.Settings.SetBoolAsync(EngineSettingKeys.Paused, false, ct).ConfigureAwait(false); await _s.Events.WriteAsync(EventSeverity.Info, EngineEventCodes.Unpaused, "Ripreso dopo la pausa.", ct: ct).ConfigureAwait(false); messages.Add("Ripreso dopo la pausa."); resumed = true; } breaker = _s.Breaker.State; if (breaker.Status == BreakerStatus.Throttled && breaker.Until is { } until) { messages.Add($"Il fermo per rallentamento dura fino {ItalianText.AtDay(until, _s.Clock.Now, _s.Clock.LocalZone)} e non si accorcia."); } else if (resumed) { // The first session after «Riprendi» comes 2–10 minutes later, as after a start. var restart = _s.Clock.Now + _s.Random.Between(_s.Options.StartupDelayMin, _s.Options.StartupDelayMax); if (_s.Runtime.NextSessionAt is not { } planned || planned < restart) { _s.Runtime.NextSessionAt = restart; } } Wake(); _s.Events.Publish(EngineNotificationKind.StateChanged); return new ResumeResult(resumed, messages.Count == 0 ? "Febe stava già lavorando." : string.Join(" ", messages)); } /// /// «Controlla ora» (spec §7.8): puts the check of an account on top of the queue. It still goes through the /// Governor: with an exhausted budget Febe says so and does not do it. Outside the active window the first call /// returns with a token; calling again with the token allows that /// single check. /// public async Task CheckNowAsync(long accountId, string? confirmationToken = null, CancellationToken ct = default) { var now = _s.Clock.Now; var zone = _s.Clock.LocalZone; var account = await _s.Storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false); if (account is null) { return new CheckNowResult(CheckNowStatus.Refused, "Questo account non c'è più nell'elenco di Febe."); } var handle = ItalianText.Handle(account.Username); if (!CheckPolicy.AllowsManualCheck(account)) { return new CheckNowResult( CheckNowStatus.Refused, account.State == AccountState.ArchiveOnly ? $"{handle} è «Solo archivio»: Febe non lo contatta." : $"{handle} è privato e non lo segui: Febe non lo apre."); } var breaker = _s.Breaker.State; if (!breaker.AllowsSiteActions) { return new CheckNowResult(CheckNowStatus.Refused, Governor.BreakerMessage(breaker, now, zone)); } if (_s.Runtime.IsPaused) { return new CheckNowResult(CheckNowStatus.Refused, "Febe è in pausa: premi «Riprendi» prima di chiedere un controllo."); } var kind = CheckPolicy.WantsProfileChecks(account) ? EngineTaskKind.ProfileCheck : EngineTaskKind.AccountStories; var category = kind == EngineTaskKind.ProfileCheck ? ActionKind.ProfileOpen : ActionKind.StoryView; var budget = await _s.Governor.EvaluateBudgetAsync(category, accountId, ct).ConfigureAwait(false); if (!budget.Granted && budget.Reason != DenialReason.AccountNotContactable) { return new CheckNowResult(CheckNowStatus.Refused, (budget.Message ?? "Tetto raggiunto.") + " Il controllo non parte."); } var window = await _s.Planner.GetWindowAtAsync(now, ct).ConfigureAwait(false); var floor = PauseFloor(); if (window is null) { bool confirmed; lock (_gate) { PruneLocked(now); confirmed = confirmationToken is not null && _confirmations.TryGetValue(confirmationToken, out var pending) && pending.AccountId == accountId; if (confirmed) { _confirmations.Remove(confirmationToken!); _outsideWindowAllowed[accountId] = now + TimeSpan.FromHours(1); } } if (!confirmed) { var token = Guid.NewGuid().ToString("N"); lock (_gate) { _confirmations[token] = (accountId, now + _s.Options.ManualConfirmationLifetime); } var next = await _s.Planner.GetNextWindowAsync(now, ct).ConfigureAwait(false); var resumes = next is null ? string.Empty : $" Di solito riprende {ItalianText.Around(next.Start, now, zone)}."; return new CheckNowResult( CheckNowStatus.NeedsConfirmation, $"Sei fuori dalla fascia oraria, quando Febe non apre nulla da solo.{resumes} Confermi un solo controllo di {handle} adesso?", token); } await EnqueueManualAsync(kind, accountId, now, ct).ConfigureAwait(false); var expected = floor is { } f && f > now ? f : now; await _s.Events.WriteAsync( EventSeverity.Info, EngineEventCodes.ManualCheck, $"Controllo di {handle} fuori fascia, confermato da te: parte {(expected > now ? ItalianText.Around(expected, now, zone) : "adesso")}.", accountId, ct: ct).ConfigureAwait(false); Wake(); return new CheckNowResult(CheckNowStatus.Queued, $"Controllo di {handle} confermato: è l'unico che Febe fa fuori fascia.", null, expected); } await EnqueueManualAsync(kind, accountId, now, ct).ConfigureAwait(false); Wake(); if (_s.Runtime.CurrentSession is not null) { return new CheckNowResult(CheckNowStatus.Queued, $"Controllo di {handle} in cima alla coda: parte in questa sessione.", null, now); } // The next session comes as soon as the pause floor allows (spec §7.2: the floor always holds). var start = floor is { } minimum && minimum > now ? minimum : now; await _s.Events.WriteAsync( EventSeverity.Info, EngineEventCodes.ManualCheck, $"Controllo di {handle} chiesto da te: in cima alla coda.", accountId, ct: ct).ConfigureAwait(false); return new CheckNowResult( CheckNowStatus.Queued, start > now ? $"Controllo di {handle} in cima alla coda: parte {ItalianText.Around(start, now, zone)}, dopo la pausa minima fra due sessioni." : $"Controllo di {handle} in cima alla coda: parte adesso.", null, start); } /// «Leggi l'elenco dei seguiti» (spec §4.2): read at human pace inside the budgets, possibly over several sessions. public async Task RequestFollowingListAsync(CancellationToken ct = default) { var now = _s.Clock.Now; Volatile.Write(ref _manualWaiting, true); await _s.Storage.Tasks.EnqueueAsync( new EngineTask { Kind = EngineTaskKind.FollowingList, DueAt = now, Priority = _s.Options.ManualPriority, IsManual = true, CreatedAt = now, }, ct).ConfigureAwait(false); Wake(); _s.Events.Publish(EngineNotificationKind.StateChanged); } /// Accounts were added, removed or changed: the queue is brought in step before the next session. public async Task NotifyAccountsChangedAsync(CancellationToken ct = default) { await _composer.SyncQueueAsync(ct).ConfigureAwait(false); Wake(); _s.Events.Publish(EngineNotificationKind.StateChanged); } /// Alberto started or finished using the browser: when he starts, the session in progress ends at once. public void NotifyUserDrivingChanged() { if (_s.Runtime.UserIsDriving) { CancelSession(); } Wake(); _s.Events.Publish(EngineNotificationKind.StateChanged); } /// Reactivates a recipe suspended after repeated unrecognized formats (after the reader was updated). public async Task ResumeRecipeAsync(RecipeKind kind, CancellationToken ct = default) { var resumed = await _health.ResumeAsync(kind, ct).ConfigureAwait(false); if (resumed) { await _s.Events.WriteAsync( EventSeverity.Info, EngineEventCodes.RecipeResumed, $"«{ItalianText.Capitalize(SessionComposer.RecipeName(kind))}» riattivato.", ct: ct).ConfigureAwait(false); Wake(); } return resumed; } /// Stores and applies new engine settings, then replans. public async Task ApplySettingsAsync(EngineSettings settings, CancellationToken ct = default) { await _s.ApplySettingsAsync(settings, ct).ConfigureAwait(false); Wake(); } private async Task InitializeAsync(CancellationToken ct) { if (_initialized) { return; } var now = _s.Clock.Now; var store = _s.Storage; await _health.LoadAsync(ct).ConfigureAwait(false); // A session left open by a process that ended abruptly closes at its last action. var lastAction = await store.ActionLog.GetLastActionAtAsync(null, ct).ConfigureAwait(false); var last = await store.Sessions.GetLastAsync(ct).ConfigureAwait(false); if (last is { EndedAt: null }) { var end = lastAction is { } a && a > last.StartedAt && a <= now ? a : last.StartedAt; await store.Sessions.CloseInterruptedAsync(end, ct).ConfigureAwait(false); last = await store.Sessions.GetLastAsync(ct).ConfigureAwait(false); } await store.Tasks.RequeueRunningAsync(ct).ConfigureAwait(false); // A restart never brings the next session earlier than a program that stayed on would have. var lastEnd = Max(last?.EndedAt, lastAction); _s.Runtime.LastSessionEnd = lastEnd; var persisted = await store.Settings.GetInt64Async(EngineSettingKeys.NextSession, ct).ConfigureAwait(false); var next = now + _s.Random.Between(_s.Options.StartupDelayMin, _s.Options.StartupDelayMax); if (persisted is { } ms && DateTimeOffset.FromUnixTimeMilliseconds(ms) > next) { next = DateTimeOffset.FromUnixTimeMilliseconds(ms); } if (PauseFloor() is { } floor && floor > next) { next = floor; } _s.Runtime.NextSessionAt = next; _s.Runtime.StartedAt = now; _s.Runtime.HadSessionSinceStart = false; await store.Settings.SetInt64Async(EngineSettingKeys.NextSession, next.ToUnixTimeMilliseconds(), ct).ConfigureAwait(false); await _composer.SyncQueueAsync(ct).ConfigureAwait(false); _initialized = true; _s.Events.Publish(EngineNotificationKind.StateChanged); } /// One turn of the loop: runs a session when one is due, otherwise says how long to wait. private async Task StepAsync(CancellationToken ct) { var now = _s.Clock.Now; var runtime = _s.Runtime; if (runtime.IsPaused) { return LongWait; } var breaker = _s.Breaker.State; if (!breaker.AllowsSiteActions) { if (breaker.Status == BreakerStatus.Throttled && breaker.Until is { } until) { // After the stop the engine does not restart on the dot: a few minutes later, as after a start. if (_plannedAfterStop != until) { _plannedAfterStop = until; var restart = until + _s.Random.Between(_s.Options.StartupDelayMin, _s.Options.StartupDelayMax); if (runtime.NextSessionAt is not { } planned || planned < restart) { runtime.NextSessionAt = restart; } } return until - now; } return LongWait; } if (runtime.UserIsDriving || runtime.IsConnected == false) { // Alberto at the browser, or no Instagram session yet: look again in a while. return _s.Options.UserDrivingPoll; } var floor = PauseFloor(); var window = await _s.Planner.GetWindowAtAsync(now, ct).ConfigureAwait(false); if (window is null) { // Night: nothing on the engine's initiative. The only exception is a «Controlla ora» Alberto confirmed. var manual = await FindConfirmedManualAsync(now, ct).ConfigureAwait(false); if (manual is not null) { if (floor is { } f && f > now) { return f - now; } await RunSessionAsync(null, manual, ct).ConfigureAwait(false); return null; } var next = await _s.Planner.GetNextWindowAsync(now, ct).ConfigureAwait(false); if (next is null) { return LongWait; } var target = runtime.NextSessionAt is { } planned && planned > next.Start ? planned : next.Start; if (floor is { } minimum && minimum > target) { target = minimum; } runtime.NextSessionAt = target; return target - now; } var start = runtime.NextSessionAt ?? now; if (start > now && Volatile.Read(ref _manualWaiting)) { // «Controlla ora»: the next session comes as soon as the pause floor allows. start = now; } if (floor is { } pauseFloor && pauseFloor > start) { start = pauseFloor; } if (start > now) { runtime.NextSessionAt = start; return (start < window.End ? start : window.End) - now; } if (window.End - now < _s.Options.MinimumSessionRoom) { return window.End - now; } await RunSessionAsync(window, null, ct).ConfigureAwait(false); return null; } private async Task RunSessionAsync(ActiveWindow? window, EngineTask? outsideWindowTask, CancellationToken ct) { var s = _s; var profile = s.Runtime.Profile; var start = s.Clock.Now; var mood = s.Random.SessionMood(); var plannedEnd = start + s.Random.Between(profile.SessionMin, profile.SessionMax); if (window is not null && plannedEnd > window.End) { plannedEnd = window.End; } var record = await s.Storage.Sessions.StartAsync(start, ct).ConfigureAwait(false); var context = new SessionContext(record.Id, mood, start, plannedEnd, outsideWindowTask?.AccountId); using var sessionCts = CancellationTokenSource.CreateLinkedTokenSource(ct); lock (_gate) { _sessionCts = sessionCts; } s.Runtime.CurrentSession = context; s.Runtime.HadSessionSinceStart = true; Volatile.Write(ref _manualWaiting, false); s.Runtime.NextSessionAt = null; s.Events.Publish(EngineNotificationKind.StateChanged); var outcome = SessionOutcome.Completed; var interrupted = false; try { // A stop that arrived while the session was opening ends it before anything is done. if (!s.Breaker.State.AllowsSiteActions || s.Runtime.IsPaused || s.Runtime.UserIsDriving) { sessionCts.Cancel(); } var summary = await _composer.RunAsync(context, outsideWindowTask, sessionCts.Token).ConfigureAwait(false); if (summary.StoppedEarly || !s.Breaker.State.AllowsSiteActions || s.Runtime.IsPaused || s.Runtime.UserIsDriving) { outcome = StopOutcome(); } } catch (OperationCanceledException) when (!ct.IsCancellationRequested) { outcome = StopOutcome(); } catch (OperationCanceledException) { outcome = SessionOutcome.Interrupted; interrupted = true; throw; } catch (Exception ex) when (ex is not OutOfMemoryException) { outcome = SessionOutcome.Failed; await s.Events.WriteAsync( EventSeverity.Error, EngineEventCodes.RecipeFailed, $"La sessione si è chiusa per un errore imprevisto ({ex.GetType().Name}). Riprendo alla prossima.", sessionId: record.Id, ct: CancellationToken.None).ConfigureAwait(false); } finally { lock (_gate) { _sessionCts = null; } s.Runtime.CurrentSession = null; s.Runtime.Activity = null; await EndSessionAsync(record, context, outcome, outsideWindowTask, interrupted).ConfigureAwait(false); } } private async Task EndSessionAsync(SessionRecord record, SessionContext context, SessionOutcome outcome, EngineTask? outsideWindowTask, bool interrupted) { var s = _s; var ct = CancellationToken.None; // Rest on the empty page, except when the page must stay as it is (verification, disconnection) or Alberto is // using the browser (spec §6.1, §7.6). var breaker = s.Breaker.State; var keepPage = breaker.Status is BreakerStatus.Challenge or BreakerStatus.Disconnected || s.Runtime.UserIsDriving; if (!keepPage) { try { await _runner.RestAsync(ct).ConfigureAwait(false); } catch (Exception ex) when (ex is not OutOfMemoryException) { await s.Events.WriteAsync( EventSeverity.Warning, EngineEventCodes.RecipeFailed, $"Non sono riuscito a portare il browser sulla pagina vuota ({ex.GetType().Name}).", sessionId: record.Id, ct: ct).ConfigureAwait(false); } } var end = s.Clock.Now; var summaryText = $"{ItalianText.Count(context.ActionCount, "azione", "azioni")}, {ItalianText.Count(context.NewEntries, "contenuto nuovo", "contenuti nuovi")}"; var writes = new List { s.Storage.Sessions.EndAsync(record.Id, end, outcome, context.ActionCount, summaryText, ct) }; s.Runtime.LastSessionEnd = end; if (outsideWindowTask?.AccountId is { } manualAccount) { ManualDone(manualAccount); } if (interrupted) { await Task.WhenAll(writes).ConfigureAwait(false); return; } var pause = s.Random.Between(s.Runtime.Profile.PauseMin, s.Runtime.Profile.PauseMax); var next = end + pause; s.Runtime.NextSessionAt = next; writes.Add(s.Storage.Settings.SetInt64Async(EngineSettingKeys.NextSession, next.ToUnixTimeMilliseconds(), ct)); if ((await s.Storage.Accounts.ListAsync(ct).ConfigureAwait(false)).Any(a => a.IsFollowed && CheckPolicy.IsContactable(a))) { writes.Add(_composer.EnsureSweepTaskAsync(next, ct)); } var length = ItalianText.Duration(end - record.StartedAt); var tail = outcome switch { SessionOutcome.Throttled => " Chiusa per un rallentamento chiesto da Instagram.", SessionOutcome.Stopped => " Chiusa prima del previsto.", SessionOutcome.Failed => " Chiusa per un errore.", _ => string.Empty, }; writes.Add(s.Events.WriteAsync( outcome == SessionOutcome.Completed ? EventSeverity.Info : EventSeverity.Warning, EngineEventCodes.SessionEnded, $"Sessione di {length}: {summaryText}.{tail}", sessionId: record.Id, ct: ct)); await Task.WhenAll(writes).ConfigureAwait(false); s.Events.Publish(EngineNotificationKind.StateChanged); } private SessionOutcome StopOutcome() => _s.Breaker.State.Status == BreakerStatus.Throttled ? SessionOutcome.Throttled : SessionOutcome.Stopped; private DateTimeOffset? PauseFloor() => _s.Runtime.LastSessionEnd is { } end ? end + _s.Runtime.Profile.PauseMin : null; private async Task FindConfirmedManualAsync(DateTimeOffset now, CancellationToken ct) { Dictionary allowed; lock (_gate) { PruneLocked(now); if (_outsideWindowAllowed.Count == 0) { return null; } allowed = new Dictionary(_outsideWindowAllowed); } var due = await _s.Storage.Tasks.PeekDueAsync(now, 100, ct).ConfigureAwait(false); return due.FirstOrDefault(t => t.IsManual && t.AccountId is { } id && allowed.ContainsKey(id)); } private void ManualDone(long accountId) { lock (_gate) { _outsideWindowAllowed.Remove(accountId); } } private void PruneLocked(DateTimeOffset now) { foreach (var token in _confirmations.Where(c => c.Value.Expires <= now).Select(c => c.Key).ToList()) { _confirmations.Remove(token); } foreach (var account in _outsideWindowAllowed.Where(c => c.Value <= now).Select(c => c.Key).ToList()) { _outsideWindowAllowed.Remove(account); } } private async Task EnqueueManualAsync(EngineTaskKind kind, long accountId, DateTimeOffset now, CancellationToken ct) { Volatile.Write(ref _manualWaiting, true); await _s.Storage.Tasks.EnqueueAsync( new EngineTask { Kind = kind, AccountId = accountId, DueAt = now, Priority = _s.Options.ManualPriority, IsManual = true, CreatedAt = now, }, ct).ConfigureAwait(false); } private void OnBreakerChanged(object? sender, BreakerState state) { // Signals arrive on capture threads: the engine is never run inline on them (it may need the browser to answer). // The composer also checks the breaker before every recipe, so the session stops at once either way. CancellationTokenSource? session = null; if (!state.AllowsSiteActions) { lock (_gate) { session = _sessionCts; } } _ = Task.Run(() => { Cancel(session); Wake(); _s.Events.Publish(EngineNotificationKind.StateChanged); }); } private void CancelSession() { CancellationTokenSource? session; lock (_gate) { session = _sessionCts; } Cancel(session); } private static void Cancel(CancellationTokenSource? session) { try { session?.Cancel(); } catch (ObjectDisposedException) { } } /// Wakes the loop if it is waiting; the wait it was in is cancelled synchronously. private void Wake() { CancellationTokenSource old; lock (_gate) { old = _wake; _wake = new CancellationTokenSource(); } // The old source is not disposed: the loop may still hold its (now cancelled) token. old.Cancel(); } private async Task WaitAsync(TimeSpan delay, CancellationToken wake, CancellationToken ct) { if (wake.IsCancellationRequested) { return; } using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, wake); try { await _s.Clock.Delay(delay, linked.Token).ConfigureAwait(false); } catch (OperationCanceledException) when (!ct.IsCancellationRequested) { // Woken by a command: look again. } } private static DateTimeOffset? Max(DateTimeOffset? a, DateTimeOffset? b) => a is null ? b : b is null ? a : a > b ? a : b; }