diff --git a/docs/decisioni.md b/docs/decisioni.md index 2a51cda..69155f9 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -662,3 +662,4 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-11-29 | **Subito dopo «Scollega», con l'indirizzo della pagina sconosciuto** (il browser non risponde ancora, `FullUrlAsync` dà `null`), Febe aspetta che il browser risponda, entro un limite; se ancora non risponde apre la pagina di accesso (#67). Fatto così: `BrowserConnectionService` chiede l'indirizzo ogni 200 ms (`AddressPoll`, con `IClock`) per al più 10 s (`AddressWait`), poi apre la pagina di accesso o d'inizio; se anche la navigazione non riesce, la finestra resta su e il registro dice «Alberto usa il browser: … non aperta (il browser non risponde).» | Decisione di Alberto del 29 novembre 2026: senza sapere quale pagina mostra il browser non si può dire se è già quella di accesso; aspettare un poco evita di ricaricare una pagina che sta arrivando, e il limite evita di restare fermi | | 2026-11-29 | **Il motore non rimette a riposo la pagina che Alberto ha appena ripreso**: a fine sessione e dopo la guida di Alberto il riposo (`about:blank`) si dà solo se, ottenuto il turno, Alberto non guida il browser e l'interruttore non è su Verifica o Scollegato (`KeepsPageAfterWaitingForTurn`); `IsRunning` si accende in `StartAsync` prima di avviare il lavoro | Le prove del desktop su #67 cadevano a volte: fra il controllo e il turno Alberto poteva riprendere il browser, e il motore gli toglieva la pagina. Resta una finestra stretta fra il turno e la navigazione, scritta in `docs/stato.md` | | 2026-12-01 | **Prove ferme nella CI (502 e 532): `--blame-hang-timeout 20m --blame-hang-dump-type none` su ogni `dotnet test` e lo stato della macchina durante le prove** (`.gitea/scripts/macchina.sh`: ogni 15 s ora, carico, memoria, scambio e pressione PSI in `macchina.log`, nel pacchetto `febe-ci` con i `.trx`). Nessun limite ai Chromium paralleli | Nelle due pause si sono fermate insieme tutte le prove in corso, anche le H.265, che non usano browser (aperti solo 5 e 3 Chromium), e tutto è ripartito insieme: un limite a 4 Chromium non le avrebbe evitate e allunga le prove (da 242 a 332 s in una misura sola, nell'immagine della CI in locale). Il quadro fa pensare alla macchina del runner (memoria, disco o sospensione), ma non è verificato: un buco negli orari di `macchina.log` dirà una sospensione, le righe senza buchi che cosa mancava. Venti minuti senza una prova che comincia o finisce chiudono l'esecuzione con i nomi delle prove in corso; niente dump, che può pesare gigabyte nel pacchetto | +| 2026-12-01 | **Prove da capo a fondo: il tempo scorre cinque volte più in fretta con un orologio che non somma le attese** (`ScaledClock`, uno solo per `ServerTestBed` e `DesktopBed`: `Now` dipende solo dal tempo vero) **e l'unica sessione è quella chiesta con «Controlla ora»** (la prima di suo è oltre la durata della prova). `CompressedClock` resta per le prove di raccolta, con un flusso per volta. Quando un'attesa scade, la prova dice che cosa faceva Febe (motore, interruttore, sessioni, coda, azioni, eventi, stato dei file, coda del registro; mai corpi, cookie o indirizzi dei file). Sostituisce per queste prove la riga del 13 ottobre (10×) | `TheRealServerCollectsFromTheTestSite…` cadeva a volte dopo 90 s senza dire perché. `CompressedClock` sommava le attese dei lavori di sottofondo (misurato: circa 34× invece di 10×, a salti di decine di secondi): i 30 s di una pagina vera e i pochi minuti della prima sessione finivano subito, e il controllo di marta.prova falliva (riprovato un'ora dopo) o i suoi file restavano in coda. Dopo la sessione i file aspettano la prossima, almeno 20 minuti (120 s veri): allungare il limite non bastava. La causa è l'orologio: con quello nuovo, anche lasciando al motore la sua sessione a «Ho finito» (un altro account per primo in 35 giri su 40), 40 giri su 40 sono passati; la sola sessione chiesta rende certo l'ordine. Senza più la sessione del motore, «Controlla ora» si chiede di nuovo prima di aspettare la verifica: altrimenti, a sessione finita, la pausa è fra 20 e 90 minuti | diff --git a/docs/guida/Sviluppo.md b/docs/guida/Sviluppo.md index de821e8..dd3a70b 100644 --- a/docs/guida/Sviluppo.md +++ b/docs/guida/Sviluppo.md @@ -52,7 +52,8 @@ dotnet test tests/Febe.Tests --filter "FullyQualifiedName~Febe.Tests.Alerts" - Le prove con un browser vero cercano Chromium in `FEBE_CHROMIUM` (o nel `PATH`) e Xvfb nel `PATH`; se mancano risultano inconcludenti, non fallite. Lo stesso per le prove d'insieme del server (`Febe.Tests.Server`), che avviano la composizione vera contro il sito di prova. -- Il motore si prova con un orologio virtuale e un seme fisso; le prove d'insieme con un orologio compresso (10×). +- Il motore si prova con un orologio virtuale e un seme fisso; le prove d'insieme con un orologio più veloce (10× le + ricette, 5× le composizioni intere). - La prova `Febe.Tests.Docs` controlla che questa guida dica tutto ciò che la specifica chiede (§15) e che ogni collegamento fra le pagine porti a una pagina che esiste. diff --git a/docs/stato.md b/docs/stato.md index fa5ef11..465ef0e 100644 --- a/docs/stato.md +++ b/docs/stato.md @@ -58,6 +58,9 @@ fra le sessioni; ciò che è da fare si legge nelle issue aperte. 28/11 11:38–12:20 e del 29/11 12:55–13:23 UTC. La 510 è stata verde alla seconda prova: al primo giro la prova da capo a fondo con il sito di prova (`TheRealServerCollectsFromTheTestSite…`) ha passato i 90 s, come già una volta prima di E3 (2 min 10 s nella 107). + Riaccaduto il 1º dicembre (551): era la prova, non Febe. Corretta con un orologio che non somma le attese e con la + sola sessione di «Controlla ora» (`decisioni.md`, 1º dicembre; ramo `correzione/prova-da-capo-a-fondo`); un'attesa + scaduta ora dice che cosa faceva Febe. La causa della 551 e della 510 resta dedotta: non c'è il loro registro. Dopo l'unione la 518 di main è caduta nell'immagine su `APreviewPastItsBudgetSaysToUseTheFolderOfTheCopies`: con un tempo zero il fotogramma si annullava con un timer, che su una macchina carica scattava dopo la decodifica; ora un tempo zero annulla subito, come già in `VideoFrameDecoder` (ramo `correzione/fotogramma-senza-tempo`). diff --git a/tests/Febe.Tests.Windows/Febe.Tests.Windows.csproj b/tests/Febe.Tests.Windows/Febe.Tests.Windows.csproj index c29d1cb..809bed6 100644 --- a/tests/Febe.Tests.Windows/Febe.Tests.Windows.csproj +++ b/tests/Febe.Tests.Windows/Febe.Tests.Windows.csproj @@ -15,6 +15,10 @@ + + + + diff --git a/tests/Febe.Tests.Windows/Support/CompositionSupport.cs b/tests/Febe.Tests.Windows/Support/CompositionSupport.cs index 54f2c73..f6a36b9 100644 --- a/tests/Febe.Tests.Windows/Support/CompositionSupport.cs +++ b/tests/Febe.Tests.Windows/Support/CompositionSupport.cs @@ -1,57 +1,7 @@ -using Febe.Core.Abstractions; using Febe.Desktop.Core; namespace Febe.Tests.Windows.Support; -/// -/// A clock that compresses time, like the one of the Linux suite: waits for real only a fraction -/// of the requested time and moves on by the whole of it, so the engine keeps its order of events -/// while a session lasts minutes instead of hours. -/// -internal sealed class CompressedClock(double factor, TimeZoneInfo zone) : IClock -{ - private readonly Lock _gate = new(); - private TimeSpan _offset; - - public TimeZoneInfo LocalZone { get; } = zone; - - public DateTimeOffset Now - { - get - { - lock (_gate) - { - return DateTimeOffset.UtcNow + _offset; - } - } - } - - public async Task Delay(TimeSpan time, CancellationToken ct) - { - if (time <= TimeSpan.Zero) - { - ct.ThrowIfCancellationRequested(); - return; - } - - var real = TimeSpan.FromTicks((long)(time.Ticks / factor)); - if (real >= TimeSpan.FromMilliseconds(1)) - { - await Task.Delay(real, ct).ConfigureAwait(false); - } - else - { - ct.ThrowIfCancellationRequested(); - await Task.Yield(); - } - - lock (_gate) - { - _offset += time - real; - } - } -} - internal static class TestZones { /// diff --git a/tests/Febe.Tests.Windows/Support/DesktopBed.cs b/tests/Febe.Tests.Windows/Support/DesktopBed.cs index 290d1af..285192e 100644 --- a/tests/Febe.Tests.Windows/Support/DesktopBed.cs +++ b/tests/Febe.Tests.Windows/Support/DesktopBed.cs @@ -8,6 +8,7 @@ using Febe.Desktop; using Febe.Desktop.Browser; using Febe.Desktop.Core; using Febe.SitoDiProva; +using Febe.Tests.Support; using Febe.Web.Native; namespace Febe.Tests.Windows.Support; @@ -15,14 +16,14 @@ namespace Febe.Tests.Windows.Support; /// /// The shared composition () as Febe.exe composes it — , /// DesktopShell, the window «Browser di Febe» on a WPF UI thread — against its own test site, in temporary -/// folders, on a clock ten times faster and in a zone where it is noon. The interface is asked like the main window asks +/// folders, on a clock five times faster () and in a zone where it is noon. The interface is asked like the main window asks /// it: with the token of this start and the Origin of the interface. /// internal sealed class DesktopBed : IAsyncDisposable { private readonly HttpClient _client; - private DesktopBed(TestSite site, TestFolder folder, UiThread ui, LogLines lines, CompressedClock clock, DesktopPlatform platform, FebeApp app) + private DesktopBed(TestSite site, TestFolder folder, UiThread ui, LogLines lines, ScaledClock clock, DesktopPlatform platform, FebeApp app) { Site = site; Folder = folder; @@ -47,7 +48,7 @@ internal sealed class DesktopBed : IAsyncDisposable /// What Febe wrote in its log. public LogLines Lines { get; } - public CompressedClock Clock { get; } + public ScaledClock Clock { get; } public DesktopPlatform Platform { get; } @@ -69,10 +70,13 @@ internal sealed class DesktopBed : IAsyncDisposable { var lines = new LogLines(); var data = folder.Combine("dati"); + + // «--prima-sessione» at its maximum, an hour (twelve minutes of real time): the only session start is the one + // a test asks for with «Controlla ora», as in the Linux suite (ServerTestBed). List arguments = [ "--dati", data, "--libreria", folder.Combine("libreria"), - "--sito-di-prova", site.SiteUrl, "--cdn-di-prova", site.CdnUrl, "--prima-sessione", "1", + "--sito-di-prova", site.SiteUrl, "--cdn-di-prova", site.CdnUrl, "--prima-sessione", "3600", ]; if (autoLogin) { @@ -87,7 +91,7 @@ internal sealed class DesktopBed : IAsyncDisposable } var zone = TestZones.Noon(); - var clock = new CompressedClock(10, zone); + var clock = new ScaledClock(5, zone); var shell = new DesktopShell(ui.Dispatcher, null, BrowserShell.Instance); var platform = new DesktopPlatform(options, shell, new MemoryLocations(), dataFolderFixed: true); var appOptions = options.AppOptions(data, new DesktopFolders(folder.Combine("AppData"), folder.Combine("Immagini"))) with { Zone = zone, ZoneId = zone.Id }; diff --git a/tests/Febe.Tests/Collection/Support/CollectionFakes.cs b/tests/Febe.Tests/Collection/Support/CollectionFakes.cs index 8ca6bf5..14924a3 100644 --- a/tests/Febe.Tests/Collection/Support/CollectionFakes.cs +++ b/tests/Febe.Tests/Collection/Support/CollectionFakes.cs @@ -8,7 +8,8 @@ namespace Febe.Tests.Collection.Support; /// /// A clock that compresses time: waits for real only a fraction of the requested time, and /// moves on by the whole of it. Recipes against a real browser keep their order of events, but a -/// 2.2-second «wait after load» lasts a few hundred milliseconds. +/// 2.2-second «wait after load» lasts a few hundred milliseconds. For one flow at a time: waits that overlap add up +/// (a whole composition, with its background loops, uses ). /// public sealed class CompressedClock : IClock { diff --git a/tests/Febe.Tests/Server/RemoteViewSocketTests.cs b/tests/Febe.Tests/Server/RemoteViewSocketTests.cs index 16f5d39..34eb98c 100644 --- a/tests/Febe.Tests/Server/RemoteViewSocketTests.cs +++ b/tests/Febe.Tests/Server/RemoteViewSocketTests.cs @@ -3,6 +3,7 @@ using System.Net.WebSockets; using System.Text; using Febe.Server; using Febe.Tests.Server.Support; +using Febe.Tests.Support; using Febe.Tests.Web.Support; using Febe.Web; using Febe.Web.Connection; @@ -74,7 +75,7 @@ public sealed class RemoteViewSocketTests await socket.SendAsync(Encoding.UTF8.GetBytes(message), WebSocketMessageType.Text, true, TestContext.CancellationToken); } - await ServerTestBed.WaitUntilAsync(() => Task.FromResult(view.Inputs.Count >= 4), TimeSpan.FromSeconds(10), "quattro gesti inoltrati"); + await TestWait.UntilAsync(() => view.Inputs.Count >= 4, "quattro gesti inoltrati"); await Task.Delay(200); var inputs = view.Inputs.ToArray(); Assert.HasCount(4, inputs, "out-of-range, unknown and malformed messages are dropped"); @@ -90,7 +91,7 @@ public sealed class RemoteViewSocketTests Assert.AreEqual(RemoteViewNavigation.Back, inputs[3]); await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "fine", TestContext.CancellationToken); - await ServerTestBed.WaitUntilAsync(() => Task.FromResult(view.Disposed), TimeSpan.FromSeconds(10), "la vista chiusa dal server"); + await TestWait.UntilAsync(() => view.Disposed, "la vista chiusa dal server"); } [TestMethod] @@ -106,7 +107,7 @@ public sealed class RemoteViewSocketTests await second.SendAsync(new byte[RemoteViewSocket.MaxMessageBytes + 10], WebSocketMessageType.Text, true, TestContext.CancellationToken); await ExpectCloseAsync(second, WebSocketCloseStatus.MessageTooBig); - await ServerTestBed.WaitUntilAsync(() => Task.FromResult(host.Opened[1].Disposed), TimeSpan.FromSeconds(10), "la vista chiusa"); + await TestWait.UntilAsync(() => host.Opened[1].Disposed, "la vista chiusa"); } [TestMethod] diff --git a/tests/Febe.Tests/Server/ScaledClockTests.cs b/tests/Febe.Tests/Server/ScaledClockTests.cs new file mode 100644 index 0000000..b9bff76 --- /dev/null +++ b/tests/Febe.Tests/Server/ScaledClockTests.cs @@ -0,0 +1,59 @@ +using System.Diagnostics; +using Febe.Core.Collection.Readers; +using Febe.Core.Collection.Recipes; +using Febe.Tests.Support; + +namespace Febe.Tests.Server; + +/// +/// The clock of the end-to-end tests (): waits that overlap must not add up. With a clock that +/// adds them up, the background loops of the server used up the time limits of the real browser and the few minutes of +/// the first session in a moment, and the files of the end-to-end test came only after the next one («Tempo scaduto: tre +/// file di marta.prova scaricati»). The bounds follow the real time measured around, so a loaded runner does not fail them. +/// +[TestClass] +public sealed class ScaledClockTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public async Task OverlappingWaitsPassTheSameTime() + { + const double factor = 100; + var clock = new ScaledClock(factor); + var real = Stopwatch.StartNew(); + var before = clock.Now; + await Task.WhenAll(Enumerable.Range(0, 10).Select(_ => clock.Delay(TimeSpan.FromSeconds(30), TestContext.CancellationToken))); + var passed = clock.Now - before; + + Assert.IsGreaterThanOrEqualTo(TimeSpan.FromSeconds(30), passed, "every wait lasted its whole time"); + Assert.IsLessThanOrEqualTo(real.Elapsed * factor, passed, "ten waits together pass the time of one, not of ten"); + } + + [TestMethod] + public async Task AWaitForThePageIsNotCutShortByTheLongWaitOfAnotherLoop() + { + // The wait of the recipes for the data of a page, as they do it, while another loop's long wait ends in the middle. + const double factor = 20; + var clock = new ScaledClock(factor); + var capture = new CaptureCollector(new ShapeReader(ReaderVocabulary.LoadTestSite()), clock); + var other = clock.Delay(TimeSpan.FromSeconds(60), TestContext.CancellationToken); + await clock.Delay(TimeSpan.FromSeconds(50), TestContext.CancellationToken); + + var real = Stopwatch.StartNew(); + await capture.WaitAsync(capture.Mark(), _ => false, TimeSpan.FromSeconds(20), TimeSpan.FromMilliseconds(100), TestContext.CancellationToken); + Assert.IsGreaterThanOrEqualTo(TimeSpan.FromSeconds(20 / factor) - TimeSpan.FromMilliseconds(50), real.Elapsed, "the page had its whole time"); + await other; + } + + [TestMethod] + public async Task AWaitEndsWhenItIsCancelled() + { + var clock = new ScaledClock(10); + using var cancel = new CancellationTokenSource(); + var wait = clock.Delay(TimeSpan.FromHours(1), cancel.Token); + await cancel.CancelAsync(); + await Assert.ThrowsAsync(() => wait); + await Assert.ThrowsAsync(() => clock.Delay(TimeSpan.Zero, cancel.Token)); + } +} diff --git a/tests/Febe.Tests/Server/ServerEndToEndTests.cs b/tests/Febe.Tests/Server/ServerEndToEndTests.cs index a7f065f..1e3e9bf 100644 --- a/tests/Febe.Tests/Server/ServerEndToEndTests.cs +++ b/tests/Febe.Tests/Server/ServerEndToEndTests.cs @@ -37,7 +37,7 @@ public sealed partial class ServerEndToEndTests } [TestMethod] - [Timeout(540_000, CooperativeCancellation = true)] + [Timeout(900_000, CooperativeCancellation = true)] public async Task TheRealServerCollectsFromTheTestSiteStopsAtTheVerificationAndShowsTheBrowser() { var ct = TestContext.CancellationToken; @@ -86,16 +86,11 @@ public sealed partial class ServerEndToEndTests Assert.AreEqual(ConnectionState.Connected, (await connection.GetStatusAsync(ct)).State); // «Controlla ora». - var check = await bed.JsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Id}/check-now"); - if (check.GetProperty("status").GetString() == "needsConfirmation") - { - check = await bed.JsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Id}/check-now", $$"""{"token":"{{check.GetProperty("token").GetString()}}"}"""); - } - + var check = await CheckNowAsync(bed, marta.Id); Assert.AreEqual("queued", check.GetProperty("status").GetString(), check.GetProperty("message").GetString()); // The engine runs a session: every action toward the site has its Governor's permit in action_log. - await ServerTestBed.WaitUntilAsync( + await bed.WaitUntilAsync( async () => (await server.Database.ActionLog.ListAsync(DateTimeOffset.UnixEpoch, bed.Clock.Now.AddDays(1), ct)).Any(a => a.AccountId == marta.Id), TimeSpan.FromSeconds(90), "un'azione del motore su marta.prova nel registro delle azioni"); @@ -103,11 +98,18 @@ public sealed partial class ServerEndToEndTests Assert.IsTrue(actions.All(a => a.SessionId is not null), "every counted action belongs to a session"); Assert.IsNotNull(await server.Database.Sessions.GetLastAsync(ct)); + // The session is the one Alberto asked for, and starts from the account he chose: not a session of the engine's + // own that began at «Ho finito», before his request. + if (actions.First(a => a.AccountId is not null).AccountId != marta.Id) + { + Assert.Fail($"La prima azione della sessione non è su marta.prova, chiesta con «Controlla ora».\n{await bed.DescribeAsync()}"); + } + // Files arrive in the library with the names of the scheme, and their thumbnails. var library = bed.Library; var thumbnails = bed.Thumbnails; List<(Entry Entry, Media Media)> stored = []; - await ServerTestBed.WaitUntilAsync( + await bed.WaitUntilAsync( async () => { stored = await StoredAsync(server, marta.Id, ct); @@ -133,8 +135,9 @@ public sealed partial class ServerEndToEndTests TestContext.WriteLine($"Ricette: {string.Join(", ", recipes.Select(r => r.Code).Distinct())}; file di marta.prova: {stored.Count}."); // The site asks for a verification: at its next action toward the site the engine stops and the banner appears - // in /api/engine. Usually still in the first session (two accounts to read in full); if that session already - // ended, in the next one, after the minimum pause (20 minutes at 10×: two real minutes). + // in /api/engine. Usually still in the first session (two accounts to read in full). Were that session over, or + // ending right now, the next one would come 20 to 90 minutes later (4 to 18 real ones at 5×): «Controlla ora» again + // brings it to the minimum pause, four real minutes. // Alerts on Telegram (M8): token and chat set from Impostazioni ▸ Notifiche; the composition sends through the fake. const string token = "4839574812:AAF-gettoneDelServerDiProva_123"; var events = """{"verification":true,"disconnection":true,"throttle":true,"backfillDone":true,"diskLow":true,"unknownFormat":true}"""; @@ -142,20 +145,21 @@ public sealed partial class ServerEndToEndTests var servedBefore = bed.Site.Control.CdnFilesServed; bed.Site.Control.Set(StopMode.Challenge); - await ServerTestBed.WaitUntilAsync( + await CheckNowAsync(bed, marta.Id); + await bed.WaitUntilAsync( async () => { var engine = await bed.JsonAsync(HttpMethod.Get, "/api/engine"); var snapshot = engine.GetProperty("snapshot"); return snapshot.GetProperty("mode").GetString() == "StoppedForVerification" && snapshot.GetProperty("banner").ValueKind == JsonValueKind.Object; }, - TimeSpan.FromSeconds(200), + TimeSpan.FromSeconds(360), "la striscia di arresto per la verifica in /api/engine"); Assert.AreEqual(ConnectionState.VerificationRequired, (await connection.GetStatusAsync(ct)).State); TestContext.WriteLine($"CDN: {servedBefore} file prima del fermo, {bed.Site.Control.CdnFilesServed} adesso."); // The same stop reached Telegram, with the Italian text, and the «Avvisi» list of Attività. - await ServerTestBed.WaitUntilAsync( + await bed.WaitUntilAsync( () => Task.FromResult(telegram.Requests.Any(r => r.Text.StartsWith("Febe · Instagram chiede una verifica\n", StringComparison.Ordinal))), TimeSpan.FromSeconds(20), "il messaggio Telegram della verifica"); @@ -200,7 +204,7 @@ public sealed partial class ServerEndToEndTests await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "fine", ct); } - await ServerTestBed.WaitUntilAsync(() => Task.FromResult(!server.Browser.UserIsDriving), TimeSpan.FromSeconds(10), "la vista chiusa libera il browser"); + await bed.WaitUntilAsync(() => Task.FromResult(!server.Browser.UserIsDriving), TimeSpan.FromSeconds(10), "la vista chiusa libera il browser"); } [TestMethod] @@ -222,7 +226,7 @@ public sealed partial class ServerEndToEndTests Assert.IsTrue(server.Browser.IsAvailable, "the browser runs again, with an empty profile"); Assert.AreEqual(ConnectionState.NotConnected, (await connection.GetStatusAsync(ct)).State); Assert.IsFalse(server.Browser.UserIsDriving); - await ServerTestBed.WaitUntilAsync( + await bed.WaitUntilAsync( () => Task.FromResult(server.Engine!.Services.Runtime.IsRunning), TimeSpan.FromSeconds(60), "il motore di nuovo in funzione, in attesa del collegamento"); @@ -272,7 +276,7 @@ public sealed partial class ServerEndToEndTests // From the rest page: where the browser starts, and where the engine puts it once nobody is at the browser. // Page.getFrameTree is answered by the page itself, which DevTools holds back while a navigation is pending: // «about:blank» here means the engine's rest has committed. - await ServerTestBed.WaitUntilAsync( + await bed.WaitUntilAsync( async () => await Febe.Browser.Cdp.CdpPageExtensions.GetMainFrameUrlAsync(server.Browser.Cdp, ct) == "about:blank", TimeSpan.FromSeconds(60), "la pagina di riposo"); @@ -322,7 +326,7 @@ public sealed partial class ServerEndToEndTests { // From the rest page, as in TwoViews…: the previous round ends on a site page, so «about:blank» here means the // engine's rest after the last view has committed and nothing else navigates. - await ServerTestBed.WaitUntilAsync( + await bed.WaitUntilAsync( async () => await Febe.Browser.Cdp.CdpPageExtensions.GetMainFrameUrlAsync(browser.Cdp, ct) == "about:blank", TimeSpan.FromSeconds(60), "la pagina di riposo"); @@ -377,6 +381,16 @@ public sealed partial class ServerEndToEndTests return false; } + /// «Controlla ora», confirmed when Febe asks for it. + private static async Task CheckNowAsync(ServerTestBed bed, long accountId) + { + var path = $"/api/accounts/{accountId}/check-now"; + var check = await bed.JsonAsync(HttpMethod.Post, path); + return check.GetProperty("status").GetString() == "needsConfirmation" + ? await bed.JsonAsync(HttpMethod.Post, path, $$"""{"token":"{{check.GetProperty("token").GetString()}}"}""") + : check; + } + private static async Task> StoredAsync(Febe.Server.FebeServer server, long accountId, CancellationToken ct) { var list = new List<(Entry, Media)>(); diff --git a/tests/Febe.Tests/Server/Support/ServerTestBed.cs b/tests/Febe.Tests/Server/Support/ServerTestBed.cs index fa23913..29c6c71 100644 --- a/tests/Febe.Tests/Server/Support/ServerTestBed.cs +++ b/tests/Febe.Tests/Server/Support/ServerTestBed.cs @@ -1,3 +1,4 @@ +using System.Globalization; using System.Net; using System.Net.WebSockets; using System.Text; @@ -5,11 +6,12 @@ using System.Text.Json; using Febe.Browser.Hosting; using Febe.Core.Abstractions; using Febe.Core.Alerts; +using Febe.Core.Domain; using Febe.Core.Library; +using Febe.Core.Storage; using Febe.Server; using Febe.SitoDiProva; using Febe.Tests.Browser.TestSupport; -using Febe.Tests.Collection.Support; using Febe.Tests.Support; namespace Febe.Tests.Server.Support; @@ -17,14 +19,16 @@ namespace Febe.Tests.Server.Support; /// /// The real server composition () against the local test site, with Xvfb and a real Chromium, /// in a temporary Data/Library/Import folder, on free ports and a free display. Never Instagram: the browser only ever -/// sees 127.0.0.1. Time runs on a compressed clock (10×) in a time zone where it is around noon now, so that the -/// engine is inside its active window whatever the hour of the test. +/// sees 127.0.0.1. Time runs five times faster () in a time zone where it is around noon now, so +/// that the engine is inside its active window whatever the hour of the test. Five and not more: the engine's few minutes +/// and pauses stay short, and the limits of a real page (30 seconds to load, 20 for its data) are six and four real +/// seconds. /// internal sealed class ServerTestBed : IAsyncDisposable { public const string Password = "una password di prova per il server"; - private ServerTestBed(TempFolder temp, TestSite site, FebeServer server, CompressedClock clock, ServerOptions options) + private ServerTestBed(TempFolder temp, TestSite site, FebeServer server, ScaledClock clock, ServerOptions options) { Temp = temp; Site = site; @@ -44,7 +48,7 @@ internal sealed class ServerTestBed : IAsyncDisposable public FebeServer Server { get; } - public CompressedClock Clock { get; } + public ScaledClock Clock { get; } public ServerOptions Options { get; } @@ -57,12 +61,12 @@ internal sealed class ServerTestBed : IAsyncDisposable public static string? UnavailableReason() => RealBrowser.UnavailableReason(); - public static async Task StartAsync(bool autoLogin = false, double factor = 10, HttpMessageHandler? telegram = null, IFreeSpaceProbe? freeSpace = null) + public static async Task StartAsync(bool autoLogin = false, double factor = 5, HttpMessageHandler? telegram = null, IFreeSpaceProbe? freeSpace = null) { var temp = new TempFolder("server"); var site = await SyntheticSite.StartAsync(); var zone = NoonZone(); - var clock = new CompressedClock(factor, zone); + var clock = new ScaledClock(factor, zone); var options = new ServerOptions { Password = Password, @@ -81,7 +85,10 @@ internal sealed class ServerTestBed : IAsyncDisposable TestSite = new Uri(site.SiteUrl + "/"), TestCdn = new Uri(site.CdnUrl + "/"), TestSiteAutoLogin = autoLogin, - FirstSessionDelay = TimeSpan.FromSeconds(1), + + // The only session start is the one the test asks for («Controlla ora»): far beyond the length of a test. + // With a due session, the engine started it at «Ho finito», before the request, with another account first. + FirstSessionDelay = TimeSpan.FromHours(4), }; Directory.CreateDirectory(options.ImportFolder); FebeServer server; @@ -185,9 +192,11 @@ internal sealed class ServerTestBed : IAsyncDisposable } } - /// Waits (real time) until holds; fails with otherwise. - - public static async Task WaitUntilAsync(Func> condition, TimeSpan timeout, string what) + /// + /// Waits (real time) until holds; otherwise fails with and what + /// Febe was doing (). + /// + public async Task WaitUntilAsync(Func> condition, TimeSpan timeout, string what) { var deadline = DateTime.UtcNow + timeout; while (true) @@ -199,13 +208,95 @@ internal sealed class ServerTestBed : IAsyncDisposable if (DateTime.UtcNow > deadline) { - Assert.Fail($"Tempo scaduto: {what}."); + Assert.Fail($"Tempo scaduto ({timeout.TotalSeconds:0} s): {what}.\n{await DescribeAsync()}"); } await Task.Delay(250); } } + /// + /// What Febe was doing, for a wait that ran out: engine, breaker, sessions, queue, actions, events, states of the + /// files and the tail of the log. Only what the interface and the log already say (the log is scrubbed, rule 10); + /// never payloads, addresses of files, cookies or bodies. Never throws. + /// + public async Task DescribeAsync() + { + var text = new StringBuilder(); + var from = DateTimeOffset.UnixEpoch; + var to = Clock.Now.AddDays(1); + await AppendAsync("Motore", () => + { + var runtime = Server.Engine?.Services.Runtime; + var session = runtime?.CurrentSession; + return Task.FromResult>( + [ + $"adesso {Time(Clock.Now)} (tempo ×{Clock.Factor:0}); in funzione {runtime?.IsRunning}, collegato {runtime?.IsConnected}, guida Alberto {runtime?.UserIsDriving}, pausa {runtime?.IsPaused}", + $"sessione {(session is null ? "nessuna" : $"{session.SessionId} fino alle {Time(session.PlannedEnd)}")}; prossima {Time(runtime?.NextSessionAt)}; attività «{runtime?.Activity}»", + $"interruttore {Server.Engine?.Services.Breaker.State.Status}; scaricamenti in pausa fino alle {Time(Server.Pipeline?.Downloads.PausedUntil)}; browser: {Server.Browser?.LastError ?? "nessun errore"}", + $"sito di prova: {Site.Control.CdnFilesServed} file serviti dal CDN", + ]); + }); + await AppendAsync("Sessioni", async () => (await Server.Database.Sessions.ListAsync(from, to)) + .Select(s => $"{s.Id}: {Time(s.StartedAt)}–{Time(s.EndedAt)} {s.Outcome}, {s.ActionCount} azioni. {s.Summary}")); + await AppendAsync("Coda", async () => (await Server.Database.Tasks.ListPendingAsync(20)) + .Select(t => $"{t.Kind} account {t.AccountId} alle {Time(t.DueAt)}, priorità {t.Priority}, tentativi {t.Attempts}. {t.LastError}")); + await AppendAsync("Ultime azioni", async () => (await Server.Database.ActionLog.ListAsync(from, to)) + .TakeLast(20).Select(a => $"{Time(a.At)} {a.Category} account {a.AccountId}, sessione {a.SessionId}, {a.Amount}")); + await AppendAsync("Ultimi eventi", async () => (await Server.Database.Events.ListAsync(new EventQuery { Limit = 20 })) + .Reverse().Select(e => $"{Time(e.At)} {e.Severity} {e.Code}: {e.Message}")); + await AppendAsync("File", async () => + { + var states = new List(); + foreach (var account in await Server.Database.Accounts.ListAsync()) + { + var files = new List(); + foreach (var entry in await Server.Database.Entries.ListByAccountAsync(account.Id, null)) + { + files.AddRange(await Server.Database.Media.ListByEntryAsync(entry.Id)); + } + + states.AddRange(files.GroupBy(m => (m.State, m.Attempts, m.LastError)) + .Select(g => $"account {account.Id}: {g.Count()} {g.Key.State}, tentativi {g.Key.Attempts}. {g.Key.LastError}")); + } + + return states; + }); + await AppendAsync("Registro", async () => + { + var lines = new List(); + foreach (var file in Directory.EnumerateFiles(Server.Data!.Logs).Order(StringComparer.Ordinal)) + { + await using var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + using var reader = new StreamReader(stream); + lines.AddRange((await reader.ReadToEndAsync()).Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)); + } + + return lines.TakeLast(40); + }); + return text.ToString(); + + async Task AppendAsync(string title, Func>> read) + { + text.Append("== ").Append(title).Append('\n'); + try + { + foreach (var line in await read().WaitAsync(TimeSpan.FromSeconds(10))) + { + text.Append(line).Append('\n'); + } + } + catch (Exception ex) + { + // The timeout is the failure to report: what cannot be read is said and the rest follows. + text.Append("non leggibile: ").Append(ex.GetType().Name).Append('\n'); + } + } + + string Time(DateTimeOffset? at) => + at is { } instant ? TimeZoneInfo.ConvertTime(instant, Clock.LocalZone).ToString("HH:mm:ss", CultureInfo.InvariantCulture) : "—"; + } + public async ValueTask DisposeAsync() { Client.Dispose(); diff --git a/tests/Febe.Tests/Support/ScaledClock.cs b/tests/Febe.Tests/Support/ScaledClock.cs new file mode 100644 index 0000000..117a6bf --- /dev/null +++ b/tests/Febe.Tests/Support/ScaledClock.cs @@ -0,0 +1,36 @@ +using System.Diagnostics; +using Febe.Core.Abstractions; + +namespace Febe.Tests.Support; + +/// +/// A clock that runs times faster than the real one: is a function of the real +/// time alone, and waits that fraction of the requested time. For whole compositions, where many +/// background loops wait at the same time: their waits overlap as they do in reality, so none of them moves the time +/// of the others. (A clock that adds every wait to counts overlapping waits more than once: the time +/// then jumps, and a 30-second limit on a real browser may end at once.) Measured with the monotonic timer, so a +/// correction of the system time does not move it. +/// +internal sealed class ScaledClock(double factor, TimeZoneInfo? zone = null) : IClock +{ + private readonly DateTimeOffset _start = DateTimeOffset.UtcNow; + private readonly long _startStamp = Stopwatch.GetTimestamp(); + + public double Factor { get; } = factor >= 1 ? factor : throw new ArgumentOutOfRangeException(nameof(factor)); + + public TimeZoneInfo LocalZone { get; } = zone ?? TimeZoneInfo.Utc; + + public DateTimeOffset Now => _start + (Stopwatch.GetElapsedTime(_startStamp) * Factor); + + public async Task Delay(TimeSpan time, CancellationToken ct) + { + ct.ThrowIfCancellationRequested(); + var target = Now + time; + for (var left = time; left > TimeSpan.Zero; left = target - Now) + { + // Task.Delay counts whole milliseconds and may end a moment early: never less than one, then look again. + var real = left / Factor; + await Task.Delay(real > TimeSpan.FromMilliseconds(1) ? real : TimeSpan.FromMilliseconds(1), ct).ConfigureAwait(false); + } + } +}