Files
Febe/tests/Febe.Tests/Server/Support/ServerTestBed.cs
T
Alby96andClaude Opus 5.5 4dc3a83a51
verifica / controlli (push) Successful in 22s
verifica / prove (push) Successful in 23m56s
verifica / installatore (push) Successful in 2m6s
verifica / immagine (push) In progress
Merge remote-tracking branch 'origin/main' into correzione/prova-da-capo-a-fondo
Revisione: la causa è l'orologio che somma le attese, e «Controlla ora» si chiede
di nuovo prima di aspettare la verifica, perché a sessione finita la pausa può
arrivare a 90 minuti.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 17:54:28 +01:00

308 lines
13 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Globalization;
using System.Net;
using System.Net.WebSockets;
using System.Text;
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.Support;
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 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, ScaledClock clock, ServerOptions options)
{
Temp = temp;
Site = site;
Server = server;
Clock = clock;
Options = options;
Client = new HttpClient(new HttpClientHandler { UseCookies = true, CookieContainer = Cookies, AllowAutoRedirect = false })
{
BaseAddress = server.Address,
Timeout = TimeSpan.FromSeconds(30),
};
}
public TempFolder Temp { get; }
public TestSite Site { get; }
public FebeServer Server { get; }
public ScaledClock Clock { get; }
public ServerOptions Options { get; }
public CookieContainer Cookies { get; } = new();
public HttpClient Client { get; }
/// <summary>«http://127.0.0.1:port»: the Origin of requests coming from the interface.</summary>
public string Origin => $"{Server.Address.Scheme}://{Server.Address.Authority}";
public static string? UnavailableReason() => RealBrowser.UnavailableReason();
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 ScaledClock(factor, zone);
var options = new ServerOptions
{
Password = Password,
ListenAddress = IPAddress.Loopback,
Port = 0,
ZoneId = zone.Id,
Zone = zone,
Language = "it_IT.UTF-8",
DataFolder = temp.Combine("dati"),
LibraryFolder = temp.Combine("libreria"),
ImportFolder = temp.Combine("importa"),
NoSandbox = RealBrowser.IsRoot,
ChromiumPath = RealBrowser.ChromiumPath(),
DebugPort = LocalTestSite.FreePort(),
Display = XvfbProcess.FindFreeDisplay(300, 399) ?? throw new InvalidOperationException("Nessun display libero."),
TestSite = new Uri(site.SiteUrl + "/"),
TestCdn = new Uri(site.CdnUrl + "/"),
TestSiteAutoLogin = autoLogin,
// 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;
try
{
server = await FebeServer.StartAsync(options, new ServerHooks { Clock = clock, Random = new SeededRandom(20261013), Console = TextWriter.Null, TelegramHandler = telegram, FreeSpace = freeSpace });
}
catch
{
await site.DisposeAsync();
temp.Dispose();
throw;
}
return new ServerTestBed(temp, site, server, clock, options);
}
/// <summary>
/// A fixed-offset zone where the local time is between 12:00 and 13:00 now: inside the active window of every
/// caution profile, so the test does not depend on when it runs.
/// </summary>
public static TimeZoneInfo NoonZone()
{
var offset = 12 - DateTimeOffset.UtcNow.Hour;
if (offset > 12)
{
offset -= 24;
}
else if (offset < -12)
{
offset += 24;
}
// The sign of the Etc/GMT names is inverted: Etc/GMT-2 is two hours east of Greenwich.
var id = offset == 0 ? "Etc/GMT" : offset > 0 ? $"Etc/GMT-{offset}" : $"Etc/GMT+{-offset}";
return TimeZoneInfo.FindSystemTimeZoneById(id);
}
/// <summary>Logs in with the interface password (cookie in <see cref="Cookies"/>).</summary>
public async Task LoginAsync()
{
using var response = await SendAsync(HttpMethod.Post, "/api/accesso", $$"""{"password":"{{Password}}"}""");
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, await response.Content.ReadAsStringAsync());
}
/// <summary>A request as the interface sends it: Origin of the interface, JSON body.</summary>
public async Task<HttpResponseMessage> SendAsync(HttpMethod method, string path, string? json = null)
{
using var request = new HttpRequestMessage(method, path);
request.Headers.TryAddWithoutValidation("Origin", Origin);
if (json is not null)
{
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
}
return await Client.SendAsync(request);
}
public async Task<JsonElement> JsonAsync(HttpMethod method, string path, string? json = null)
{
using var response = await SendAsync(method, path, json);
var text = await response.Content.ReadAsStringAsync();
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, $"{path}: {text}");
return JsonDocument.Parse(text).RootElement.Clone();
}
/// <summary>The remote view, opened like the Browser page does: session cookie and Origin of the interface.</summary>
public async Task<ClientWebSocket> OpenRemoteViewAsync(CancellationToken ct)
{
var socket = new ClientWebSocket();
socket.Options.Cookies = Cookies;
socket.Options.SetRequestHeader("Origin", Origin);
var address = new UriBuilder(Server.Address) { Scheme = "ws", Path = "/api/vista" }.Uri;
await socket.ConnectAsync(address, ct);
return socket;
}
public LibraryLayout Library => Server.Library ?? throw new InvalidOperationException("Nessuna libreria.");
public ThumbnailStore Thumbnails => new(Server.Data!.Thumbnails);
/// <summary>
/// The hang guard of <see cref="WaitRunningAsync"/>. A cold Chromium start on a loaded runner can take minutes,
/// with a retry after a failed attempt (#46); the wait ends as soon as Febe is up.
/// </summary>
public static readonly TimeSpan RunningPatience = TimeSpan.FromMinutes(4);
/// <summary>
/// Waits until Febe has started (Xvfb, Chromium, pipeline, connection, engine). A start that never ends fails with
/// the last error of the browser instead of a bare timeout.
/// </summary>
public async Task WaitRunningAsync(CancellationToken ct)
{
try
{
await Server.Running.WaitAsync(RunningPatience, ct);
}
catch (TimeoutException)
{
Assert.Fail($"Febe non è partito in {RunningPatience.TotalMinutes:0} minuti: {Server.Browser?.LastError ?? "nessun errore del browser"}.");
}
}
/// <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)
{
if (await condition())
{
return;
}
if (DateTime.UtcNow > deadline)
{
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();
await Server.DisposeAsync();
await Site.DisposeAsync();
Temp.Dispose();
}
}