Browser di Febe per Windows: ripartenze robuste, WebView2 toccato solo dal suo thread
Dopo la correzione dell'avvio, la revisione di tutto il percorso del browser per Windows ha trovato altri punti della stessa famiglia: lavoro che, se va storto, lascia il browser morto o riprova per sempre. - WebView2Host: avvio, ripartenza, chiusura dopo un avvio fallito e arresto passano uno alla volta (ognuno aspetta WebView2 sul thread dell'interfaccia e prima potevano intrecciarsi); un arresto del processo del browser durante un avvio fa fallire quell'avvio invece di lasciare un WebView morto dato per buono; l'arresto del processo si annuncia solo dopo che il gestore dell'evento di WebView2 è tornato (WebView2 non regge chiusure e ricreazioni dentro i suoi gestori) e solo per il WebView in uso; versione e numero del processo sono valori semplici letti sul thread dell'interfaccia; MoveFocus, Bounds, Indietro e Ricarica non fanno più cadere eccezioni nell'interfaccia se il processo è appena morto; in primo piano il permesso di guida si prende prima di spostare il fuoco. - WebView2Browser: dopo un arresto del processo e dopo un «Scollega» la cui ripartenza fallisce, il browser riparte con gli stessi tentativi del primo avvio (prima: un tentativo solo, poi morto fino al riavvio di Febe; e con «Scollega» anche il motore restava fermo, perché l'errore non era di cartella); un solo ciclo di ripartenza alla volta, sul pool e mai dentro un gestore di WebView2; la cancellazione del profilo non blocca più la finestra. Prove nuove su WebView2 vero: un avvio che fallisce davvero si riprova una volta sola e poi va; la finestra viene in primo piano e torna fuori vista con il permesso di guida, anche chiudendola; «Scollega» cancella profilo e sessione e il browser riparte vuoto; ucciso (per numero di processo) il browser avviato dalla prova, Febe lo fa ripartire da solo; l'ospitalità «composizione» di S2 parte e disegna. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a6623e5736
commit
ccfd8b5c08
4 files changed
+649
-114
No files matched your search
@@ -15,13 +15,14 @@ namespace Febe.Tests.Windows.Support;
|
||||
/// </summary>
|
||||
internal sealed class BrowserBed : IAsyncDisposable
|
||||
{
|
||||
private BrowserBed(TestFolder folder, UiThread ui, LogLines lines, FebeLog log, FebeDatabase database, WebView2Browser browser)
|
||||
private BrowserBed(TestFolder folder, UiThread ui, LogLines lines, FebeLog log, FebeDatabase database, BrowserUseTracker tracker, WebView2Browser browser)
|
||||
{
|
||||
Folder = folder;
|
||||
Ui = ui;
|
||||
Lines = lines;
|
||||
Log = log;
|
||||
Database = database;
|
||||
Tracker = tracker;
|
||||
Browser = browser;
|
||||
}
|
||||
|
||||
@@ -36,6 +37,9 @@ internal sealed class BrowserBed : IAsyncDisposable
|
||||
|
||||
public FebeDatabase Database { get; }
|
||||
|
||||
/// <summary>When Alberto last used the browser («Riprendi» after a verification).</summary>
|
||||
public BrowserUseTracker Tracker { get; }
|
||||
|
||||
public WebView2Browser Browser { get; }
|
||||
|
||||
public static async Task<BrowserBed> CreateAsync(string name, BrowserHosting hosting = BrowserHosting.Window)
|
||||
@@ -48,14 +52,33 @@ internal sealed class BrowserBed : IAsyncDisposable
|
||||
var data = new DataFolderLayout(folder.Combine("dati"));
|
||||
var database = await FebeDatabase.OpenAsync(data.Root);
|
||||
var options = new FebeAppOptions { DataFolder = data.Root, LibraryFolder = folder.Combine("libreria") };
|
||||
var context = new FebePlatformContext(options, data, database, clock, log, new BrowserUseTracker());
|
||||
var tracker = new BrowserUseTracker();
|
||||
var context = new FebePlatformContext(options, data, database, clock, log, tracker);
|
||||
var settings = new WebView2BrowserSettings(data.BrowserProfile, 1280, 900, hosting, BrowserArguments.ForWebView2());
|
||||
|
||||
// Built off the UI thread, as DesktopPlatform.CreateBrowserAsync does after its awaits.
|
||||
var browser = new WebView2Browser(ui.Dispatcher, settings, context, icon: null);
|
||||
return new BrowserBed(folder, ui, lines, log, database, browser);
|
||||
return new BrowserBed(folder, ui, lines, log, database, tracker, browser);
|
||||
}
|
||||
|
||||
/// <summary>Waits (real time) until <paramref name="condition"/> holds; fails with <paramref name="what"/> and the log otherwise.</summary>
|
||||
public async Task WaitUntilAsync(Func<bool> condition, TimeSpan timeout, string what, CancellationToken ct)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + timeout;
|
||||
while (!condition())
|
||||
{
|
||||
if (DateTime.UtcNow > deadline)
|
||||
{
|
||||
Assert.Fail($"Tempo scaduto: {what}.\n{Lines.Text}");
|
||||
}
|
||||
|
||||
await Task.Delay(50, ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads a value of the UI thread (the window, its position) through the dispatcher.</summary>
|
||||
public Task<T> OnUiAsync<T>(Func<T> read) => Ui.InvokeAsync(read);
|
||||
|
||||
/// <summary>
|
||||
/// Starts the browser from a thread-pool thread, like <c>FebeApp.BringUpBrowserAsync</c>, and waits until
|
||||
/// <see cref="WebView2Browser.RunAsync"/> returns. Fails at once when the log reports a failed start: the loop of
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
using System.Diagnostics;
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Browser.Hosting;
|
||||
using Febe.Browser.Recipes;
|
||||
using Febe.Browser.RemoteView;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Desktop.Core;
|
||||
using Febe.SitoDiProva;
|
||||
using Febe.Tests.Windows.Support;
|
||||
|
||||
namespace Febe.Tests.Windows;
|
||||
|
||||
/// <summary>
|
||||
/// The life of the browser of Febe on a real Windows, driven from thread-pool threads as the composition and the
|
||||
/// connection service drive it: a start that really fails is retried (and only that), the window comes on screen and
|
||||
/// goes away with the «driving» lease (the login), «Scollega» empties the profile and the browser comes back, a browser
|
||||
/// process that dies is started again, and the second hosting of S2 (composition) starts and draws.
|
||||
/// </summary>
|
||||
/// <remarks>Two tests bring the window «Browser di Febe» on screen for a moment, as «Accedi a Instagram» does.</remarks>
|
||||
[TestClass]
|
||||
public sealed class WebView2LifecycleTests
|
||||
{
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestInitialize]
|
||||
public void RequireWebView2() => WebView2Runtime.Require();
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(120_000, CooperativeCancellation = true)]
|
||||
public async Task AStartThatReallyFailsIsRetriedAndThenTheBrowserIsReady()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await BrowserBed.CreateAsync("tentativi");
|
||||
|
||||
// A file where the profile folder must go: WebView2 cannot start.
|
||||
var profile = bed.Browser.ProfileDirectory;
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(profile)!);
|
||||
await File.WriteAllTextAsync(profile, "occupa il posto della cartella del profilo", ct);
|
||||
|
||||
var run = Task.Run(() => bed.Browser.RunAsync(ct), ct);
|
||||
await bed.WaitUntilAsync(() => bed.Lines.Any("non parte"), TimeSpan.FromSeconds(30), "il primo avvio non riuscito", ct);
|
||||
Assert.IsFalse(bed.Browser.IsAvailable);
|
||||
StringAssert.StartsWith(bed.Browser.LastError, "WebView2 non parte (IOException:");
|
||||
StringAssert.EndsWith(bed.Lines.Lines.Single(l => l.Contains("non parte", StringComparison.Ordinal)), "Nuovo tentativo fra 5 s.");
|
||||
|
||||
// The obstacle goes away: the next attempt, 5 s later, works.
|
||||
File.Delete(profile);
|
||||
await run.WaitAsync(TimeSpan.FromSeconds(60), ct);
|
||||
|
||||
TestContext.WriteLine(bed.Lines.Text);
|
||||
Assert.IsTrue(bed.Browser.IsAvailable);
|
||||
Assert.IsNull(bed.Browser.LastError);
|
||||
Assert.HasCount(1, bed.Lines.Lines.Where(l => l.Contains("non parte", StringComparison.Ordinal)), "one failed attempt only");
|
||||
Assert.HasCount(1, bed.Lines.Lines.Where(l => l.Contains("Browser di Febe pronto: WebView2 ", StringComparison.Ordinal)));
|
||||
Assert.AreEqual(CdpPageExtensions.RestUrl, await Task.Run(() => bed.Browser.Cdp.GetMainFrameUrlAsync(ct), ct));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(120_000, CooperativeCancellation = true)]
|
||||
public async Task TheWindowComesOnScreenWithTheLeaseAndGoesAwayWithIt()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await BrowserBed.CreateAsync("finestra");
|
||||
await bed.StartAsync(ct);
|
||||
var window = await bed.OnUiAsync(() => bed.Browser.Host.Window) ?? throw new AssertFailedException("nessuna finestra");
|
||||
Assert.IsTrue(await bed.OnUiAsync(() => window.IsVisible), "the window is open");
|
||||
Assert.IsFalse(await bed.OnUiAsync(() => window.IsOnScreen), "after the start it is parked out of view");
|
||||
Assert.IsFalse(bed.Browser.UserIsDriving);
|
||||
|
||||
// «Accedi a Instagram» / «Portalo in primo piano», from the connection service's thread.
|
||||
await Task.Run(() => bed.Browser.ShowToUserAsync(ct), ct);
|
||||
Assert.IsTrue(await bed.OnUiAsync(() => window.IsOnScreen), "the window came on screen");
|
||||
Assert.IsTrue(bed.Browser.UserIsDriving, "while it is in front the engine is still");
|
||||
Assert.IsNotNull(bed.Tracker.LastUsedAt, "using it counts for «Riprendi»");
|
||||
|
||||
// «Ho finito».
|
||||
await Task.Run(() => bed.Browser.HideFromUserAsync(ct), ct);
|
||||
Assert.IsFalse(await bed.OnUiAsync(() => window.IsOnScreen));
|
||||
Assert.IsFalse(bed.Browser.UserIsDriving);
|
||||
|
||||
// Closing the window is «ho finito» too: out of view, still open, still painting.
|
||||
await Task.Run(() => bed.Browser.ShowToUserAsync(ct), ct);
|
||||
Assert.IsTrue(bed.Browser.UserIsDriving);
|
||||
await bed.OnUiAsync(() =>
|
||||
{
|
||||
window.Close();
|
||||
return true;
|
||||
});
|
||||
Assert.IsFalse(bed.Browser.UserIsDriving);
|
||||
Assert.IsTrue(await bed.OnUiAsync(() => window.IsVisible), "closing it never closes it");
|
||||
Assert.IsFalse(await bed.OnUiAsync(() => window.IsOnScreen));
|
||||
var jpeg = await Task.Run(() => PagePreview.CaptureAsync(bed.Browser.Cdp, 50, ct), ct);
|
||||
Assert.AreEqual(0xFF, jpeg[0], "the page still draws out of view");
|
||||
Assert.IsTrue(bed.Browser.IsAvailable);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(180_000, CooperativeCancellation = true)]
|
||||
public async Task ScollegaDeletesTheProfileWithTheSessionAndTheBrowserComesBackEmpty()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var site = await TestSite.StartAsync(new TestSiteOptions(), ct);
|
||||
await using var bed = await BrowserBed.CreateAsync("scollega");
|
||||
await bed.StartAsync(ct);
|
||||
var cdp = bed.Browser.Cdp;
|
||||
var cookie = CollectionSite.TestSite(site.SiteHost, site.CdnHost).SessionCookie;
|
||||
var clock = new SystemClock();
|
||||
|
||||
// «Collegato»: the site's session cookie is in the profile.
|
||||
await Task.Run(
|
||||
async () =>
|
||||
{
|
||||
await cdp.NavigateAsync(site.Url("/"), ct);
|
||||
await cdp.WaitForLoadAsync(clock, TimeSpan.FromSeconds(15), ct);
|
||||
},
|
||||
ct);
|
||||
Assert.IsTrue(await Task.Run(() => SessionCookieProbe.HasSessionCookieAsync(cdp, cookie, ct), ct), "connected to the test site");
|
||||
var marker = Path.Combine(bed.Browser.ProfileDirectory, "segno-della-prova");
|
||||
await File.WriteAllTextAsync(marker, "x", ct);
|
||||
var before = bed.Browser.Host.BrowserProcessId;
|
||||
|
||||
// «Scollega», from the connection service's thread.
|
||||
await Task.Run(() => bed.Browser.RestartWithEmptyProfileAsync(ct), ct);
|
||||
|
||||
TestContext.WriteLine(bed.Lines.Text);
|
||||
Assert.IsFalse(File.Exists(marker), "the profile folder was deleted");
|
||||
Assert.IsTrue(bed.Browser.IsAvailable, "the browser runs again");
|
||||
Assert.AreNotEqual(before, bed.Browser.Host.BrowserProcessId, "with a new browser process");
|
||||
Assert.IsFalse(await Task.Run(() => SessionCookieProbe.HasSessionCookieAsync(cdp, cookie, ct), ct), "the session went with the profile");
|
||||
Assert.AreEqual(CdpPageExtensions.RestUrl, await Task.Run(() => cdp.GetMainFrameUrlAsync(ct), ct));
|
||||
Assert.IsTrue(bed.Lines.Any("Profilo del browser cancellato; il browser è ripartito vuoto."));
|
||||
Assert.IsFalse(bed.Lines.Any("ERRORE"), bed.Lines.Text);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(180_000, CooperativeCancellation = true)]
|
||||
public async Task WhenItsBrowserProcessDiesTheBrowserStartsAgainByItself()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await BrowserBed.CreateAsync("arresto");
|
||||
await bed.StartAsync(ct);
|
||||
var reconnected = 0;
|
||||
bed.Browser.Host.Connection.Reconnected += (_, _) => Interlocked.Increment(ref reconnected);
|
||||
|
||||
// The browser process this test started — by its id, never by name.
|
||||
var pid = bed.Browser.Host.BrowserProcessId;
|
||||
Assert.AreNotEqual(0, pid);
|
||||
using (var process = Process.GetProcessById(pid))
|
||||
{
|
||||
Assert.AreEqual("msedgewebview2", process.ProcessName, "the browser process of WebView2");
|
||||
process.Kill();
|
||||
}
|
||||
|
||||
await bed.WaitUntilAsync(() => bed.Lines.Any("Browser di Febe ripartito: WebView2 "), TimeSpan.FromSeconds(90), "la ripartenza del browser", ct);
|
||||
|
||||
TestContext.WriteLine(bed.Lines.Text);
|
||||
Assert.IsTrue(bed.Lines.Any("WebView2: processo terminato (BrowserProcessExited)."));
|
||||
Assert.IsTrue(bed.Browser.IsAvailable);
|
||||
Assert.AreNotEqual(pid, bed.Browser.Host.BrowserProcessId, "a new browser process");
|
||||
Assert.AreEqual(1, Volatile.Read(ref reconnected), "the subscriptions of the session moved to the new WebView once");
|
||||
Assert.AreEqual(CdpPageExtensions.RestUrl, await Task.Run(() => bed.Browser.Cdp.GetMainFrameUrlAsync(ct), ct));
|
||||
Assert.IsFalse(bed.Lines.Any("non parte"), "the new start worked at once");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(120_000, CooperativeCancellation = true)]
|
||||
public async Task TheCompositionHostingOfS2StartsAndDrawsThePage()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var site = await TestSite.StartAsync(new TestSiteOptions(), ct);
|
||||
await using var bed = await BrowserBed.CreateAsync("composizione", BrowserHosting.Composition);
|
||||
await bed.StartAsync(ct);
|
||||
Assert.IsTrue(bed.Lines.Any(", composizione, fuori vista."), bed.Lines.Text);
|
||||
var cdp = bed.Browser.Cdp;
|
||||
var clock = new SystemClock();
|
||||
|
||||
var seen = await Task.Run(
|
||||
async () =>
|
||||
{
|
||||
await cdp.NavigateAsync(site.Url("/profilo/marta.prova/"), ct);
|
||||
await cdp.WaitForLoadAsync(clock, TimeSpan.FromSeconds(15), ct);
|
||||
return await cdp.EvaluateAsync("({ visibility: document.visibilityState, width: innerWidth, height: innerHeight })", ct);
|
||||
},
|
||||
ct);
|
||||
TestContext.WriteLine("La pagina vede: " + seen.GetRawText());
|
||||
Assert.AreEqual("visible", seen.GetProperty("visibility").GetString());
|
||||
Assert.AreEqual(1280, seen.GetProperty("width").GetInt32());
|
||||
var jpeg = await Task.Run(() => PagePreview.CaptureAsync(cdp, 60, ct), ct);
|
||||
Assert.IsGreaterThan(5_000, jpeg.Length, "a real frame");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user