Files
Febe/src/Febe.Core/Engine/EngineHost.cs
T
Alby96andClaude Opus 5.5 31bbbf8bb7
verifica / controlli (push) Successful in 2m10s
verifica / prove (push) Successful in 26m16s
verifica / installatore (push) Successful in 5m39s
verifica / immagine (push) Successful in 28m39s
Instagram: Febe legge le risposte vere (campioni dal HAR del 21/10)
Febe non estraeva nulla da Instagram per due motivi. Instagram manda i
dati di storie e raccolte (GraphQL) come text/javascript, e la cattura
leggeva solo le risposte dichiarate JSON: le scartava tutte. E i file di
Instagram (lettori, bersagli) erano scheletri, quindi le ricette si
rifiutavano di girare.

Alberto ha mandato un HAR del suo browser e una guida. La guida descrive
richieste costruite a mano, vietate dalle regole 2-4, e un formato che
nel HAR non compare: non si usa. Dal HAR si è letta solo la forma; le
risposte utili sono diventate campioni grezzi fuori dal repository,
ripuliti e verificati con febe-sonda (tests/Febe.Tests/campioni/instagram).

Che cosa cambia:
- la cattura legge le risposte text/javascript chieste dalla pagina (mai
  gli script) e ogni blocco JSON incorporato nel documento della pagina,
  e avvisa quando un corpo atteso non arriverà;
- le risposte che non parlano di contenuti (promozioni, «storia vista»)
  si ignorano invece di valere come formato non riconosciuto;
- lettori.instagram.json è confermato, con sole chiavi presenti nei
  campioni; identificativi delle raccolte nella forma dell'indirizzo;
- bersagli.instagram.json ha le pagine viste nel traffico vero; i
  bersagli restano vuoti (H11): storie, raccolte, Taggati e Reel
  aspettano lo script tools/bersagli/raccogli-bersagli.js;
- le ricette del profilo reggono dati in risposte diverse e prendono la
  paginazione solo dalla risposta che porta i loro post; l'elenco dei
  seguiti scarta i profili suggeriti; «Tu» si riconosce anche dal solo
  identificativo dell'account collegato;
- il visualizzatore delle raccolte conta i contenuti (l'indirizzo non
  cambia), chiede il permesso prima di ogni contenuto e si chiude sempre;
- una ricetta che la configurazione non lascia girare è «Da configurare»:
  non è un guasto, non si sospende, non si pianifica; le sospensioni
  dovute ai file vecchi si azzerano una volta al cambio dei file;
- la barra laterale dice «Collegato» dal cookie di sessione; i «Post
  singolo» per gli indirizzi scaduti non vengono più annullati;
- febe-sonda da-har; la ripulitura tiene latest_reel_media e mette un
  riempitivo neutro sotto le chiavi simili a segreti (gitleaks).

Prove su Windows: 783 superate, 76 saltate (Chromium e Xvfb, nella CI).
Nulla è stato provato contro Instagram. Dettagli e decisioni in
docs/stato.md e docs/decisioni.md (righe del 25 ottobre).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 14:22:16 +01:00

