Collegamento e motore: correzioni regole-1, regole-2, regole-6, websec-1, websec-5, websec-6, engine-1, engine-2, sched-1
Pagine aperte da Alberto non sono segnali (regole-1); cookie perso fuori sessione = disconnessione (regole-2); pagina a riposo quando Alberto lascia il browser (regole-6); la lease di «Accedi»/«Usa il browser» finisce da sola dopo 2 minuti senza vista remota né finestra (websec-1); ping con scadenza sulla vista remota (websec-5); aperture della vista remota serializzate (websec-6); orologio virtuale senza fine anticipata (engine-1); la sincronizzazione della coda non duplica il compito in corso (engine-2); raccolte in evidenza programmate (sched-1). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
19 files changed
+1122
-92
No files matched your search
@@ -31,6 +31,15 @@ public sealed class SignalDetector : IResponseObserver, IResponseConsumer, IStop
|
||||
|
||||
public TimeSpan DedupeWindow { get; }
|
||||
|
||||
/// <summary>
|
||||
/// True while the page is Alberto's, not the engine's: he holds the «driving» lease and no session runs. The
|
||||
/// addresses he opens then — the login page of «Accedi a Instagram», a verification he completes by hand — are not
|
||||
/// engine actions (rule 7 of §2) nor the page «going back to the login» of §7.6, so path rules (navigations and
|
||||
/// main documents) are not signals. Status and text rules, and the cookie check of the recipes, still are.
|
||||
/// Null: the page is always the engine's.
|
||||
/// </summary>
|
||||
public Func<bool>? UserOwnsPage { get; init; }
|
||||
|
||||
/// <summary>Raised after a signal has been reported to the breaker.</summary>
|
||||
public event EventHandler<Signal>? SignalRaised;
|
||||
|
||||
@@ -49,6 +58,7 @@ public sealed class SignalDetector : IResponseObserver, IResponseConsumer, IStop
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(response);
|
||||
var scope = response.IsMainFrameDocument ? SignalScope.Document : SignalScope.Subresource;
|
||||
var paths = !UserIsOnPage();
|
||||
foreach (var rule in _rules.Rules)
|
||||
{
|
||||
if (!rule.HostKinds.Contains(response.HostKind) || (rule.Scope & scope) == 0)
|
||||
@@ -57,7 +67,7 @@ public sealed class SignalDetector : IResponseObserver, IResponseConsumer, IStop
|
||||
}
|
||||
|
||||
if ((rule.Statuses.Count > 0 && rule.Statuses.Contains(response.Status))
|
||||
|| (rule.Path is not null && SafeIsMatch(rule.Path, response.Path)))
|
||||
|| (paths && rule.Path is not null && SafeIsMatch(rule.Path, response.Path)))
|
||||
{
|
||||
return Raise(rule.Level, rule.Code, response.Url);
|
||||
}
|
||||
@@ -66,10 +76,15 @@ public sealed class SignalDetector : IResponseObserver, IResponseConsumer, IStop
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Path rules on a main-frame navigation.</summary>
|
||||
/// <summary>Path rules on a main-frame navigation (none while the page is Alberto's: <see cref="UserOwnsPage"/>).</summary>
|
||||
public Signal? ObserveNavigation(NavigationDescriptor navigation)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(navigation);
|
||||
if (UserIsOnPage())
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach (var rule in _rules.Rules)
|
||||
{
|
||||
if (rule.Path is null || (rule.Scope & SignalScope.Navigation) == 0 || !rule.HostKinds.Contains(navigation.HostKind))
|
||||
@@ -144,6 +159,8 @@ public sealed class SignalDetector : IResponseObserver, IResponseConsumer, IStop
|
||||
public Signal? ObserveSessionCookie(bool present) =>
|
||||
present ? null : Raise(SignalLevel.Disconnect, SignalRules.SessionCookieMissingCode, null);
|
||||
|
||||
private bool UserIsOnPage() => UserOwnsPage?.Invoke() == true;
|
||||
|
||||
private Signal? Raise(SignalLevel level, string code, string? url)
|
||||
{
|
||||
var now = _clock.Now;
|
||||
|
||||
@@ -44,6 +44,19 @@ public static class CheckPolicy
|
||||
|
||||
public static bool WantsStories(Account account) => (account.ContentTypes & ContentTypes.Stories) != 0;
|
||||
|
||||
public static bool WantsHighlights(Account account) => (account.ContentTypes & ContentTypes.Highlights) != 0;
|
||||
|
||||
/// <summary>
|
||||
/// Interval between two looks at the same highlight collection («Raccolta in evidenza»): eight story intervals of
|
||||
/// the frequency, between one and seven days (High 1 day, Normal 2, Low a little less than 3). Collections change far
|
||||
/// less often than stories, and mostly with stories already saved (H9); a new collection is looked at at once.
|
||||
/// </summary>
|
||||
public static TimeSpan HighlightInterval(Account account)
|
||||
{
|
||||
var ticks = StoryMaxInterval(account).Ticks * 8;
|
||||
return TimeSpan.FromTicks(Math.Clamp(ticks, TimeSpan.FromDays(1).Ticks, TimeSpan.FromDays(7).Ticks));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Interval between profile checks. Not followed: ~12 h / ~3 h / ~75 min (Su misura: the hours chosen). Followed: the
|
||||
/// sweep discovers new posts, the profile check is only a reconciliation every 24 / 12 / 6 hours (Su misura: four
|
||||
|
||||
@@ -51,6 +51,7 @@ public sealed class EngineHost : IAsyncDisposable
|
||||
private Task? _loop;
|
||||
private bool _initialized;
|
||||
private bool _manualWaiting;
|
||||
private int _restAfterDriving;
|
||||
private DateTimeOffset? _plannedAfterStop;
|
||||
|
||||
public EngineHost(EngineServices services, IRecipeRunner runner)
|
||||
@@ -363,11 +364,15 @@ public sealed class EngineHost : IAsyncDisposable
|
||||
_s.Events.Publish(EngineNotificationKind.StateChanged);
|
||||
}
|
||||
|
||||
/// <summary>Alberto started or finished using the browser: when he starts, the session in progress ends at once.</summary>
|
||||
/// <summary>
|
||||
/// Alberto started or finished using the browser: when he starts, the session in progress ends at once (leaving the
|
||||
/// page to him); when he lets go, the loop puts the page back to rest.
|
||||
/// </summary>
|
||||
public void NotifyUserDrivingChanged()
|
||||
{
|
||||
if (_s.Runtime.UserIsDriving)
|
||||
{
|
||||
Volatile.Write(ref _restAfterDriving, 1);
|
||||
CancelSession();
|
||||
}
|
||||
|
||||
@@ -451,6 +456,15 @@ public sealed class EngineHost : IAsyncDisposable
|
||||
{
|
||||
var now = _s.Clock.Now;
|
||||
var runtime = _s.Runtime;
|
||||
if (runtime.UserIsDriving)
|
||||
{
|
||||
Volatile.Write(ref _restAfterDriving, 1);
|
||||
}
|
||||
else if (Interlocked.Exchange(ref _restAfterDriving, 0) == 1)
|
||||
{
|
||||
await RestAfterDrivingAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (runtime.IsPaused)
|
||||
{
|
||||
return LongWait;
|
||||
@@ -630,6 +644,8 @@ public sealed class EngineHost : IAsyncDisposable
|
||||
var keepPage = breaker.Status is BreakerStatus.Challenge or BreakerStatus.Disconnected || s.Runtime.UserIsDriving;
|
||||
if (!keepPage)
|
||||
{
|
||||
// This rest also serves a driving period that ended during the session.
|
||||
Interlocked.Exchange(ref _restAfterDriving, 0);
|
||||
try
|
||||
{
|
||||
await _runner.RestAsync(ct).ConfigureAwait(false);
|
||||
@@ -687,6 +703,36 @@ public sealed class EngineHost : IAsyncDisposable
|
||||
s.Events.Publish(EngineNotificationKind.StateChanged);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Alberto let go of the browser and no session runs: the page goes back to rest (spec §6.1), so that nothing he or a
|
||||
/// cancelled session left open stays on the site — a story viewer moves on by itself to other accounts (§6.3).
|
||||
/// After a verification or a disconnection the page stays as it is until «Riprendi» (§7.6).
|
||||
/// </summary>
|
||||
private async Task RestAfterDrivingAsync(CancellationToken ct)
|
||||
{
|
||||
if (_s.Breaker.State.Status is BreakerStatus.Challenge or BreakerStatus.Disconnected)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await _runner.RestAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
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}).",
|
||||
ct: CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private SessionOutcome StopOutcome() =>
|
||||
_s.Breaker.State.Status == BreakerStatus.Throttled ? SessionOutcome.Throttled : SessionOutcome.Stopped;
|
||||
|
||||
|
||||
@@ -7,9 +7,10 @@ namespace Febe.Core.Engine;
|
||||
|
||||
/// <summary>
|
||||
/// Composes and runs one session (spec §7.2, §7.3): commands of Alberto first, then usually the Giro dei seguiti,
|
||||
/// the flagged and due stories, the expired profile checks, finally a few pages of history on one account. About one
|
||||
/// session in three stops after the sweep and the stories. Accounts are taken in a random order weighted by frequency
|
||||
/// and delay. Planned work lives in the persisted task queue; this class keeps it in step with the accounts.
|
||||
/// the flagged and due stories, the expired profile checks and highlight collections, finally a few pages of history on
|
||||
/// one account. About one session in three stops after the sweep and the stories. Accounts are taken in a random order
|
||||
/// weighted by frequency and delay. Planned work lives in the persisted task queue; this class keeps it in step with
|
||||
/// the accounts.
|
||||
/// </summary>
|
||||
internal sealed class SessionComposer
|
||||
{
|
||||
@@ -22,6 +23,12 @@ internal sealed class SessionComposer
|
||||
private readonly Action<long> _manualDone;
|
||||
private readonly Lock _noticeGate = new();
|
||||
private readonly HashSet<(string Code, long? Account, DateOnly Day)> _notices = [];
|
||||
|
||||
// The interface calls SyncQueueAsync while a session may be running. A recipe's task is Running in the database
|
||||
// between its start and its bookkeeping, and then has its successor: under this gate the queue is looked at only
|
||||
// when every task is pending, in flight (_inFlight) or already replaced by its successor, never in between.
|
||||
private readonly SemaphoreSlim _queueGate = new(1, 1);
|
||||
private EngineTask? _inFlight;
|
||||
private DateTimeOffset? _lastSweepAt;
|
||||
private bool _lastSweepLoaded;
|
||||
|
||||
@@ -114,7 +121,7 @@ internal sealed class SessionComposer
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Expired profile checks and other planned work.
|
||||
// 4. Expired profile checks, highlight collections and other planned work.
|
||||
if (!light && !Over(state, ct))
|
||||
{
|
||||
var now = Clock.Now;
|
||||
@@ -146,11 +153,25 @@ internal sealed class SessionComposer
|
||||
|
||||
/// <summary>
|
||||
/// Keeps the queue in step with the accounts: a profile check and a story check (as the account wants them) for
|
||||
/// every contactable account, a backfill task for every account «Storico in corso», a Giro dei seguiti when someone
|
||||
/// is followed; pending planned tasks of accounts that may not be contacted are cancelled. Commands of Alberto
|
||||
/// are left alone.
|
||||
/// every contactable account, a look at each highlight collection on its profile, a backfill task for every account
|
||||
/// «Storico in corso», a Giro dei seguiti when someone is followed; pending planned tasks of accounts that may not be
|
||||
/// contacted are cancelled. Commands of Alberto are left alone, and so is the task of the recipe in progress: its
|
||||
/// own bookkeeping plans the next one.
|
||||
/// </summary>
|
||||
public async Task<Dictionary<long, Account>> SyncQueueAsync(CancellationToken ct)
|
||||
{
|
||||
await _queueGate.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
return await SyncQueueLockedAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_queueGate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<Dictionary<long, Account>> SyncQueueLockedAsync(CancellationToken ct)
|
||||
{
|
||||
var now = Clock.Now;
|
||||
var accounts = (await Store.Accounts.ListAsync(ct).ConfigureAwait(false)).ToDictionary(a => a.Id);
|
||||
@@ -161,14 +182,14 @@ internal sealed class SessionComposer
|
||||
{
|
||||
var tasks = byAccount[account.Id].Where(t => !t.IsManual).ToList();
|
||||
var wanted = WantedKinds(account);
|
||||
foreach (var task in tasks.Where(t => !wanted.ContainsKey(t.Kind) && !(t.Kind == EngineTaskKind.AccountStories && t.Priority >= Options.FlaggedStoriesPriority && CheckPolicy.IsContactable(account))))
|
||||
foreach (var task in tasks.Where(t => t.Kind != EngineTaskKind.HighlightCheck && !wanted.ContainsKey(t.Kind) && !(t.Kind == EngineTaskKind.AccountStories && t.Priority >= Options.FlaggedStoriesPriority && CheckPolicy.IsContactable(account))))
|
||||
{
|
||||
await Store.Tasks.CancelAsync(task.Id, now, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var (kind, dueAt) in wanted)
|
||||
{
|
||||
if (tasks.Any(t => t.Kind == kind))
|
||||
if (tasks.Any(t => t.Kind == kind) || InFlight(account.Id, kind, null))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@@ -177,6 +198,8 @@ internal sealed class SessionComposer
|
||||
new EngineTask { Kind = kind, AccountId = account.Id, DueAt = dueAt ?? now, CreatedAt = now },
|
||||
ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await SyncHighlightsAsync(account, tasks, now, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var anyFollowed = accounts.Values.Any(a => a.IsFollowed && CheckPolicy.IsContactable(a));
|
||||
@@ -196,6 +219,52 @@ internal sealed class SessionComposer
|
||||
return accounts;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «Raccolta in evidenza» (spec §6.3) for an account that wants «Storie in evidenza»: one task per collection the
|
||||
/// profile check found (payload: its Instagram identifier), due at once for a collection never looked at, then
|
||||
/// after <see cref="CheckPolicy.HighlightInterval"/>. Tasks of collections that left the profile, or of accounts
|
||||
/// that no longer want them or may not be contacted, are cancelled.
|
||||
/// </summary>
|
||||
private async Task SyncHighlightsAsync(Account account, List<EngineTask> tasks, DateTimeOffset now, CancellationToken ct)
|
||||
{
|
||||
var planned = tasks.Where(t => t.Kind == EngineTaskKind.HighlightCheck).ToList();
|
||||
var collections = new Dictionary<string, Highlight>(StringComparer.Ordinal);
|
||||
if (CheckPolicy.IsContactable(account) && CheckPolicy.WantsHighlights(account))
|
||||
{
|
||||
foreach (var highlight in await Store.Highlights.ListAsync(account.Id, includeRemoved: false, ct).ConfigureAwait(false))
|
||||
{
|
||||
if (highlight.InstagramId is { Length: > 0 } id)
|
||||
{
|
||||
collections.TryAdd(id, highlight);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var task in planned.Where(t => t.Payload is null || !collections.ContainsKey(t.Payload)))
|
||||
{
|
||||
await Store.Tasks.CancelAsync(task.Id, now, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var (id, highlight) in collections)
|
||||
{
|
||||
if (planned.Any(t => t.Payload == id) || InFlight(account.Id, EngineTaskKind.HighlightCheck, id))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var due = highlight.LastCheckedAt is { } last
|
||||
? last + CheckPolicy.NextCheckDelay(_s.Random, CheckPolicy.HighlightInterval(account))
|
||||
: now;
|
||||
await Store.Tasks.EnqueueAsync(
|
||||
new EngineTask { Kind = EngineTaskKind.HighlightCheck, AccountId = account.Id, Payload = id, DueAt = due, CreatedAt = now },
|
||||
ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Whether the recipe in progress runs a task of this kind (and payload) for the account. Under the queue gate.</summary>
|
||||
private bool InFlight(long accountId, EngineTaskKind kind, string? payload) =>
|
||||
_inFlight is { } task && task.AccountId == accountId && task.Kind == kind && (payload is null || task.Payload == payload);
|
||||
|
||||
/// <summary>The Giro dei seguiti shown in the queue at the next session.</summary>
|
||||
public Task EnsureSweepTaskAsync(DateTimeOffset dueAt, CancellationToken ct) =>
|
||||
Store.Tasks.EnqueueAsync(
|
||||
@@ -359,6 +428,13 @@ internal sealed class SessionComposer
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// One highlight collection per account and session, and none on a profile already opened in this session:
|
||||
// the others wait for the next session instead of reopening the same profile again and again.
|
||||
if (task.Kind == EngineTaskKind.HighlightCheck && (state.Visited.Contains(id) || !state.HighlightAccounts.Add(id)))
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
switch (task.Kind)
|
||||
@@ -610,7 +686,7 @@ internal sealed class SessionComposer
|
||||
return null;
|
||||
}
|
||||
|
||||
if (task is not null && !await Store.Tasks.TryStartAsync(task.Id, Clock.Now, ct).ConfigureAwait(false))
|
||||
if (task is not null && !await StartTaskAsync(task, ct).ConfigureAwait(false))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
@@ -627,7 +703,16 @@ internal sealed class SessionComposer
|
||||
{
|
||||
if (task is not null)
|
||||
{
|
||||
await RequeueAsync(task, "Interrotta", Clock.Now).ConfigureAwait(false);
|
||||
await _queueGate.WaitAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await RequeueAsync(task, "Interrotta", Clock.Now).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_inFlight = null;
|
||||
_queueGate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
throw;
|
||||
@@ -643,11 +728,41 @@ internal sealed class SessionComposer
|
||||
}
|
||||
|
||||
context.AddNewEntries(outcome.NewEntries);
|
||||
await ApplyOutcomeAsync(task, request, account, outcome, state).ConfigureAwait(false);
|
||||
await _queueGate.WaitAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await ApplyOutcomeAsync(task, request, account, outcome, state).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_inFlight = null;
|
||||
_queueGate.Release();
|
||||
}
|
||||
|
||||
_s.Events.Publish(EngineNotificationKind.ActivityChanged);
|
||||
return outcome;
|
||||
}
|
||||
|
||||
/// <summary>Pending → Running, recorded as the task in flight under the queue gate. False when it was not pending.</summary>
|
||||
private async Task<bool> StartTaskAsync(EngineTask task, CancellationToken ct)
|
||||
{
|
||||
await _queueGate.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
if (!await Store.Tasks.TryStartAsync(task.Id, Clock.Now, ct).ConfigureAwait(false))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
_inFlight = task;
|
||||
return true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_queueGate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ApplyOutcomeAsync(EngineTask? task, RecipeRequest request, Account? account, RecipeOutcome outcome, SessionState state)
|
||||
{
|
||||
// Bookkeeping always completes, even when the session has just been cancelled. Independent writes are queued
|
||||
@@ -1022,6 +1137,9 @@ internal sealed class SessionComposer
|
||||
/// <summary>Commands of Alberto already taken up in this session.</summary>
|
||||
public HashSet<long> ManualDone { get; } = [];
|
||||
|
||||
/// <summary>Accounts whose highlight collection was taken up in this session (one per account and session).</summary>
|
||||
public HashSet<long> HighlightAccounts { get; } = [];
|
||||
|
||||
public bool Stop { get; set; }
|
||||
|
||||
public int Recipes { get; set; }
|
||||
|
||||
@@ -13,6 +13,11 @@ namespace Febe.Core.Simulation;
|
||||
/// <para>Delays are rounded up to whole milliseconds, the resolution of the database, so stored and computed times compare exactly.</para>
|
||||
/// <para>With <see cref="AutoAdvance"/> a delay moves time forward at once: handy for one component under test, without a driver.</para>
|
||||
/// <para>Each actor must wait on at most one delay at a time, otherwise the driver could advance before the second is registered.</para>
|
||||
/// <para>
|
||||
/// A delay may be cancelled from any thread, also one that is not an actor (the engine cancels a session from the thread
|
||||
/// pool when a signal arrives). The cancelled actor runs again, so the driver decides whether to fire the next timer or
|
||||
/// to finish under the same lock in which it looks again at how many actors still wait.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class VirtualClock : IClock
|
||||
{
|
||||
@@ -120,17 +125,9 @@ public sealed class VirtualClock : IClock
|
||||
/// <summary>Moves time to <paramref name="target"/>, firing in order the timers that fall due on the way.</summary>
|
||||
public void AdvanceTo(DateTimeOffset target)
|
||||
{
|
||||
while (TryFireNext(target))
|
||||
while (FireNextOrFinish(target, running: 0) != Step.Finished)
|
||||
{
|
||||
}
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
if (target > _now)
|
||||
{
|
||||
_now = target;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -152,16 +149,9 @@ public sealed class VirtualClock : IClock
|
||||
await failed.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (!TryFireNext(target))
|
||||
var running = Actors - actors.Count(a => a.IsCompleted);
|
||||
if (FireNextOrFinish(target, running) == Step.Finished)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (target > _now)
|
||||
{
|
||||
_now = target;
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -198,11 +188,22 @@ public sealed class VirtualClock : IClock
|
||||
}
|
||||
}
|
||||
|
||||
private bool TryFireNext(DateTimeOffset limit)
|
||||
/// <summary>
|
||||
/// One step of the driver, atomic with a fresh look at the waiting actors: fires the earliest live timer due by
|
||||
/// <paramref name="limit"/>; when there is none, moves time to <paramref name="limit"/> and says the run is finished.
|
||||
/// With <paramref name="running"/> actors expected to wait, fewer pending timers mean that an actor's timer was
|
||||
/// cancelled from another thread after the quiescence check: that actor runs again and nothing moves.
|
||||
/// </summary>
|
||||
private Step FireNextOrFinish(DateTimeOffset limit, int running)
|
||||
{
|
||||
PendingDelay? fired = null;
|
||||
lock (_gate)
|
||||
{
|
||||
if (running > 0 && _active < running)
|
||||
{
|
||||
return Step.NotQuiescent;
|
||||
}
|
||||
|
||||
while (_timers.TryPeek(out var next, out _))
|
||||
{
|
||||
if (next.Done)
|
||||
@@ -228,16 +229,21 @@ public sealed class VirtualClock : IClock
|
||||
FiredTimers++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (fired is null)
|
||||
{
|
||||
return false;
|
||||
if (fired is null)
|
||||
{
|
||||
if (limit > _now)
|
||||
{
|
||||
_now = limit;
|
||||
}
|
||||
|
||||
return Step.Finished;
|
||||
}
|
||||
}
|
||||
|
||||
fired.Registration.Dispose();
|
||||
fired.Completion.TrySetResult();
|
||||
return true;
|
||||
return Step.Fired;
|
||||
}
|
||||
|
||||
private void Cancel(PendingDelay delay, CancellationToken ct)
|
||||
@@ -259,6 +265,18 @@ public sealed class VirtualClock : IClock
|
||||
delay.Completion.TrySetCanceled(ct);
|
||||
}
|
||||
|
||||
private enum Step
|
||||
{
|
||||
/// <summary>A timer fired: an actor runs.</summary>
|
||||
Fired,
|
||||
|
||||
/// <summary>An actor runs again (its timer was cancelled from outside): wait until it waits.</summary>
|
||||
NotQuiescent,
|
||||
|
||||
/// <summary>Nothing left before the limit: time is at the limit.</summary>
|
||||
Finished,
|
||||
}
|
||||
|
||||
private sealed class PendingDelay
|
||||
{
|
||||
public DateTimeOffset Due { get; set; }
|
||||
|
||||
Reference in new issue
Block a user