Il limite di 30 s all'arresto copriva solo un «Scollega» in corso (rilievo R3 della revisione). FebeApp aspetta RunAsync prima di chiudere il browser, e RunAsync e il ciclo di ripartenza aspettavano WebView2 senza limite: con un WebView2 che non risponde, «Esci» restava fermo. Ora WebView2Host.StartAsync onora il suo token. Chi chiama smette subito di aspettare, un avvio non ancora cominciato non comincia più, uno in corso finisce da sé e chiude ciò che ha creato se l'arresto è già passato. Il ciclo di ripartenza usa lo stesso avvio, e WebView2Browser.DisposeAsync lo aspetta al più 30 s. «Scollega», una volta cominciato, va invece fino in fondo: il profilo con la sessione deve sparire e il motore deve ripartire. Nuova prova: con il thread dell'interfaccia occupato, RunAsync torna subito alla cancellazione e dopo l'uscita non si apre nessuna finestra. Rossa prima della correzione (ancora in attesa dopo 10 s), verde dopo. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
316 lines
12 KiB
C#
316 lines
12 KiB
C#
using System.Globalization;
|
||
using System.Windows.Media;
|
||
using System.Windows.Threading;
|
||
using Febe.App;
|
||
using Febe.Browser.Cdp;
|
||
using Febe.Browser.Hosting;
|
||
using Febe.Core.Abstractions;
|
||
using Febe.Desktop.Core;
|
||
|
||
namespace Febe.Desktop.Browser;
|
||
|
||
/// <summary>
|
||
/// The browser of Instagram on Windows as the shared composition sees it (<see cref="IFebeBrowser"/>): a
|
||
/// <see cref="WebView2Host"/> started with retries like <see cref="ChromiumBrowser"/> starts Chromium, started again
|
||
/// (with the same retries) when its browser process goes away, and emptied by «Scollega» (spec §4.1) once WebView2 has
|
||
/// closed.
|
||
/// </summary>
|
||
/// <remarks>
|
||
/// Only a failed start is retried: what follows a start that worked (the log line, the state) is outside the retries,
|
||
/// and reads only plain values of the host, never WebView2 objects — this class runs on the threads of the composition,
|
||
/// while every WebView2 object lives on the UI thread (the error of 14 October 2026: the version of WebView2 read here,
|
||
/// on a thread-pool thread, threw after every successful start, and the start was undone and retried for ever).
|
||
/// </remarks>
|
||
internal sealed class WebView2Browser : IFebeBrowser
|
||
{
|
||
private static readonly TimeSpan[] Retry = [TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(5)];
|
||
|
||
/// <summary>How long stopping waits for the restart loop to end before closing WebView2 anyway.</summary>
|
||
private static readonly TimeSpan StopWait = TimeSpan.FromSeconds(30);
|
||
|
||
private readonly WebView2BrowserSettings _settings;
|
||
private readonly FebePlatformContext _context;
|
||
private readonly IClock _wallClock;
|
||
private readonly BrowserOptions _options;
|
||
private readonly CancellationTokenSource _lifetime = new();
|
||
private readonly Lock _gate = new();
|
||
private Task? _restartLoop;
|
||
private bool _restartWanted;
|
||
private Exception? _restartFailure;
|
||
private volatile bool _started;
|
||
private volatile string? _lastError;
|
||
|
||
public WebView2Browser(Dispatcher ui, WebView2BrowserSettings settings, FebePlatformContext context, ImageSource? icon)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(ui);
|
||
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
|
||
_context = context ?? throw new ArgumentNullException(nameof(context));
|
||
|
||
// Starts and retries in wall-clock time, whatever clock the engine runs on.
|
||
_wallClock = new SystemClock(context.Clock.LocalZone);
|
||
ProfileDirectory = Path.GetFullPath(settings.ProfileDirectory);
|
||
_options = new BrowserOptions(ProfileDirectory, settings.Width, settings.Height);
|
||
Host = new WebView2Host(
|
||
ui,
|
||
new WebView2HostOptions(settings.Hosting, settings.AdditionalBrowserArguments, icon, () => context.Tracker.MarkUsed(context.Clock.Now)),
|
||
context.Log);
|
||
Host.BrowserProcessFailed += (_, _) => RequestRestart(null);
|
||
}
|
||
|
||
/// <summary>The host: window «Browser di Febe», WebView2, CDP.</summary>
|
||
public WebView2Host Host { get; }
|
||
|
||
public ICdpSession Cdp => Host.Cdp;
|
||
|
||
public UserDrivingGate UserDriving => Host.UserDriving;
|
||
|
||
public bool UserIsDriving => Host.UserIsDriving;
|
||
|
||
public bool IsAvailable => _started && Host.IsAttached;
|
||
|
||
public string? LastError => _lastError;
|
||
|
||
public string ProfileDirectory { get; }
|
||
|
||
public int WindowWidth => _settings.Width;
|
||
|
||
public int WindowHeight => _settings.Height;
|
||
|
||
public async Task RunAsync(CancellationToken ct)
|
||
{
|
||
using var stop = CancellationTokenSource.CreateLinkedTokenSource(ct, _lifetime.Token);
|
||
if (await StartWithRetriesAsync(token => Host.StartAsync(_options, token), stop.Token).ConfigureAwait(false))
|
||
{
|
||
_context.Log.Info("browser", ReadyMessage("Browser di Febe pronto"));
|
||
}
|
||
}
|
||
|
||
public Task<NavigationResult> RestAsync(CancellationToken ct) => Host.Cdp.RestAsync(ct);
|
||
|
||
public Task ShowToUserAsync(CancellationToken ct) => Host.ShowToUserAsync();
|
||
|
||
public Task HideFromUserAsync(CancellationToken ct) => Host.HideFromUserAsync();
|
||
|
||
/// <summary>
|
||
/// «Scollega»: WebView2 closes and its process exits, <c>Dati\browser</c> is deleted, the browser starts empty. When
|
||
/// the profile cannot be deleted completely an <see cref="IOException"/> says so (the browser starts again anyway);
|
||
/// when WebView2 does not start again, the same retries as at start-up bring it back in the background, and
|
||
/// «Scollega» has still done its part (the connection service starts the engine again either way).
|
||
/// </summary>
|
||
public async Task RestartWithEmptyProfileAsync(CancellationToken ct)
|
||
{
|
||
Exception? deletion = null;
|
||
async Task DeleteProfileQuietlyAsync()
|
||
{
|
||
try
|
||
{
|
||
await DeleteProfileAsync().ConfigureAwait(true);
|
||
}
|
||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||
{
|
||
deletion = ex;
|
||
}
|
||
}
|
||
|
||
var restarted = false;
|
||
try
|
||
{
|
||
await Host.RestartAsync(DeleteProfileQuietlyAsync, ct).ConfigureAwait(false);
|
||
MarkStarted();
|
||
restarted = true;
|
||
}
|
||
catch (Exception ex) when (ex is not (OutOfMemoryException or ObjectDisposedException))
|
||
{
|
||
// The start that follows the deletion failed: never a dead browser after «Scollega».
|
||
RequestRestart(ex);
|
||
}
|
||
|
||
if (deletion is not null)
|
||
{
|
||
throw new IOException($"La cartella del browser ({ProfileDirectory}) non si è potuta cancellare del tutto: esci da Febe e cancellala tu, contiene la sessione di Instagram.", deletion);
|
||
}
|
||
|
||
_context.Log.Info("browser", restarted
|
||
? "Profilo del browser cancellato; il browser è ripartito vuoto."
|
||
: "Profilo del browser cancellato; il browser ripartirà vuoto.");
|
||
}
|
||
|
||
/// <summary>
|
||
/// Stops the retries, waits for the restart loop to notice (it stops waiting for WebView2 as soon as
|
||
/// <c>_lifetime</c> is cancelled; at most <see cref="StopWait"/> in any case), then closes WebView2 and its window.
|
||
/// <c>_lifetime</c> stays undisposed on purpose: a late caller may still read its (cancelled) token.
|
||
/// </summary>
|
||
public async ValueTask DisposeAsync()
|
||
{
|
||
await _lifetime.CancelAsync().ConfigureAwait(false);
|
||
Task? restarting;
|
||
lock (_gate)
|
||
{
|
||
restarting = _restartLoop;
|
||
}
|
||
|
||
if (restarting is not null)
|
||
{
|
||
try
|
||
{
|
||
await restarting.WaitAsync(StopWait).ConfigureAwait(false);
|
||
}
|
||
catch (TimeoutException)
|
||
{
|
||
_context.Log.Warn("browser", "WebView2: la ripartenza del browser non si è fermata in tempo; Febe si chiude lo stesso.");
|
||
}
|
||
}
|
||
|
||
await Host.DisposeAsync().ConfigureAwait(false);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Runs <paramref name="start"/> until it works (true) or <paramref name="ct"/> is cancelled (false), waiting
|
||
/// <see cref="Retry"/> between attempts. With <paramref name="failedFirst"/> the first attempt already failed with it.
|
||
/// Only an exception of the start itself is a failed start; this method never throws.
|
||
/// </summary>
|
||
private async Task<bool> StartWithRetriesAsync(Func<CancellationToken, Task> start, CancellationToken ct, Exception? failedFirst = null)
|
||
{
|
||
var attempt = 0;
|
||
if (failedFirst is not null && !await AfterFailedStartAsync(failedFirst, attempt++, ct).ConfigureAwait(false))
|
||
{
|
||
return false;
|
||
}
|
||
|
||
while (!ct.IsCancellationRequested)
|
||
{
|
||
try
|
||
{
|
||
await start(ct).ConfigureAwait(false);
|
||
}
|
||
catch (Exception ex) when (ct.IsCancellationRequested && ex is (OperationCanceledException or ObjectDisposedException))
|
||
{
|
||
return false;
|
||
}
|
||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||
{
|
||
if (!await AfterFailedStartAsync(ex, attempt++, ct).ConfigureAwait(false))
|
||
{
|
||
return false;
|
||
}
|
||
|
||
continue;
|
||
}
|
||
|
||
MarkStarted();
|
||
return true;
|
||
}
|
||
|
||
return false;
|
||
}
|
||
|
||
/// <summary>
|
||
/// A start failed: it is said, and the next attempt waits. False when cancelled. What the failed start created it
|
||
/// closed itself, inside the host: a close from here could catch a browser that «Scollega» started meanwhile.
|
||
/// </summary>
|
||
private async Task<bool> AfterFailedStartAsync(Exception error, int attempt, CancellationToken ct)
|
||
{
|
||
var wait = Retry[Math.Min(attempt, Retry.Length - 1)];
|
||
_lastError = $"WebView2 non parte ({error.GetType().Name}: {FirstLine(error.Message)}).";
|
||
_context.Log.Error("browser", $"{_lastError} Nuovo tentativo fra {wait.TotalSeconds.ToString("0", CultureInfo.InvariantCulture)} s.");
|
||
try
|
||
{
|
||
await _wallClock.Delay(wait, ct).ConfigureAwait(false);
|
||
return true;
|
||
}
|
||
catch (OperationCanceledException)
|
||
{
|
||
return false;
|
||
}
|
||
}
|
||
|
||
private void MarkStarted()
|
||
{
|
||
_started = true;
|
||
_lastError = null;
|
||
}
|
||
|
||
/// <summary>
|
||
/// The browser must start again (its process went away by itself, or the start after «Scollega» failed with
|
||
/// <paramref name="failure"/>): one loop at a time starts it, with the retries of the first start, on the thread
|
||
/// pool — never inside an event handler of WebView2. A request that comes while the loop runs makes it go round
|
||
/// again. The loop only starts what is not running: when another way in (the first start, «Scollega») brought the
|
||
/// browser back first, its attempt finds it running and is done.
|
||
/// </summary>
|
||
private void RequestRestart(Exception? failure)
|
||
{
|
||
lock (_gate)
|
||
{
|
||
if (_lifetime.IsCancellationRequested)
|
||
{
|
||
return;
|
||
}
|
||
|
||
_restartWanted = true;
|
||
_restartFailure ??= failure;
|
||
_restartLoop ??= Task.Run(RestartLoopAsync);
|
||
}
|
||
}
|
||
|
||
private async Task RestartLoopAsync()
|
||
{
|
||
while (true)
|
||
{
|
||
Exception? failure;
|
||
lock (_gate)
|
||
{
|
||
if (!_restartWanted || _lifetime.IsCancellationRequested)
|
||
{
|
||
_restartLoop = null;
|
||
return;
|
||
}
|
||
|
||
_restartWanted = false;
|
||
failure = _restartFailure;
|
||
_restartFailure = null;
|
||
}
|
||
|
||
if (await StartWithRetriesAsync(token => Host.StartAsync(_options, token), _lifetime.Token, failure).ConfigureAwait(false))
|
||
{
|
||
_context.Log.Info("browser", ReadyMessage("Browser di Febe ripartito"));
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>Plain values only (the version was read on the UI thread during the start).</summary>
|
||
private string ReadyMessage(string what) =>
|
||
$"{what}: WebView2 {Host.Version ?? "di versione sconosciuta"}, pagina {WindowWidth.ToString(CultureInfo.InvariantCulture)}×{WindowHeight.ToString(CultureInfo.InvariantCulture)}, {BrowserHostingNames.Name(_settings.Hosting)}, fuori vista.";
|
||
|
||
/// <summary>
|
||
/// Deletes the profile — off the UI thread, it can be large — retrying while a process of WebView2 still holds a
|
||
/// file for a moment.
|
||
/// </summary>
|
||
private async Task DeleteProfileAsync()
|
||
{
|
||
for (var attempt = 0; ; attempt++)
|
||
{
|
||
try
|
||
{
|
||
await Task.Run(() =>
|
||
{
|
||
if (Directory.Exists(ProfileDirectory))
|
||
{
|
||
Directory.Delete(ProfileDirectory, recursive: true);
|
||
}
|
||
}).ConfigureAwait(true);
|
||
return;
|
||
}
|
||
catch (Exception ex) when ((ex is IOException or UnauthorizedAccessException) && attempt < 10)
|
||
{
|
||
await _wallClock.Delay(TimeSpan.FromMilliseconds(500), CancellationToken.None).ConfigureAwait(true);
|
||
}
|
||
}
|
||
}
|
||
|
||
private static string FirstLine(string text)
|
||
{
|
||
var line = text.Split('\n')[0].Trim();
|
||
return line.Length > 200 ? line[..200] : line;
|
||
}
|
||
}
|