Correzione: la prova da capo a fondo del server non perde più la prima sessione

«Tempo scaduto: tre file di marta.prova scaricati» era un difetto della prova: l'orologio
compresso sommava le attese dei lavori di sottofondo (circa 34 volte invece di 10, a salti) e
consumava in un attimo i limiti delle pagine vere e la prima sessione; inoltre il motore apriva
la sua sessione a «Ho finito», prima di «Controlla ora», con luca.prova per primo. Finita la
sessione, i file aspettavano la prossima: 120 secondi veri, più dei 90 della prova.

Ora le composizioni intere usano ScaledClock (attese sovrapposte = stesso tempo, 5 volte), la sola
sessione è quella chiesta con «Controlla ora», e un'attesa scaduta dice che cosa faceva Febe.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-01 17:00:10 +01:00
1 parent 6d66cf96d3
commit 66a3873554
12 files changed
+242 -83

No files matched your search

@@ -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]
@@ -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;
/// <summary>
/// The clock of the end-to-end tests (<see cref="ScaledClock"/>): 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.
/// </summary>
[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<OperationCanceledException>(() => wait);
await Assert.ThrowsAsync<OperationCanceledException>(() => clock.Delay(TimeSpan.Zero, cancel.Token));
}
}
+19 -11
View File
@@ -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;
@@ -95,7 +95,7 @@ public sealed partial class ServerEndToEndTests
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 +103,19 @@ 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 his account. Another account first (a session of the
// engine's own that began at «Ho finito») leaves little of these few minutes to marta.prova, and once they end the
// files have to wait for the next session: say it here, not after a wait that cannot succeed.
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);
@@ -134,7 +142,7 @@ public sealed partial class ServerEndToEndTests
// 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).
// ended, in the next one, after the minimum pause (20 minutes at 5×: 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 +150,20 @@ public sealed partial class ServerEndToEndTests
var servedBefore = bed.Site.Control.CdnFilesServed;
bed.Site.Control.Set(StopMode.Challenge);
await ServerTestBed.WaitUntilAsync(
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 +208,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 +230,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 +280,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 +330,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");
+103 -12
View File
@@ -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;
/// <summary>
/// The real server composition (<see cref="FebeServer"/>) 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 (<see cref="ScaledClock"/>) 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) stay seconds on a loaded
/// runner.
/// </summary>
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<ServerTestBed> StartAsync(bool autoLogin = false, double factor = 10, HttpMessageHandler? telegram = null, IFreeSpaceProbe? freeSpace = null)
public static async Task<ServerTestBed> 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
}
}
/// <summary>Waits (real time) until <paramref name="condition"/> holds; fails with <paramref name="what"/> otherwise.</summary>
public static async Task WaitUntilAsync(Func<Task<bool>> condition, TimeSpan timeout, string what)
/// <summary>
/// Waits (real time) until <paramref name="condition"/> holds; otherwise fails with <paramref name="what"/> and what
/// Febe was doing (<see cref="DescribeAsync"/>).
/// </summary>
public async Task WaitUntilAsync(Func<Task<bool>> 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);
}
}
/// <summary>
/// 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.
/// </summary>
public async Task<string> 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<IEnumerable<string>>(
[
$"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<string>();
foreach (var account in await Server.Database.Accounts.ListAsync())
{
var files = new List<Media>();
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<string>();
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<Task<IEnumerable<string>>> 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();