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

+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();