using System.Buffers; using System.Collections.Concurrent; using System.Net.WebSockets; using System.Text.Json; using System.Text.Json.Nodes; using Febe.Browser.Diagnostics; using Febe.Core.Abstractions; namespace Febe.Browser.Cdp; /// Options of . /// How long to wait for the answer to a command before giving up. public sealed record CdpClientOptions(TimeSpan? CommandTimeout = null) { public static CdpClientOptions Default { get; } = new(); internal TimeSpan EffectiveTimeout => CommandTimeout ?? TimeSpan.FromSeconds(60); } /// /// Chrome DevTools Protocol client over a WebSocket (spec §5, §6.1), written by hand on . /// /// /// /// Only commands of are sent; Runtime.evaluate also passes . /// The log receives command names only: never parameters, results or event payloads. /// Event handlers run on the receive loop: they must be quick and must never wait for a command /// (queue the work instead), or the loop stops. /// When the connection drops every pending command fails with ; /// a new client is needed (see ). Disposal is idempotent. /// /// public sealed class CdpClient : ICdpSession, IAsyncDisposable { private const int ReceiveChunk = 64 * 1024; private const int MaxRetainedBuffer = 4 * 1024 * 1024; private static readonly JsonSerializerOptions ParameterOptions = new(JsonSerializerDefaults.Web) { DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull, }; private readonly WebSocket _socket; private readonly IBrowserLog _log; private readonly CdpClientOptions _options; private readonly ConcurrentDictionary _pending = new(); private readonly Dictionary>> _handlers = new(StringComparer.Ordinal); private readonly Lock _handlersGate = new(); private readonly SemaphoreSlim _sendLock = new(1, 1); private readonly CancellationTokenSource _lifetime = new(); private readonly Task _receiveLoop; private int _nextId; private int _disposed; private int _closed; private Exception? _closeReason; internal CdpClient(WebSocket socket, IBrowserLog? log = null, CdpClientOptions? options = null) { _socket = socket ?? throw new ArgumentNullException(nameof(socket)); _log = log ?? NullBrowserLog.Instance; _options = options ?? CdpClientOptions.Default; _receiveLoop = Task.Run(ReceiveLoopAsync); } /// True until the connection closes or the client is disposed. public bool IsConnected => Volatile.Read(ref _closed) == 0; /// Raised once when the connection closes (the argument is the cause, null for a normal close). public event EventHandler? Disconnected; /// Connects to a DevTools WebSocket on the loopback interface (never through a proxy). public static async Task ConnectAsync(Uri webSocketUrl, IBrowserLog? log = null, CdpClientOptions? options = null, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(webSocketUrl); CdpTargetDiscovery.EnsureLoopback(webSocketUrl); var socket = new ClientWebSocket(); socket.Options.Proxy = null; socket.Options.KeepAliveInterval = TimeSpan.FromSeconds(20); try { using var connectTimeout = CancellationTokenSource.CreateLinkedTokenSource(ct); connectTimeout.CancelAfter(TimeSpan.FromSeconds(10)); await socket.ConnectAsync(webSocketUrl, connectTimeout.Token).ConfigureAwait(false); } catch { socket.Dispose(); throw; } (log ?? NullBrowserLog.Instance).Debug("CDP: collegamento aperto."); return new CdpClient(socket, log, options); } public async Task 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")); } ThrowIfClosed(); var id = Interlocked.Increment(ref _nextId); var pending = new Pending(method, new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)); _pending[id] = pending; try { var payload = Serialize(id, method, node); using (var lockWait = CancellationTokenSource.CreateLinkedTokenSource(ct, _lifetime.Token)) { await _sendLock.WaitAsync(lockWait.Token).ConfigureAwait(false); } try { ThrowIfClosed(); // Never pass the caller's token to the socket: cancelling a send aborts the whole connection. await _socket.SendAsync(payload, WebSocketMessageType.Text, endOfMessage: true, _lifetime.Token).ConfigureAwait(false); } finally { _sendLock.Release(); } _log.Debug($"CDP → {method}"); using var wait = CancellationTokenSource.CreateLinkedTokenSource(ct); wait.CancelAfter(_options.EffectiveTimeout); try { return await pending.Completion.Task.WaitAsync(wait.Token).ConfigureAwait(false); } catch (OperationCanceledException) when (!ct.IsCancellationRequested) { ThrowIfClosed(); throw new TimeoutException($"Il browser non ha risposto al comando «{method}» entro {_options.EffectiveTimeout.TotalSeconds:0} s."); } } catch (Exception ex) when (ex is WebSocketException or ObjectDisposedException || (ex is OperationCanceledException && _lifetime.IsCancellationRequested && !ct.IsCancellationRequested)) { throw new CdpDisconnectedException("Il collegamento con il browser si è chiuso durante il comando.", ex); } finally { _pending.TryRemove(id, out _); } } public IDisposable On(string eventName, Action handler) { ArgumentException.ThrowIfNullOrEmpty(eventName); ArgumentNullException.ThrowIfNull(handler); lock (_handlersGate) { if (!_handlers.TryGetValue(eventName, out var list)) { list = []; _handlers[eventName] = list; } list.Add(handler); } return new Subscription(() => { lock (_handlersGate) { if (_handlers.TryGetValue(eventName, out var list)) { list.Remove(handler); if (list.Count == 0) { _handlers.Remove(eventName); } } } }); } public async ValueTask DisposeAsync() { if (Interlocked.Exchange(ref _disposed, 1) == 1) { return; } if (_socket.State == WebSocketState.Open) { try { using var closeTimeout = new CancellationTokenSource(TimeSpan.FromSeconds(1)); await _socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, null, closeTimeout.Token).ConfigureAwait(false); } catch (Exception ex) when (ex is WebSocketException or OperationCanceledException or ObjectDisposedException) { // The browser may already be gone. } } try { await _receiveLoop.WaitAsync(TimeSpan.FromSeconds(1)).ConfigureAwait(false); } catch (TimeoutException) { // Fall through: cancelling aborts the receive. } await _lifetime.CancelAsync().ConfigureAwait(false); try { await _receiveLoop.ConfigureAwait(false); } catch (Exception ex) when (ex is OperationCanceledException or WebSocketException) { } MarkClosed(null); _socket.Dispose(); // _sendLock and _lifetime are deliberately not disposed: a concurrent SendAsync may still touch them, // and neither holds unmanaged resources (no wait handle, no timer). } private async Task ReceiveLoopAsync() { var buffer = new ArrayBufferWriter(ReceiveChunk); Exception? failure = null; try { while (!_lifetime.IsCancellationRequested) { buffer.ResetWrittenCount(); ValueWebSocketReceiveResult result; do { result = await _socket.ReceiveAsync(buffer.GetMemory(ReceiveChunk), _lifetime.Token).ConfigureAwait(false); if (result.MessageType == WebSocketMessageType.Close) { return; } buffer.Advance(result.Count); } while (!result.EndOfMessage); Dispatch(buffer.WrittenSpan); if (buffer.Capacity > MaxRetainedBuffer) { buffer = new ArrayBufferWriter(ReceiveChunk); } } } catch (OperationCanceledException) when (_lifetime.IsCancellationRequested) { } catch (Exception ex) when (ex is WebSocketException or ObjectDisposedException or InvalidOperationException) { failure = ex; } finally { MarkClosed(failure); } } private void Dispatch(ReadOnlySpan message) { JsonElement root; try { // ParseValue yields a self-contained element (no JsonDocument to dispose) and needs no serializer, // so it also works where reflection-based serialization is disabled (trimmed or AOT builds). var reader = new Utf8JsonReader(message); root = JsonElement.ParseValue(ref reader); } catch (JsonException ex) { _log.Warn("CDP: messaggio non leggibile ricevuto dal browser.", ex); return; } if (root.ValueKind != JsonValueKind.Object) { return; } if (root.TryGetProperty("id", out var idElement) && idElement.TryGetInt32(out var id)) { if (!_pending.TryGetValue(id, out var pending)) { return; } if (root.TryGetProperty("error", out var error)) { var code = error.TryGetProperty("code", out var c) && c.TryGetInt32(out var ci) ? ci : 0; var text = error.TryGetProperty("message", out var m) ? m.GetString() ?? string.Empty : string.Empty; _log.Debug($"CDP ✗ {pending.Method} (codice {code})"); pending.Completion.TrySetException(new CdpCommandException(pending.Method, code, text)); } else { pending.Completion.TrySetResult(root.TryGetProperty("result", out var result) ? result : default); } return; } if (root.TryGetProperty("method", out var methodElement) && methodElement.GetString() is { } eventName) { Action[] handlers; lock (_handlersGate) { if (!_handlers.TryGetValue(eventName, out var list) || list.Count == 0) { return; } handlers = [.. list]; } var parameters = root.TryGetProperty("params", out var p) ? p : default; foreach (var handler in handlers) { try { handler(parameters); } catch (Exception ex) { _log.Warn($"CDP: errore nel gestore dell'evento {eventName}.", ex); } } } } private void MarkClosed(Exception? reason) { if (Interlocked.Exchange(ref _closed, 1) == 1) { return; } _closeReason = reason; var disconnected = new CdpDisconnectedException("Il collegamento con il browser si è chiuso.", reason); foreach (var (_, pending) in _pending) { pending.Completion.TrySetException(disconnected); } if (Volatile.Read(ref _disposed) == 0) { _log.Info("CDP: il browser ha chiuso il collegamento."); } try { Disconnected?.Invoke(this, reason); } catch (Exception ex) { _log.Warn("CDP: errore nel gestore della disconnessione.", ex); } } private void ThrowIfClosed() { if (Volatile.Read(ref _closed) == 1 || Volatile.Read(ref _disposed) == 1) { throw new CdpDisconnectedException("Il collegamento con il browser è chiuso.", _closeReason); } } private static ReadOnlyMemory Serialize(int id, string method, JsonNode? parameters) { var output = new ArrayBufferWriter(256); using (var writer = new Utf8JsonWriter(output)) { writer.WriteStartObject(); writer.WriteNumber("id", id); writer.WriteString("method", method); if (parameters is not null) { writer.WritePropertyName("params"); parameters.WriteTo(writer); } writer.WriteEndObject(); } return output.WrittenMemory; } private sealed record Pending(string Method, TaskCompletionSource Completion); } /// Disposable that runs an action once. internal sealed class Subscription(Action dispose) : IDisposable { private Action? _dispose = dispose; public void Dispose() => Interlocked.Exchange(ref _dispose, null)?.Invoke(); } /// Converts command parameters (anonymous objects, dictionaries, JSON nodes or elements) to JSON. internal static class CdpParameters { public static JsonNode? ToNode(object? parameters, JsonSerializerOptions options) => parameters switch { null => null, JsonNode node => node, JsonElement { ValueKind: JsonValueKind.Undefined or JsonValueKind.Null } => null, JsonElement element => JsonNode.Parse(element.GetRawText()), _ when !JsonSerializer.IsReflectionEnabledByDefault => throw new NotSupportedException( "Senza serializzazione per riflessione i parametri CDP vanno passati come JsonObject."), _ => JsonSerializer.SerializeToNode(parameters, parameters.GetType(), options), }; public static string? GetString(JsonNode? node, string property) => node is JsonObject obj && obj.TryGetPropertyValue(property, out var value) && value is JsonValue v && v.TryGetValue(out var s) ? s : null; }