Integrazione 0.1.1: unione di correzione/storico-completato-una-volta

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

# Conflicts:
#	docs/decisioni.md
This commit is contained in:
Alby96 committed 2026-10-20 18:05:33 +02:00
commit 00c3d8bdf4
5 files changed
+356 -27

No files matched your search

+3
View File
@@ -259,3 +259,6 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
| 2026-10-20 | Prova della cartella dei dati su una condivisione: su Linux il montaggio cifs iniettato come prima, su Windows un percorso UNC verso `febe-prova.invalid`, riconosciuto dalla sola forma; il controllo «niente scritto nella cartella dei dati» resta solo su Linux | Stesso comportamento sui due sistemi, ognuno con il suo modo di riconoscere la rete (su Windows non c'è tabella dei montaggi); guardare dentro un UNC vorrebbe dire interrogare la rete, e un nome `.invalid` (RFC 6761) non risponde mai |
| 2026-10-20 | `TestLibrary.LoseDatabaseAsync`: su Windows un'eliminazione che trova il file in uso da un altro programma (`0x80070020`) si ripete ogni 50 ms, per al più 5 s | Su Windows un file aperto da un altro programma non si elimina. Su questo PC, con Defender attivo, succedeva circa 3 volte su 40 esecuzioni di `Febe.Tests.Library`: il file era libero dopo 6–17 ms e il Restart Manager non vedeva nessun processo che lo tenesse, quindi non è un collegamento di Febe rimasto aperto. Su Linux eliminare un file aperto riesce sempre e non si ripete nulla |
| 2026-10-20 | Prova di `costruisci.sh`: su Windows prima Git Bash (accanto a git sul PATH, poi nelle cartelle del suo installatore), altrimenti un bash sul PATH che non sia il lanciatore di WSL (`System32\bash.exe`, alias in `WindowsApps`); senza bash la prova è inconcludente invece di passare in silenzio | Dal PATH di PowerShell il primo bash è il lanciatore di WSL, che senza distribuzione fallisce («execvpe(/bin/bash) failed») e non vede lo script col percorso di Windows; su Linux si usa come prima il primo bash sul PATH |
| 2026-10-20 | «Storico completato» lo scrive solo il motore (`SessionComposer.FinishBackfillAsync`: @nome, post in libreria, che cosa succede ora); la ricetta Storico non scrive più una riga sua. Il motore chiude lo storico ogni volta che il cammino è arrivato in fondo (`BackfillFinished`), anche se poi la corsa finisce con un segnale o un'interruzione | Due righe nella cronologia e in «Avvisi» per lo stesso storico (@marta.prova, 14:31): la corta della ricetta e quella del motore. La notifica era già una sola e col testo del motore, perché la riga della ricetta (`CollectionWriter.EventAsync`) non passa da `EngineEvents` e `AlertService` non la vede. Con un segnale subito dopo l'ultima pagina l'account restava «Storico in corso» per sempre |
| 2026-10-20 | Anche lo storico completato dal controllo del profilo (profilo tutto nella prima pagina) lo chiude il motore, con la sua riga (`BackfillFinished` del controllo, solo per un account «Storico in corso»). A inizio sessione il motore chiude gli account rimasti «Storico in corso» con lo storico già completato; la fase dello Storico rilegge gli account invece di usare quelli di inizio sessione | Con due account «Storico in corso» quello piccolo restava così per sempre, senza riga né avviso: dalla sessione dopo non era più candidato dello Storico. Rileggere gli account evita una seconda riga quando lo Storico della stessa sessione sceglierebbe proprio quello appena chiuso |
| 2026-10-20 | Quando chiude uno storico, il motore toglie subito dalla coda il suo «Storico» e, se l'account resta in pausa, gli altri compiti pianificati; non rimette in coda la corsa dello Storico arrivata in fondo e poi fermata da un segnale | La Coda mostrava fino alla sessione dopo (dopo una verifica, fino a «Riprendi») uno Storico da fare per un account già «Aggiornato» o «In pausa». I comandi di Alberto restano |
@@ -184,7 +184,11 @@ public sealed partial class RecipeRunner
}
else if (page?.HasMore == false)
{
// The whole profile is on the first page, saved just now. For an account «Storico in corso» its history
// is complete: the engine closes it, with its line (RecipeOutcome.BackfillFinished). An account that
// keeps only the new posts had no history to announce.
await Env.Storage.Accounts.SetBackfillAsync(account.Id, null, Env.Clock.Now, run.Ct).ConfigureAwait(false);
run.Finished = account.State == AccountState.Backfilling;
}
}
else if (CollectionWriter.Wants(account, EntryKind.Post) && (account.BackfillCursor is not null || account.BackfillCompletedAt is not null))
@@ -394,9 +398,10 @@ public sealed partial class RecipeRunner
run.Finished = true;
if (walk.IsGrid)
{
// «Storico completato» in Attività, and the new state of the account, are the engine's: one line per
// history, with its numbers (SessionComposer, from RecipeOutcome.BackfillFinished).
await Env.Storage.Accounts.SetBackfillAsync(account.Id, null, Env.Clock.Now, run.Ct).ConfigureAwait(false);
await settings.SetAsync(walk.MarkKey(account.Id), null, run.Ct).ConfigureAwait(false);
await Writer.EventAsync("storico-completato", $"Storico di {account.Username} completato.", EventSeverity.Success, account.Id, run.Session.SessionId, run.Ct).ConfigureAwait(false);
}
else
{
+4 -1
View File
@@ -89,7 +89,10 @@ public sealed record RecipeOutcome(
/// <summary>Accounts where the sweep saw new posts (FollowingSweep).</summary>
public IReadOnlyList<long> AccountsWithNewPosts { get; init; } = [];
/// <summary>For Backfill: true when the beginning of the profile has been reached.</summary>
/// <summary>
/// Backfill: true when the beginning of the profile has been reached. ProfileCheck: true when the check found the
/// whole profile of an account «Storico in corso» on its first page (its history is complete as well).
/// </summary>
public bool BackfillFinished { get; init; }
}
+89 -25
View File
@@ -51,6 +51,7 @@ internal sealed class SessionComposer
public async Task<SessionSummary> RunAsync(SessionContext context, EngineTask? outsideWindowTask, CancellationToken ct)
{
var state = new SessionState(context);
await CloseCompletedHistoriesAsync(state, ct).ConfigureAwait(false);
var accounts = await SyncQueueAsync(ct).ConfigureAwait(false);
if (outsideWindowTask is not null)
@@ -145,12 +146,41 @@ internal sealed class SessionComposer
// 5. A few pages of history on one account.
if (!light && !Over(state, ct))
{
await RunBackfillAsync(accounts, state, ct).ConfigureAwait(false);
await RunBackfillAsync(state, ct).ConfigureAwait(false);
}
return state.Summary();
}
/// <summary>
/// Accounts still «Storico in corso» whose history is complete: a run closed it but its outcome was never recorded
/// (Febe stopped in between), or an earlier version left them so. Closed before the session plans anything, with
/// their line (<see cref="FinishBackfillAsync"/>); nothing towards the site.
/// </summary>
private async Task CloseCompletedHistoriesAsync(SessionState state, CancellationToken ct)
{
var complete = (await Store.Accounts.ListAsync(ct).ConfigureAwait(false))
.Where(a => a.State == AccountState.Backfilling && a.BackfillCompletedAt is not null)
.ToList();
if (complete.Count == 0)
{
return;
}
await _queueGate.WaitAsync(ct).ConfigureAwait(false);
try
{
foreach (var account in complete)
{
await FinishBackfillAsync(account, state, Clock.Now, CancellationToken.None).ConfigureAwait(false);
}
}
finally
{
_queueGate.Release();
}
}
/// <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 look at each highlight collection on its profile, a backfill task for every account
@@ -568,14 +598,16 @@ internal sealed class SessionComposer
/// History advances on one account per session, alternating among the accounts «Storico in corso», each up to its
/// daily maximum; suspended while the account has too many files waiting or the data budget is reached (§6.3).
/// </summary>
private async Task RunBackfillAsync(Dictionary<long, Account> accounts, SessionState state, CancellationToken ct)
private async Task RunBackfillAsync(SessionState state, CancellationToken ct)
{
if (_health.IsSuspended(RecipeKind.Backfill) || state.Exhausted.Contains(ActionKind.BackfillPage))
{
return;
}
var candidates = accounts.Values
// Read again, not taken from the start of the session: a profile check of this session may have completed a
// history already (its line is written), and that account is not walked again.
var candidates = (await Store.Accounts.ListAsync(ct).ConfigureAwait(false))
.Where(a => a.State == AccountState.Backfilling && a.BackfillCompletedAt is null && CheckPolicy.IsContactable(a))
.ToList();
if (candidates.Count == 0)
@@ -771,6 +803,15 @@ internal sealed class SessionComposer
var now = Clock.Now;
var kind = request.Kind;
var writes = new List<Task>();
// The history reached the beginning of the profile: the walk of the Storico, however the run ended (a signal or
// a cancellation can come right after the last page was stored, and that account would not be walked again),
// or a profile check that found the whole profile on its first page. What follows sees the account as it is now.
if (kind is RecipeKind.Backfill or RecipeKind.ProfileCheck && outcome.BackfillFinished && account is not null)
{
account = await FinishBackfillAsync(account, state, now, ct).ConfigureAwait(false);
}
switch (outcome.Status)
{
case RecipeStatus.Completed:
@@ -798,7 +839,12 @@ internal sealed class SessionComposer
case RecipeStatus.StoppedBySignal:
case RecipeStatus.Cancelled:
if (task is not null)
if (task is not null && kind == RecipeKind.Backfill && outcome.BackfillFinished)
{
// The walk got to the end before the run stopped: nothing to take up again (closed above).
writes.Add(Store.Tasks.CompleteAsync(task.Id, now, ct));
}
else if (task is not null)
{
await RequeueAsync(task, outcome.Status == RecipeStatus.Cancelled ? "Interrotta" : "Fermata da un segnale", now).ConfigureAwait(false);
}
@@ -947,27 +993,8 @@ internal sealed class SessionComposer
break;
}
case RecipeKind.Backfill when outcome.BackfillFinished:
{
var fresh = await Store.Accounts.GetAsync(account.Id, ct).ConfigureAwait(false) ?? account;
await Store.Accounts.SetBackfillAsync(account.Id, fresh.BackfillCursor, now, ct).ConfigureAwait(false);
var newState = fresh.KeepUpdated ? AccountState.UpToDate : AccountState.Paused;
await Store.Accounts.SetStateAsync(account.Id, newState, now, null, ct).ConfigureAwait(false);
var total = await Store.Entries.CountDiscoveredAsync(account.Id, EntryKind.Post, DateTimeOffset.UnixEpoch, now.AddSeconds(1), ct).ConfigureAwait(false);
var tail = fresh.KeepUpdated
? " Da ora lo tengo aggiornato."
: " «Tieni aggiornato» è spento: l'account resta in pausa.";
await _s.Events.WriteAsync(
EventSeverity.Success,
EngineEventCodes.BackfillCompleted,
$"Storico di {ItalianText.Handle(account.Username)} completato: {ItalianText.Count(total, "post", "post")} in libreria.{tail}",
account.Id,
state.Context.SessionId,
ct).ConfigureAwait(false);
break;
}
case RecipeKind.Backfill:
// A history completed: FinishBackfillAsync, from ApplyOutcomeAsync.
case RecipeKind.Backfill when !outcome.BackfillFinished:
if (contactable)
{
// Behind the other accounts «Storico in corso»: they alternate.
@@ -980,6 +1007,43 @@ internal sealed class SessionComposer
}
}
/// <summary>
/// The history of the account is complete: «Aggiornato» (or «In pausa» with «Tieni aggiornato» off) and the one
/// «storico completato» line of Attività, which is also the alert (spec §13.3). The recipes write no line of their
/// own for it. Called once per history: after it the account is no longer «Storico in corso». Returns the account
/// as it is now.
/// </summary>
private async Task<Account> FinishBackfillAsync(Account account, SessionState state, DateTimeOffset now, CancellationToken ct)
{
var fresh = await Store.Accounts.GetAsync(account.Id, ct).ConfigureAwait(false) ?? account;
await Store.Accounts.SetBackfillAsync(account.Id, fresh.BackfillCursor, now, ct).ConfigureAwait(false);
var newState = fresh.KeepUpdated ? AccountState.UpToDate : AccountState.Paused;
await Store.Accounts.SetStateAsync(account.Id, newState, now, null, ct).ConfigureAwait(false);
// The Coda follows at once, not at the next session: no «Storico» left for the account, and nothing planned
// for an account that stays paused. Commands of Alberto stay; the task in flight is settled by its outcome.
foreach (var task in await Store.Tasks.ListPendingAsync(10_000, ct).ConfigureAwait(false))
{
if (task.AccountId == account.Id && !task.IsManual && (newState == AccountState.Paused || task.Kind == EngineTaskKind.Backfill))
{
await Store.Tasks.CancelAsync(task.Id, now, ct).ConfigureAwait(false);
}
}
var total =await Store.Entries.CountDiscoveredAsync(account.Id, EntryKind.Post, DateTimeOffset.UnixEpoch, now.AddSeconds(1), ct).ConfigureAwait(false);
var tail = fresh.KeepUpdated
? " Da ora lo tengo aggiornato."
: " «Tieni aggiornato» è spento: l'account resta in pausa.";
await _s.Events.WriteAsync(
EventSeverity.Success,
EngineEventCodes.BackfillCompleted,
$"Storico di {ItalianText.Handle(account.Username)} completato: {ItalianText.Count(total, "post", "post")} in libreria.{tail}",
account.Id,
state.Context.SessionId,
ct).ConfigureAwait(false);
return await Store.Accounts.GetAsync(account.Id, ct).ConfigureAwait(false) ?? fresh;
}
private async Task PauseAfterSingleDownloadAsync(Account account, DateTimeOffset now, SessionState state, CancellationToken ct)
{
await Store.Accounts.SetStateAsync(account.Id, AccountState.Paused, now, null, ct).ConfigureAwait(false);
@@ -0,0 +1,254 @@
using Febe.Core.Abstractions;
using Febe.Core.Alerts;
using Febe.Core.Collection;
using Febe.Core.Collection.Readers;
using Febe.Core.Collection.Recipes;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Storage;
using Febe.Tests.Alerts.Support;
using Febe.Tests.Collection.Support;
using Febe.Tests.Engine.Support;
using Febe.Web.Api;
namespace Febe.Tests.Engine;
/// <summary>
/// «Storico completato» is one line of Attività and one alert per history, written by the engine with its numbers:
/// the real recipes on the scripted site (no browser) under the real engine, and the runs that end otherwise right
/// after the last page.
/// </summary>
[TestClass]
public sealed class BackfillCompletedTests
{
private static readonly DateTimeOffset Morning = EngineTestBed.Local(2026, 10, 14, 6, 0);
/// <summary>Found testing Febe for Windows on the test site: two lines in «Avvisi» for one history, at 14:31.</summary>
[TestMethod]
public async Task AHistoryCompletedByTheRecipesIsOneLineOfAvvisiWithItsNumbersAndOneNotification()
{
await using var bed = await AlertBed.CreateAsync(start: Morning);
var engine = bed.Engine;
var (runner, site) = RealRecipes(engine);
var marta = site.Add(new ScriptedAccount("2002", "marta.prova") { Followed = false });
marta.Posts.AddRange(ScriptedBed.Posts(0, 18, Morning.AddDays(-30)));
var account = await AddBackfillingAsync(engine, marta, postCount: 18);
engine.Start(runner);
await engine.RunUntilAsync(Morning.AddDays(2));
await engine.StopAsync();
await bed.Alerts.FlushAsync();
const string Expected = "Storico di @marta.prova completato: 18 post in libreria. Da ora lo tengo aggiornato.";
var done = await engine.Db.Accounts.GetAsync(account.Id);
Assert.IsNotNull(done!.BackfillCompletedAt, "The history reached the beginning of the profile.");
Assert.AreEqual(AccountState.UpToDate, done.State);
Assert.HasCount(18, await engine.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Post, Limit = 100 }));
var lines = await engine.Db.Events.ListAsync(new EventQuery { Codes = [EngineEventCodes.BackfillCompleted] });
Assert.HasCount(1, lines, "One line for one history: " + string.Join(" | ", lines.Select(e => e.Message)));
Assert.AreEqual(Expected, lines[0].Message);
Assert.AreEqual(EventSeverity.Success, lines[0].Severity);
Assert.AreEqual(account.Id, lines[0].AccountId);
Assert.IsNotNull(lines[0].SessionId);
// The «Avvisi» list of Attività.
var alerts = (await ActivityApi.AlertsAsync(engine.Db, engine.Clock, CancellationToken.None)).Items.Where(i => i.Kind == "backfillDone").ToList();
Assert.HasCount(1, alerts);
Assert.AreEqual(Expected, alerts[0].Message);
// One Windows notification and one Telegram message, with the same full text.
var notification = bed.Shell.Notifications.Single(n => n.Title == AlertCatalog.Title(AlertKind.BackfillDone));
Assert.AreEqual(Expected, notification.Message);
var telegram = bed.Telegram.Requests.Where(r => r.Text.StartsWith("Febe · Storico completato\n", StringComparison.Ordinal)).ToList();
Assert.HasCount(1, telegram);
Assert.AreEqual("Febe · Storico completato\n" + Expected, telegram[0].Text);
Assert.HasCount(1, bed.Outcomes.Where(o => o.Alert.Kind == AlertKind.BackfillDone), "Nothing held back as a repeat either.");
}
/// <summary>
/// A run that completes the history: the walk reached the beginning of the profile and stored it, then a signal or
/// a cancellation changed how the run ended; or a profile check found the whole profile on its first page. The
/// history is closed with its line (it would never be walked again), and right after that run the Coda shows
/// nothing planned for the account, now paused: no «Storico» put back in the queue (review F3).
/// </summary>
[TestMethod]
[DataRow(RecipeKind.Backfill, RecipeStatus.StoppedBySignal)]
[DataRow(RecipeKind.Backfill, RecipeStatus.Cancelled)]
[DataRow(RecipeKind.ProfileCheck, RecipeStatus.Completed)]
public async Task AHistoryCompletedByARunIsClosedWithItsLineAndLeavesNothingInTheQueue(RecipeKind kind, RecipeStatus status)
{
await using var bed = await AlertBed.CreateAsync(start: Morning);
var engine = bed.Engine;
var account = await engine.AddAccountAsync("luca.prova", followed: true, state: AccountState.Backfilling, postCount: 30);
await engine.Db.Accounts.UpdateAsync((await engine.Db.Accounts.GetAsync(account.Id))! with { KeepUpdated = false });
var runner = new ScriptedRunner(engine.Governor, engine.Clock);
RecipeRequest? closing = null;
var walksAfter = 0;
runner.Before = async r =>
{
if (r.AccountId != account.Id)
{
return;
}
if (closing is not null)
{
walksAfter += r.Kind == RecipeKind.Backfill ? 1 : 0;
}
else if (r.Kind == kind)
{
// What the recipe stores: the walk met the end of the list, or the whole profile is on its first page.
await engine.Db.Accounts.SetBackfillAsync(account.Id, null, engine.Clock.Now);
closing = r;
}
};
runner.Script = r => ReferenceEquals(r, closing) ? new RecipeOutcome(status, 1, 6) { BackfillFinished = true } : null;
engine.Start(runner);
var end = Morning.AddDays(2);
while (closing is null && engine.Clock.Now < end)
{
await engine.RunForAsync(TimeSpan.FromMinutes(1));
}
// Right after that run, before the next session tidies the queue.
Assert.IsNotNull(closing);
var queued = (await engine.Db.Tasks.ListPendingAsync(1000)).Where(t => t.AccountId == account.Id).ToList();
Assert.HasCount(0, queued, "Planned for a paused account: " + string.Join(", ", queued.Select(t => $"{t.Kind} «{t.LastError}»")));
await engine.RunUntilAsync(end);
await engine.StopAsync();
await bed.Alerts.FlushAsync();
Assert.AreEqual(0, walksAfter, "Never walked again.");
var finished = await engine.Db.Accounts.GetAsync(account.Id);
Assert.AreEqual(AccountState.Paused, finished!.State, "«Tieni aggiornato» off: one download, then paused.");
var lines = await engine.Db.Events.ListAsync(new EventQuery { Codes = [EngineEventCodes.BackfillCompleted] });
Assert.HasCount(1, lines);
Assert.AreEqual("Storico di @luca.prova completato: 0 post in libreria. «Tieni aggiornato» è spento: l'account resta in pausa.", lines[0].Message);
Assert.HasCount(1, bed.Shell.Notifications.Where(n => n.Title == AlertCatalog.Title(AlertKind.BackfillDone)));
}
/// <summary>
/// A profile that fits on its first page: the profile check completes its history. When the walk of the session
/// went to another account «Storico in corso», the small one stayed so for ever, with no line and no alert (review
/// F1). Added first, the small one is the walk's next pick in that very session: it must not get a second line.
/// An account that keeps only the new posts has no history to announce.
/// </summary>
[TestMethod]
[DataRow(false)]
[DataRow(true)]
public async Task AHistoryCompletedByTheProfileCheckIsClosedAtOnceWithOneLine(bool smallFirst)
{
await using var bed = await AlertBed.CreateAsync(start: Morning);
var engine = bed.Engine;
var (runner, site) = RealRecipes(engine);
var big = site.Add(new ScriptedAccount("3003", "grande.prova") { Followed = false });
big.Posts.AddRange(ScriptedBed.Posts(0, 400, Morning.AddDays(-30), prefix: "g"));
var small = site.Add(new ScriptedAccount("4004", "piccolo.prova") { Followed = false });
small.Posts.AddRange(ScriptedBed.Posts(0, 5, Morning.AddDays(-30), prefix: "s"));
var news = site.Add(new ScriptedAccount("5005", "nuovi.prova") { Followed = false });
news.Posts.AddRange(ScriptedBed.Posts(0, 3, Morning.AddDays(-30), prefix: "n"));
// Among the accounts «Storico in corso» the walk takes the lowest id first.
Account smallAccount;
if (smallFirst)
{
smallAccount = await AddBackfillingAsync(engine, small, postCount: 5);
await AddBackfillingAsync(engine, big, postCount: 400);
}
else
{
await AddBackfillingAsync(engine, big, postCount: 400);
smallAccount = await AddBackfillingAsync(engine, small, postCount: 5);
}
var newsAccount = await engine.Db.Accounts.AddAsync(Account.Create(news.Username, StartingPoint.OnlyNewFromToday, engine.Clock.Now, EngineTestBed.Zone, engine.Runtime.Profile) with
{
InstagramId = news.Id,
IsFollowed = news.Followed,
ContentTypes = ContentTypes.PostPhotos | ContentTypes.PostVideos,
PostCount = 3,
});
Assert.AreEqual(AccountState.UpToDate, newsAccount.State);
engine.Start(runner);
await engine.RunUntilAsync(Morning.AddDays(4));
await engine.StopAsync();
await bed.Alerts.FlushAsync();
var lines = await engine.Db.Events.ListAsync(new EventQuery { Codes = [EngineEventCodes.BackfillCompleted] });
var all = string.Join(" | ", lines.Select(e => e.Message));
var done = await engine.Db.Accounts.GetAsync(smallAccount.Id);
Assert.IsNotNull(done!.BackfillCompletedAt, "The whole profile is on its first page.");
Assert.AreEqual(AccountState.UpToDate, done.State, all);
const string Expected = "Storico di @piccolo.prova completato: 5 post in libreria. Da ora lo tengo aggiornato.";
Assert.HasCount(1, lines.Where(e => e.AccountId == smallAccount.Id).ToList(), all);
Assert.AreEqual(Expected, lines.Single(e => e.AccountId == smallAccount.Id).Message);
Assert.AreEqual(1, bed.Shell.Notifications.Count(n => n.Message == Expected));
Assert.IsFalse(lines.Any(e => e.AccountId == newsAccount.Id), "«Solo i nuovi»: no history. " + all);
Assert.AreEqual(AccountState.UpToDate, (await engine.Db.Accounts.GetAsync(newsAccount.Id))!.State);
Assert.IsTrue(lines.GroupBy(e => e.AccountId).All(g => g.Count() == 1), "One line per history: " + all);
}
/// <summary>
/// An account «Storico in corso» whose history is already complete (a profile check closed it and Febe stopped
/// before recording the outcome, or a version that left it so): closed when the next session starts, with its
/// line, without walking anything.
/// </summary>
[TestMethod]
public async Task AnAccountLeftStoricoInCorsoWithItsHistoryCompleteIsClosedWhenASessionStarts()
{
await using var bed = await AlertBed.CreateAsync(start: Morning);
var engine = bed.Engine;
var account = await engine.AddAccountAsync("anna.prova", followed: true, state: AccountState.Backfilling, postCount: 7);
await engine.Db.Accounts.SetBackfillAsync(account.Id, null, engine.Clock.Now);
var runner = new ScriptedRunner(engine.Governor, engine.Clock);
engine.Start(runner);
await engine.RunUntilAsync(Morning.AddDays(1));
await engine.StopAsync();
await bed.Alerts.FlushAsync();
Assert.AreEqual(AccountState.UpToDate, (await engine.Db.Accounts.GetAsync(account.Id))!.State);
var lines = await engine.Db.Events.ListAsync(new EventQuery { Codes = [EngineEventCodes.BackfillCompleted] });
Assert.HasCount(1, lines);
Assert.AreEqual("Storico di @anna.prova completato: 0 post in libreria. Da ora lo tengo aggiornato.", lines[0].Message);
Assert.IsNotNull(lines[0].SessionId);
Assert.IsFalse(runner.Runs.Any(r => r.Request.Kind == RecipeKind.Backfill), "Nothing left to walk.");
Assert.HasCount(1, bed.Shell.Notifications.Where(n => n.Title == AlertCatalog.Title(AlertKind.BackfillDone)));
}
/// <summary>The real recipes over the scripted site, on the engine's database, clock, Governor and breaker.</summary>
private static (RecipeRunner Runner, ScriptedSite Site) RealRecipes(EngineTestBed engine)
{
var capture = new CaptureCollector(new ShapeReader(ReaderVocabulary.LoadTestSite()), engine.Clock);
var site = new ScriptedSite(capture, engine.Clock);
var runner = new RecipeRunner(new RecipeEnvironment
{
Driver = site,
Capture = capture,
Governor = engine.Governor,
Budget = engine.Governor,
DataBudget = engine.Governor,
Signals = new SignalDetector(SignalRules.LoadTestSite(), engine.Breaker, engine.Clock),
Storage = engine.Db,
SiteMap = SiteMap.LoadTestSite(),
Clock = engine.Clock,
Random = new SeededRandom(7),
Breaker = engine.Breaker,
});
return (runner, site);
}
/// <summary>An account «Storico in corso» for a scripted account: posts only, so that a visit is the profile check.</summary>
private static Task<Account> AddBackfillingAsync(EngineTestBed engine, ScriptedAccount scripted, int postCount) =>
engine.Db.Accounts.AddAsync(Account.Create(scripted.Username, StartingPoint.EverythingAndKeepUpdated, engine.Clock.Now, EngineTestBed.Zone, engine.Runtime.Profile) with
{
InstagramId = scripted.Id,
IsFollowed = scripted.Followed,
State = AccountState.Backfilling,
ContentTypes = ContentTypes.PostPhotos | ContentTypes.PostVideos,
PostCount = postCount,
});
}