WebView2CdpSession.Attach avvisa chi ascolta Reconnected (cattura delle risposte, vista remota) dentro l'avvio del nuovo WebView, sul thread dell'interfaccia: un'eccezione di uno di loro usciva da Attach e trasformava un avvio riuscito in un avvio fallito, da riprovare, con lo stesso esito ogni volta. Ora ogni gestore è chiamato da solo: il suo errore va nel registro (tipo e prima riga) e gli altri lo ricevono comunque. L'avviso resta sincrono, come prima. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
373 lines
14 KiB
C#
373 lines
14 KiB
C#
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Threading.Channels;
|
|
using Febe.Browser.Cdp;
|
|
using Febe.Browser.Diagnostics;
|
|
using Febe.Core.Abstractions;
|
|
|
|
namespace Febe.Browser.WebView2;
|
|
|
|
/// <summary>
|
|
/// The two WebView2 calls Febe needs for the DevTools protocol (spec §6.1, Windows): <c>CallDevToolsProtocolMethodAsync</c>
|
|
/// and <c>GetDevToolsProtocolEventReceiver</c>, never the deprecated <c>DevToolsProtocolExtension</c> package. The desktop
|
|
/// implements it on <c>CoreWebView2</c>, on the UI thread; tests use a fake. Everything else — the allowlist, the
|
|
/// read-only guard, JSON, event dispatch, logging — is <see cref="WebView2CdpSession"/>, testable without Windows.
|
|
/// </summary>
|
|
public interface IWebView2DevTools
|
|
{
|
|
/// <summary>
|
|
/// <c>CoreWebView2.CallDevToolsProtocolMethodAsync(methodName, parametersAsJson)</c>: the result object as JSON. A
|
|
/// protocol error faults the task; its message may carry the error object (<c>{"code":…,"message":…}</c>). When the
|
|
/// WebView is gone the task faults with <see cref="CdpDisconnectedException"/>.
|
|
/// </summary>
|
|
Task<string> CallMethodAsync(string methodName, string parametersAsJson);
|
|
|
|
/// <summary>
|
|
/// <c>GetDevToolsProtocolEventReceiver(eventName).DevToolsProtocolEventReceived</c>: <paramref name="onEvent"/> gets
|
|
/// <c>ParameterObjectAsJson</c>. Disposing removes the handler.
|
|
/// </summary>
|
|
IDisposable Subscribe(string eventName, Action<string> onEvent);
|
|
}
|
|
|
|
/// <summary>Options of <see cref="WebView2CdpSession"/>.</summary>
|
|
/// <param name="CommandTimeout">How long to wait for the answer to a command before giving up (60 s by default).</param>
|
|
public sealed record WebView2CdpOptions(TimeSpan? CommandTimeout = null)
|
|
{
|
|
internal TimeSpan EffectiveTimeout => CommandTimeout ?? TimeSpan.FromSeconds(60);
|
|
}
|
|
|
|
/// <summary>
|
|
/// The <see cref="ICdpSession"/> of WebView2 (spec §5, §6.1): the same rules as <see cref="CdpClient"/> over the two
|
|
/// WebView2 calls of <see cref="IWebView2DevTools"/>.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <list type="bullet">
|
|
/// <item>Only commands of <see cref="CdpCommandPolicy"/> are sent; <c>Runtime.evaluate</c> also passes
|
|
/// <see cref="ReadOnlyScriptGuard"/>. A refused command never reaches WebView2.</item>
|
|
/// <item>The log receives command and event names only: never parameters, results, event payloads or the text of
|
|
/// WebView2's exceptions (a protocol error keeps only its code and message, like <see cref="CdpClient"/>).</item>
|
|
/// <item>Events arrive on WebView2's UI thread; they are queued and handed to the handlers in order on one background
|
|
/// loop, so a slow handler never blocks the window and a handler may send commands without deadlocking it.</item>
|
|
/// <item>Like <see cref="ReconnectingCdpSession"/>: subscriptions survive a new WebView (<see cref="Attach"/> after the
|
|
/// browser process restarted), and commands fail fast with <see cref="BrowserUnavailableException"/> while detached.</item>
|
|
/// </list>
|
|
/// </remarks>
|
|
public sealed class WebView2CdpSession : ICdpSession, ICdpConnectionEvents, IAsyncDisposable
|
|
{
|
|
private static readonly JsonSerializerOptions ParameterOptions = new(JsonSerializerDefaults.Web)
|
|
{
|
|
DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull,
|
|
};
|
|
|
|
private readonly IBrowserLog _log;
|
|
private readonly WebView2CdpOptions _options;
|
|
private readonly Lock _gate = new();
|
|
private readonly Dictionary<string, List<Action<JsonElement>>> _handlers = new(StringComparer.Ordinal);
|
|
private readonly Dictionary<string, IDisposable> _native = new(StringComparer.Ordinal);
|
|
private readonly Channel<QueuedEvent> _events = Channel.CreateUnbounded<QueuedEvent>(new UnboundedChannelOptions { SingleReader = true });
|
|
private readonly Task _dispatch;
|
|
private IWebView2DevTools? _devTools;
|
|
private bool _everAttached;
|
|
private int _disposed;
|
|
|
|
public WebView2CdpSession(IBrowserLog? log = null, WebView2CdpOptions? options = null)
|
|
{
|
|
_log = log ?? NullBrowserLog.Instance;
|
|
_options = options ?? new WebView2CdpOptions();
|
|
_dispatch = Task.Run(DispatchLoopAsync);
|
|
}
|
|
|
|
/// <summary>Raised after <see cref="Attach"/> replaced an earlier WebView (not for the first one).</summary>
|
|
public event EventHandler? Reconnected;
|
|
|
|
/// <summary>True while a WebView is attached.</summary>
|
|
public bool IsAttached
|
|
{
|
|
get
|
|
{
|
|
lock (_gate)
|
|
{
|
|
return _devTools is not null;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>Uses <paramref name="devTools"/> from now on and subscribes it to every event that has handlers.</summary>
|
|
public void Attach(IWebView2DevTools devTools)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(devTools);
|
|
bool reconnect;
|
|
lock (_gate)
|
|
{
|
|
DetachLocked();
|
|
_devTools = devTools;
|
|
foreach (var name in _handlers.Keys)
|
|
{
|
|
_native[name] = SubscribeNative(devTools, name);
|
|
}
|
|
|
|
reconnect = _everAttached;
|
|
_everAttached = true;
|
|
}
|
|
|
|
_log.Write(BrowserLogLevel.Debug, "CDP: WebView2 collegato.");
|
|
if (reconnect)
|
|
{
|
|
RaiseReconnected();
|
|
}
|
|
}
|
|
|
|
/// <summary>Stops using the current WebView (it is closing or gone); commands fail until the next <see cref="Attach"/>.</summary>
|
|
public void Detach()
|
|
{
|
|
lock (_gate)
|
|
{
|
|
DetachLocked();
|
|
}
|
|
}
|
|
|
|
public async Task<JsonElement> SendAsync(string method, object? parameters = null, CancellationToken ct = default)
|
|
{
|
|
ArgumentException.ThrowIfNullOrEmpty(method);
|
|
CdpCommandPolicy.EnsureAllowed(method);
|
|
var node = CdpParameters.ToNode(parameters, ParameterOptions);
|
|
if (method == "Runtime.evaluate")
|
|
{
|
|
ReadOnlyScriptGuard.EnsureReadOnly(CdpParameters.GetString(node, "expression"));
|
|
}
|
|
|
|
IWebView2DevTools devTools;
|
|
lock (_gate)
|
|
{
|
|
ObjectDisposedException.ThrowIf(_disposed == 1, this);
|
|
devTools = _devTools ?? throw new BrowserUnavailableException();
|
|
}
|
|
|
|
var json = node?.ToJsonString() ?? "{}";
|
|
_log.Write(BrowserLogLevel.Debug, $"CDP → {method}");
|
|
string result;
|
|
try
|
|
{
|
|
result = await devTools.CallMethodAsync(method, json).WaitAsync(_options.EffectiveTimeout, ct).ConfigureAwait(false);
|
|
}
|
|
catch (TimeoutException)
|
|
{
|
|
throw new TimeoutException($"Il browser non ha risposto al comando «{method}» entro {_options.EffectiveTimeout.TotalSeconds:0} s.");
|
|
}
|
|
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or OperationCanceledException)
|
|
{
|
|
throw;
|
|
}
|
|
catch (Exception ex) when (ex is not OutOfMemoryException)
|
|
{
|
|
var error = ProtocolError(method, ex);
|
|
_log.Write(BrowserLogLevel.Debug, $"CDP ✗ {method} (codice {error.Code})");
|
|
throw error;
|
|
}
|
|
|
|
return Parse(result);
|
|
}
|
|
|
|
public IDisposable On(string eventName, Action<JsonElement> handler)
|
|
{
|
|
ArgumentException.ThrowIfNullOrEmpty(eventName);
|
|
ArgumentNullException.ThrowIfNull(handler);
|
|
lock (_gate)
|
|
{
|
|
if (!_handlers.TryGetValue(eventName, out var list))
|
|
{
|
|
list = [];
|
|
_handlers[eventName] = list;
|
|
if (_devTools is { } devTools)
|
|
{
|
|
_native[eventName] = SubscribeNative(devTools, eventName);
|
|
}
|
|
}
|
|
|
|
list.Add(handler);
|
|
}
|
|
|
|
return new Subscription(() =>
|
|
{
|
|
lock (_gate)
|
|
{
|
|
if (_handlers.TryGetValue(eventName, out var list) && list.Remove(handler) && list.Count == 0)
|
|
{
|
|
_handlers.Remove(eventName);
|
|
if (_native.Remove(eventName, out var native))
|
|
{
|
|
native.Dispose();
|
|
}
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
/// <summary>Waits until every event received so far was handed to its handlers (tests).</summary>
|
|
public Task DrainAsync()
|
|
{
|
|
var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
if (!_events.Writer.TryWrite(new QueuedEvent(string.Empty, string.Empty, done)))
|
|
{
|
|
done.TrySetResult();
|
|
}
|
|
|
|
return done.Task;
|
|
}
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
if (Interlocked.Exchange(ref _disposed, 1) == 1)
|
|
{
|
|
return;
|
|
}
|
|
|
|
lock (_gate)
|
|
{
|
|
DetachLocked();
|
|
}
|
|
|
|
_events.Writer.TryComplete();
|
|
await _dispatch.ConfigureAwait(false);
|
|
}
|
|
|
|
/// <summary>
|
|
/// The protocol error of a failed WebView2 call. WebView2 puts the error object in the exception's message; only its
|
|
/// code and message are kept (never the text around it nor its <c>data</c>, which can echo parameters).
|
|
/// </summary>
|
|
internal static CdpCommandException ProtocolError(string method, Exception ex)
|
|
{
|
|
var bytes = Encoding.UTF8.GetBytes(ex.Message ?? string.Empty);
|
|
CdpCommandException? found = null;
|
|
|
|
// The last object with a numeric code and a string message: text and other JSON around it are ignored.
|
|
for (var i = Array.IndexOf(bytes, (byte)'{'); i >= 0; i = Array.IndexOf(bytes, (byte)'{', i + 1))
|
|
{
|
|
try
|
|
{
|
|
var reader = new Utf8JsonReader(bytes.AsSpan(i));
|
|
using var document = JsonDocument.ParseValue(ref reader);
|
|
var root = document.RootElement;
|
|
if (root.ValueKind == JsonValueKind.Object
|
|
&& root.TryGetProperty("message", out var m) && m.ValueKind == JsonValueKind.String
|
|
&& root.TryGetProperty("code", out var c) && c.TryGetInt32(out var code))
|
|
{
|
|
found = new CdpCommandException(method, code, m.GetString() ?? string.Empty);
|
|
}
|
|
}
|
|
catch (JsonException)
|
|
{
|
|
}
|
|
}
|
|
|
|
return found ?? new CdpCommandException(method, ex.HResult, "errore di WebView2");
|
|
}
|
|
|
|
private static JsonElement Parse(string? json)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(json))
|
|
{
|
|
return default;
|
|
}
|
|
|
|
// ParseValue yields a self-contained element and needs no serializer (trimmed and single-file builds).
|
|
var reader = new Utf8JsonReader(Encoding.UTF8.GetBytes(json));
|
|
return JsonElement.ParseValue(ref reader);
|
|
}
|
|
|
|
/// <summary>
|
|
/// <see cref="Reconnected"/>, on the thread of <see cref="Attach"/> (WebView2's UI thread), one handler at a time: an
|
|
/// error of a handler is logged and never reaches <see cref="Attach"/>, so it cannot undo the start of the new
|
|
/// WebView that called it. Handlers only queue their work (re-enabling a domain is a command, never sent from here).
|
|
/// </summary>
|
|
private void RaiseReconnected()
|
|
{
|
|
if (Reconnected is not { } handlers)
|
|
{
|
|
return;
|
|
}
|
|
|
|
foreach (var handler in handlers.GetInvocationList().Cast<EventHandler>())
|
|
{
|
|
try
|
|
{
|
|
handler(this, EventArgs.Empty);
|
|
}
|
|
catch (Exception ex) when (ex is not OutOfMemoryException)
|
|
{
|
|
_log.Write(BrowserLogLevel.Warning, "CDP: errore in chi ascolta il nuovo collegamento con WebView2.", ex);
|
|
}
|
|
}
|
|
}
|
|
|
|
private IDisposable SubscribeNative(IWebView2DevTools devTools, string eventName) =>
|
|
devTools.Subscribe(eventName, json => _events.Writer.TryWrite(new QueuedEvent(eventName, json ?? string.Empty, null)));
|
|
|
|
private void DetachLocked()
|
|
{
|
|
foreach (var native in _native.Values)
|
|
{
|
|
try
|
|
{
|
|
native.Dispose();
|
|
}
|
|
catch (Exception ex) when (ex is InvalidOperationException or ObjectDisposedException or CdpDisconnectedException)
|
|
{
|
|
// The WebView is already gone: its handlers went with it.
|
|
}
|
|
}
|
|
|
|
_native.Clear();
|
|
_devTools = null;
|
|
}
|
|
|
|
private async Task DispatchLoopAsync()
|
|
{
|
|
await foreach (var (name, json, drained) in _events.Reader.ReadAllAsync().ConfigureAwait(false))
|
|
{
|
|
if (drained is not null)
|
|
{
|
|
drained.TrySetResult();
|
|
continue;
|
|
}
|
|
|
|
Action<JsonElement>[] handlers;
|
|
lock (_gate)
|
|
{
|
|
if (!_handlers.TryGetValue(name, out var list) || list.Count == 0)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
handlers = [.. list];
|
|
}
|
|
|
|
JsonElement parameters;
|
|
try
|
|
{
|
|
parameters = Parse(json);
|
|
}
|
|
catch (JsonException ex)
|
|
{
|
|
_log.Write(BrowserLogLevel.Warning, $"CDP: evento {name} non leggibile.", ex);
|
|
continue;
|
|
}
|
|
|
|
foreach (var handler in handlers)
|
|
{
|
|
try
|
|
{
|
|
handler(parameters);
|
|
}
|
|
catch (Exception ex) when (ex is not OutOfMemoryException)
|
|
{
|
|
_log.Write(BrowserLogLevel.Warning, $"CDP: errore nel gestore dell'evento {name}.", ex);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>An event waiting for its handlers, or (with <paramref name="Drained"/>) the mark of <see cref="DrainAsync"/>.</summary>
|
|
private readonly record struct QueuedEvent(string Name, string Json, TaskCompletionSource? Drained);
|
|
}
|