using System.Collections.Concurrent; using System.Diagnostics; using System.Net.WebSockets; using System.Text; using System.Text.Json; using System.Text.Json.Nodes; using Febe.Tests.Browser.TestSupport; namespace Febe.Tests.Web.Support; /// /// A headless Chromium that drives Febe's own interface, like tools/schermate: only addresses on 127.0.0.1, never /// Instagram (spec §2). It speaks the DevTools protocol directly, without the command policy of Febe's own client, /// because here the tests click, type and run scripts in Febe's pages. Inconclusive when Chromium is missing. /// internal sealed class UiBrowser : IAsyncDisposable { /// /// Installed before the page scripts: what the page asks of the server, and answers that come when the test says. /// /// window.__asked: every request the page started, in order («GET /api/connection», «POST /// /api/connection/begin», «WS /api/vista»); window.__sockets: its WebSockets. /// window.__busy(): the requests not over yet. A fetch is over once the page's own continuation of /// its answer has run, and the body it reads there (as api.js does) has arrived; a WebSocket once it is open or /// closed. See . /// window.__hold(match) holds back every fetch whose address contains match, from then until /// window.__release(match), also one the page aborts meanwhile. The release lets them go and ends the hold: /// later requests pass at once, and the address can be held again (twice at the same time is an error). /// window.__started[match] counts the held-back requests that started and window.__done[match] /// those that are over, adding up all the holds of that address. /// /// An answer is late because the test holds it, never because of a delay the page might outlast on a slow machine: /// the test waits until the page has asked (__started), does what has to come first, releases it, and /// checks once the page is done with it (__done). /// public const string Requests = """ (() => { const fetchNow = window.fetch.bind(window); const later = window.setTimeout.bind(window); const NativeSocket = window.WebSocket; const holds = []; let busy = 0; const count = (counts, key) => { counts[key] = (counts[key] || 0) + 1; }; const pathOf = (url) => { const u = new URL(url, location.href); return u.pathname + u.search; }; window.__asked = []; window.__sockets = []; window.__started = {}; window.__done = {}; window.__busy = () => busy; window.__hold = (match) => { if (holds.some((h) => h.match === match)) throw new Error(`richieste già trattenute per ${match}`); let release; holds.push({ match, gate: new Promise((resolve) => { release = resolve; }), release: () => release() }); return true; }; // The requests held so far keep their hold and count as over under its match; the next ones pass. window.__release = (match) => { const index = holds.findIndex((h) => h.match === match); if (index < 0) throw new Error(`nessuna richiesta trattenuta per ${match}`); holds.splice(index, 1)[0].release(); return true; }; window.fetch = async (input, init) => { const url = input instanceof Request ? input.url : String(input); const method = ((init && init.method) || (input instanceof Request ? input.method : 'GET')).toUpperCase(); const hold = holds.find((h) => url.includes(h.match)); window.__asked.push(`${method} ${pathOf(url)}`); if (hold) count(window.__started, hold.match); busy += 1; let read = Promise.resolve(); try { if (hold) await hold.gate; const response = await fetchNow(input, init); for (const name of ['json', 'text', 'blob', 'arrayBuffer']) { const body = response[name].bind(response); response[name] = () => { const reading = body(); read = reading.then(() => {}, () => {}); return reading; }; } return response; } finally { // The page's continuation of this answer runs before the first timer and, if it reads the body, the // continuation of that read runs before the second. later(() => read.then(() => later(() => { busy -= 1; if (hold) count(window.__done, hold.match); }))); } }; window.WebSocket = class extends NativeSocket { constructor(...args) { super(...args); window.__asked.push(`WS ${pathOf(this.url)}`); window.__sockets.push(this); busy += 1; let connecting = true; const over = () => { if (!connecting) return; connecting = false; busy -= 1; }; this.addEventListener('open', over); this.addEventListener('close', over); } }; })(); """; /// /// The hang guard of every wait of this browser: its start, each DevTools command, each condition. The waits end as /// soon as their condition holds; the guard only bounds a hang, sized for a loaded runner (#46). A browser that dies /// fails the wait at once. /// internal static readonly TimeSpan Patience = TimeSpan.FromMinutes(2); private readonly Process _process; private readonly ConcurrentQueue _stderr; private readonly ClientWebSocket _socket; private readonly string _profile; private readonly ConcurrentDictionary> _pending = new(); private readonly CancellationTokenSource _stop = new(); private readonly SemaphoreSlim _send = new(1, 1); private readonly Task _reader; private int _id; private UiBrowser(Process process, ConcurrentQueue stderr, ClientWebSocket socket, string profile) { _process = process; _stderr = stderr; _socket = socket; _profile = profile; _reader = Task.Run(ReadLoopAsync); } /// Uncaught exceptions and console errors of the pages (shown when a test fails). public ConcurrentQueue Problems { get; } = new(); public static async Task StartAsync(int width = 1280, int height = 900) { if (!OperatingSystem.IsLinux() || RealBrowser.ChromiumPath() is not { } chromium) { Assert.Inconclusive("Chromium non trovato (impostare FEBE_CHROMIUM): le prove dell'interfaccia nel browser non girano."); throw new UnreachableException(); } var profile = Path.Combine(Path.GetTempPath(), "febe-interfaccia-" + Guid.NewGuid().ToString("N")); var info = new ProcessStartInfo(chromium) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, }; // Port 0: Chromium picks a free port and says which (stderr and DevToolsActivePort), so no other process can take // it between a free-port probe and the bind. Only this test browser: Febe's own browser keeps a fixed port (§6.1). foreach (var argument in new[] { "--headless", "--disable-gpu", "--hide-scrollbars", "--no-first-run", "--no-default-browser-check", "--disable-extensions", "--disable-background-networking", "--disable-component-update", "--no-proxy-server", "--mute-audio", $"--window-size={width},{height}", $"--user-data-dir={profile}", "--remote-debugging-port=0", "--remote-debugging-address=127.0.0.1", "about:blank", }) { info.ArgumentList.Add(argument); } if (RealBrowser.IsRoot) { info.ArgumentList.Add("--no-sandbox"); } foreach (var (key, value) in RealBrowser.BrowserEnvironment) { if (value is null) { info.Environment.Remove(key); } else { info.Environment[key] = value; } } var process = Process.Start(info) ?? throw new InvalidOperationException("Chromium non parte."); var stderr = new ConcurrentQueue(); var listening = 0; process.OutputDataReceived += (_, _) => { }; process.ErrorDataReceived += (_, e) => { if (e.Data is { } line) { if (ListeningPort(line) is > 0 and var found) { Interlocked.CompareExchange(ref listening, found, 0); } stderr.Enqueue(line); while (stderr.Count > 20 && stderr.TryDequeue(out string? _)) { } } }; process.BeginOutputReadLine(); process.BeginErrorReadLine(); try { // By condition: the port Chromium chose, then a page target. Fails at once if Chromium exits. using var http = new HttpClient(new HttpClientHandler { UseProxy = false }) { Timeout = TimeSpan.FromSeconds(10) }; string? debugger = null; var watch = Stopwatch.StartNew(); while (debugger is null) { if (process.HasExited) { throw new InvalidOperationException($"Chromium si è chiuso all'avvio (codice {process.ExitCode}). {Tail(stderr)}"); } if (watch.Elapsed > Patience) { throw new TimeoutException($"Chromium non risponde sulla porta di debug dopo {Patience.TotalSeconds:0} s. {Tail(stderr)}"); } var port = Volatile.Read(ref listening) is > 0 and var known ? known : ReadActivePort(profile); if (port > 0) { try { using var list = JsonDocument.Parse(await http.GetStringAsync(new Uri($"http://127.0.0.1:{port}/json/list"))); debugger = list.RootElement.EnumerateArray() .Where(t => t.GetProperty("type").GetString() == "page") .Select(t => t.GetProperty("webSocketDebuggerUrl").GetString()) .FirstOrDefault(); } catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or JsonException) { // Chromium is still starting. } } if (debugger is null) { await Task.Delay(100); } } var socket = new ClientWebSocket(); socket.Options.Proxy = null; using (var connect = new CancellationTokenSource(Patience)) { await socket.ConnectAsync(new Uri(debugger), connect.Token); } var browser = new UiBrowser(process, stderr, socket, profile); await browser.SendAsync("Runtime.enable"); await browser.SendAsync("Page.enable"); await browser.SendAsync("Log.enable"); return browser; } catch { Kill(process); RealBrowser.TryDelete(profile); throw; } } /// One command of the DevTools protocol; its result (an error of the protocol fails the test). public async Task SendAsync(string method, JsonObject? parameters = null) { var id = Interlocked.Increment(ref _id); var answer = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); _pending[id] = answer; var message = new JsonObject { ["id"] = id, ["method"] = method, ["params"] = parameters ?? new JsonObject() }; await _send.WaitAsync(); try { await _socket.SendAsync(Encoding.UTF8.GetBytes(message.ToJsonString()), WebSocketMessageType.Text, endOfMessage: true, CancellationToken.None); } finally { _send.Release(); } // A browser that dies fails the answer at once (ReadLoopAsync); a slow one is waited for. try { return await answer.Task.WaitAsync(Patience); } catch (TimeoutException) { _pending.TryRemove(id, out _); throw new TimeoutException( $"Chromium non ha risposto a {method} in {Patience.TotalSeconds:0} s{(_process.HasExited ? " (si è chiuso)" : string.Empty)}. {Tail(_stderr)}"); } } /// Runs a script in the page (promises awaited) and returns its value; an exception fails the test. public async Task EvalAsync(string expression) { var result = await SendAsync("Runtime.evaluate", new JsonObject { ["expression"] = expression, ["awaitPromise"] = true, ["returnByValue"] = true, }); if (result.TryGetProperty("exceptionDetails", out var details)) { var text = details.TryGetProperty("exception", out var ex) && ex.TryGetProperty("description", out var d) ? d.GetString() : details.GetProperty("text").GetString(); throw new AssertFailedException($"Errore nella pagina: {text}\n{Report()}"); } return result.GetProperty("result").TryGetProperty("value", out var value) ? value.Clone() : default; } public async Task EvalAsync(string expression) => (await EvalAsync(expression)).Deserialize(WebTestServer.Json)!; /// /// Polls until a condition of the page holds (an expression, or a promise of one; errors while the page changes /// count as «not yet»). /// public async Task WaitAsync(string condition, string what, TimeSpan? limit = null) { var deadline = DateTime.UtcNow + (limit ?? Patience); string? last = null; while (DateTime.UtcNow < deadline) { try { if ((await EvalAsync($"(async () => Boolean(await ({condition})))()")).ValueKind == JsonValueKind.True) { return; } } catch (AssertFailedException ex) { last = ex.Message; } await Task.Delay(50); } Assert.Fail($"timeout: {what}{(last is null ? string.Empty : "\n" + last)}\n{Report()}"); } /// Polls a condition of the test (the server side) while the page works. public async Task WaitForAsync(Func condition, string what, TimeSpan? limit = null) { var deadline = DateTime.UtcNow + (limit ?? Patience); while (DateTime.UtcNow < deadline) { if (condition()) { return; } await Task.Delay(50); } Assert.Fail($"timeout: {what}\n{Report()}"); } /// A script that runs in every new document before its own scripts. public Task AddInitScriptAsync(string source) => SendAsync("Page.addScriptToEvaluateOnNewDocument", new JsonObject { ["source"] = source }); /// /// Waits until no request of the page is in flight (): every request it started has reached /// the server and been answered, and the page's continuation of each answer has run, a request it started there /// included (that one starts before the answer it follows is over). What the page leaves for later is not waited /// for: a request started by an observer, an animation frame, a timer, a message of the event stream or a module /// still loading may come after (the mosaic asks for its rows from an observer, once it has drawn its days). The /// moment to check that a command the page would send as it is left, or in the continuation of an answer, was not /// sent, instead of a pause a slow machine may not wait out; for one started later, wait for that request itself. /// public Task WaitForQuietAsync(string what) => WaitAsync("window.__busy() === 0", what); /// The requests the page started so far () whose «METHOD path» contains the text. public Task AskedAsync(string match) => EvalAsync($"window.__asked.filter((r) => r.includes({JsonSerializer.Serialize(match)}))"); /// Loads an address of the interface and waits until the frame and the first page are drawn. public async Task OpenAsync(Uri address) { // A navigation that fails says so at once, instead of a wait for a page that never comes. var navigation = await SendAsync("Page.navigate", new JsonObject { ["url"] = address.AbsoluteUri }); if (navigation.TryGetProperty("errorText", out var error) && error.GetString() is { Length: > 0 } text) { Assert.Fail($"apertura di {address}: {text}\n{Report()}"); } await WaitAsync( $"location.href.startsWith({JsonSerializer.Serialize(address.GetLeftPart(UriPartial.Authority))}) && document.readyState === 'complete' && !document.documentElement.hasAttribute('aria-busy') && document.querySelector('main.pagina .corpo') !== null", $"apertura di {address}"); } /// Goes to an internal address the way a link of the interface does (unsaved-changes guard included). public Task NavigateAsync(string path) => EvalAsync($"import('/js/core/shell.js').then((m) => {{ m.navigate({JsonSerializer.Serialize(path)}); return true; }})"); /// Centre of the first element matching the selector, in viewport pixels (scrolled into view first). public async Task<(double X, double Y, double Width, double Height)> BoxAsync(string selector) { var box = await EvalAsync($$""" (() => { const el = document.querySelector({{JsonSerializer.Serialize(selector)}}); if (!el) return null; el.scrollIntoView({ block: 'center', inline: 'center' }); const r = el.getBoundingClientRect(); return { x: r.left + r.width / 2, y: r.top + r.height / 2, width: r.width, height: r.height }; })() """); Assert.AreEqual(JsonValueKind.Object, box.ValueKind, $"elemento non trovato: {selector}"); return (box.GetProperty("x").GetDouble(), box.GetProperty("y").GetDouble(), box.GetProperty("width").GetDouble(), box.GetProperty("height").GetDouble()); } /// A real mouse event (Input.dispatchMouseEvent): «mousePressed», «mouseMoved», «mouseReleased». public Task MouseAsync(string type, double x, double y, int buttons = 0) => SendAsync("Input.dispatchMouseEvent", new JsonObject { ["type"] = type, ["x"] = x, ["y"] = y, ["button"] = type == "mouseMoved" && buttons == 0 ? "none" : "left", ["buttons"] = buttons, ["clickCount"] = type == "mouseMoved" ? 0 : 1, }); /// What went wrong in the pages so far, for failure messages. public string Report() => Problems.IsEmpty ? string.Empty : "Pagina: " + string.Join(" | ", Problems); public async ValueTask DisposeAsync() { await _stop.CancelAsync(); try { using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(2)); await _socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "fine", timeout.Token); } catch (Exception ex) when (ex is WebSocketException or OperationCanceledException or ObjectDisposedException) { } Kill(_process); try { await _reader.WaitAsync(TimeSpan.FromSeconds(5)); } catch (Exception ex) when (ex is TimeoutException or WebSocketException or OperationCanceledException) { } _socket.Dispose(); _process.Dispose(); _stop.Dispose(); _send.Dispose(); RealBrowser.TryDelete(_profile); } /// The port of «DevTools listening on ws://127.0.0.1:<port>/devtools/browser/…», or 0. private static int ListeningPort(string line) { const string Marker = "DevTools listening on ws://127.0.0.1:"; var at = line.IndexOf(Marker, StringComparison.Ordinal); if (at < 0) { return 0; } var rest = line[(at + Marker.Length)..]; var end = rest.IndexOf('/', StringComparison.Ordinal); return int.TryParse(end < 0 ? rest : rest[..end], out var port) ? port : 0; } /// The port Chromium wrote in DevToolsActivePort (first line), or 0 while it has not. private static int ReadActivePort(string profile) { try { var lines = File.ReadAllLines(Path.Combine(profile, "DevToolsActivePort")); return lines.Length > 0 && int.TryParse(lines[0], out var port) ? port : 0; } catch (IOException) { return 0; } catch (UnauthorizedAccessException) { return 0; } } /// The last lines Chromium wrote on stderr, for failure messages. private static string Tail(ConcurrentQueue stderr) => stderr.IsEmpty ? "Chromium non ha scritto nulla su stderr." : "Ultime righe di Chromium: " + string.Join(" | ", stderr); private static void Kill(Process process) { try { if (!process.HasExited) { process.Kill(entireProcessTree: true); process.WaitForExit(5000); } } catch (Exception ex) when (ex is InvalidOperationException or System.ComponentModel.Win32Exception) { } } private async Task ReadLoopAsync() { var buffer = new byte[64 * 1024]; using var message = new MemoryStream(); try { while (!_stop.IsCancellationRequested && _socket.State == WebSocketState.Open) { message.SetLength(0); WebSocketReceiveResult result; do { result = await _socket.ReceiveAsync(buffer, _stop.Token); if (result.MessageType == WebSocketMessageType.Close) { return; } message.Write(buffer, 0, result.Count); } while (!result.EndOfMessage); Dispatch(message.ToArray()); } } catch (Exception ex) when (ex is WebSocketException or OperationCanceledException or ObjectDisposedException) { } finally { foreach (var pending in _pending.Values) { pending.TrySetException(new InvalidOperationException("Chromium si è chiuso.")); } } } private void Dispatch(byte[] data) { using var document = JsonDocument.Parse(data); var root = document.RootElement; if (root.TryGetProperty("id", out var idElement) && _pending.TryRemove(idElement.GetInt32(), out var answer)) { if (root.TryGetProperty("error", out var error)) { answer.TrySetException(new InvalidOperationException("DevTools: " + error.GetRawText())); } else { answer.TrySetResult(root.GetProperty("result").Clone()); } return; } if (!root.TryGetProperty("method", out var method)) { return; } var parameters = root.GetProperty("params"); switch (method.GetString()) { case "Runtime.exceptionThrown": var details = parameters.GetProperty("exceptionDetails"); Problems.Enqueue("eccezione: " + (details.TryGetProperty("exception", out var ex) && ex.TryGetProperty("description", out var d) ? d.GetString() : details.GetProperty("text").GetString())); break; case "Runtime.consoleAPICalled" when parameters.GetProperty("type").GetString() == "error": Problems.Enqueue("console: " + string.Join(' ', parameters.GetProperty("args").EnumerateArray().Select(a => a.TryGetProperty("value", out var v) ? v.ToString() : a.TryGetProperty("description", out var s) ? s.GetString() : "?"))); break; } } }