923 lines
36 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Pacing;
using Febe.Core.Storage;
namespace Febe.Core.Engine;
/// <summary>Outcome of «Controlla ora» (spec §7.8).</summary>
public enum CheckNowStatus
{
/// <summary>Put on top of the queue.</summary>
Queued,
/// <summary>Outside the active window: Alberto must confirm with <see cref="CheckNowResult.ConfirmationToken"/>.</summary>
NeedsConfirmation,
/// <summary>Not possible now (budget exhausted, engine stopped, account not contactable); the message says why.</summary>
Refused,
}
/// <summary>Answer to «Controlla ora»: an Italian message for the interface and, when needed, a confirmation token.</summary>
public sealed record CheckNowResult(CheckNowStatus Status, string Message, string? ConfirmationToken = null, DateTimeOffset? ExpectedAround = null);
/// <summary>Answer to «Riprendi».</summary>
public sealed record ResumeResult(bool Resumed, string Message);
/// <summary>
/// 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 <see cref="IClock"/> for time and <see cref="IRandomSource"/> for chance, so the
/// same code runs under the virtual clock of the simulation.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
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<string, (long AccountId, DateTimeOffset Expires)> _confirmations = new(StringComparer.Ordinal);
private readonly Dictionary<long, DateTimeOffset> _outsideWindowAllowed = [];
private CancellationTokenSource _wake = new();
private CancellationTokenSource? _sessionCts;
private CancellationTokenSource? _loopCts;
private Task? _loop;
private bool _initialized;
private bool _manualWaiting;
private int _restAfterDriving;
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;
/// <summary>What the interface shows of the engine (Attività, sidebar, account settings panel).</summary>
public IEngineMonitor Monitor { get; }
/// <summary>Recipes suspended after repeated unrecognized formats, with when.</summary>
public IReadOnlyDictionary<RecipeKind, DateTimeOffset> SuspendedRecipes => _health.Suspended;
internal IReadOnlyList<RecentAction> RecentActions(int limit) => _recent.Snapshot(limit);
/// <summary>Starts the background loop.</summary>
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;
}
/// <summary>Stops the loop; a session in progress ends as interrupted and the browser goes to rest.</summary>
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();
}
/// <summary>
/// The loop of the engine, until <paramref name="ct"/> is cancelled. <see cref="StartAsync"/> runs it in the
/// background; the simulation awaits it directly under the virtual clock.
/// </summary>
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);
}
}
/// <summary>«Metti in pausa»: stops the engine until «Riprendi»; a session in progress ends now.</summary>
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);
}
/// <summary>
/// «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.
/// </summary>
public async Task<ResumeResult> ResumeAsync(CancellationToken ct = default)
{
var messages = new List<string>();
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 non si accorcia: Febe riparte {ItalianText.Around(until, _s.Clock.Now, _s.Clock.LocalZone)}.");
}
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));
}
/// <summary>
/// «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 <see cref="CheckNowStatus.NeedsConfirmation"/> with a token; calling again with the token allows that
/// single check.
/// </summary>
public async Task<CheckNowResult> 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;
if (_composer.NotConfiguredReason(CheckPolicy.RecipeOf(kind)) is { } notConfigured)
{
return new CheckNowResult(CheckNowStatus.Refused, notConfigured + " Il controllo non parte.");
}
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);
}
/// <summary>«Leggi l'elenco dei seguiti» (spec §4.2): read at human pace inside the budgets, possibly over several sessions.</summary>
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);
}
/// <summary>Accounts were added, removed or changed: the queue is brought in step before the next session.</summary>
public async Task NotifyAccountsChangedAsync(CancellationToken ct = default)
{
await _composer.SyncQueueAsync(ct).ConfigureAwait(false);
Wake();
_s.Events.Publish(EngineNotificationKind.StateChanged);
}
/// <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();
}
Wake();
_s.Events.Publish(EngineNotificationKind.StateChanged);
}
/// <summary>Reactivates a recipe suspended after repeated unrecognized formats (after the reader was updated).</summary>
public async Task<bool> 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;
}
/// <summary>
/// The collection configuration in use: <paramref name="fingerprint"/> of the reader vocabulary and target map of the
/// site as loaded. When it differs from the stored one — or none is stored yet, the first start that knows it —
/// every suspension and consecutive failure of the recipes is cleared once, since they were counted against other
/// files, with one line in the timeline when there was something to clear; then the fingerprint is stored. Called at
/// start-up, before <see cref="StartAsync"/>. True when the configuration had changed.
/// </summary>
public async Task<bool> ApplyCollectionConfigurationAsync(string fingerprint, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(fingerprint);
var settings = _s.Storage.Settings;
if (string.Equals(await settings.GetAsync(EngineSettingKeys.CollectionConfiguration, ct).ConfigureAwait(false), fingerprint, StringComparison.Ordinal))
{
return false;
}
await _health.LoadAsync(ct).ConfigureAwait(false);
var (suspended, hadFailures) = await _health.ResetAllAsync(ct).ConfigureAwait(false);
if (suspended.Count > 0)
{
var names = string.Join(", ", suspended.Select(k => "«" + ItalianText.Capitalize(SessionComposer.RecipeName(k)) + "»"));
await _s.Events.WriteAsync(
EventSeverity.Info,
EngineEventCodes.CollectionConfigurationChanged,
$"La configurazione della raccolta è cambiata: le ricette sospese ripartono ({names}).",
ct: ct).ConfigureAwait(false);
}
else if (hadFailures)
{
await _s.Events.WriteAsync(
EventSeverity.Info,
EngineEventCodes.CollectionConfigurationChanged,
"La configurazione della raccolta è cambiata: i problemi delle ricette contati finora non valgono più.",
ct: ct).ConfigureAwait(false);
}
// Stored last: if Febe stops in between, the next start clears again, which changes nothing.
await settings.SetAsync(EngineSettingKeys.CollectionConfiguration, fingerprint, ct).ConfigureAwait(false);
Wake();
_s.Events.Publish(EngineNotificationKind.StateChanged);
return true;
}
/// <summary>Stores and applies new engine settings, then replans.</summary>
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);
}
/// <summary>One turn of the loop: runs a session when one is due, otherwise says how long to wait.</summary>
private async Task<TimeSpan?> StepAsync(CancellationToken ct)
{
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;
}
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)
{
// This rest also serves a driving period that ended during the session.
Interlocked.Exchange(ref _restAfterDriving, 0);
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<Task> { 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);
}
/// <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;
private DateTimeOffset? PauseFloor() =>
_s.Runtime.LastSessionEnd is { } end ? end + _s.Runtime.Profile.PauseMin : null;
private async Task<EngineTask?> FindConfirmedManualAsync(DateTimeOffset now, CancellationToken ct)
{
Dictionary<long, DateTimeOffset> allowed;
lock (_gate)
{
PruneLocked(now);
if (_outsideWindowAllowed.Count == 0)
{
return null;
}
allowed = new Dictionary<long, DateTimeOffset>(_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)
{
}
}
/// <summary>Wakes the loop if it is waiting; the wait it was in is cancelled synchronously.</summary>
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;
}