Unione di main (#79) nel ramo della tappa E4

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-01 21:07:33 +01:00
commit 7b42bb74eb
12 files changed
+255 -90

No files matched your search

@@ -8,7 +8,8 @@ namespace Febe.Tests.Collection.Support;
/// <summary>
/// A clock that compresses time: <see cref="Delay"/> waits for real only a fraction of the requested time, and
/// <see cref="Now"/> 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 <see cref="Febe.Tests.Support.ScaledClock"/>).
/// </summary>
public sealed class CompressedClock : IClock
{
@@ -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));
}
}
+32 -18
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;
@@ -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;
}
/// <summary>«Controlla ora», confirmed when Febe asks for it.</summary>
private static async Task<JsonElement> 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<List<(Entry Entry, Media Media)>> StoredAsync(Febe.Server.FebeServer server, long accountId, CancellationToken ct)
{
var list = new List<(Entry, Media)>();
+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) are six and four real
/// seconds.
/// </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();
+36
View File
@@ -0,0 +1,36 @@
using System.Diagnostics;
using Febe.Core.Abstractions;
namespace Febe.Tests.Support;
/// <summary>
/// A clock that runs <see cref="Factor"/> times faster than the real one: <see cref="Now"/> is a function of the real
/// time alone, and <see cref="Delay"/> 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 <see cref="Now"/> 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.
/// </summary>
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);
}
}
}