Skip to content

Commit

Permalink
[dotnet] Make CDP sessions autodetect close of initial attached target
Browse files Browse the repository at this point in the history
Previously, if the initial target to which a CDP session is attached is
closed, the session cannot continue to be used. This change detects that
scenario now, and will automatically reattach to another target, without
invalidating the object used by .NET code.

Additionally, this commit replaces the `ResetDevToolsSession()` method
in the `IDevTools` interface with a method called
`CloseDevToolsSession()`. The purpose of this method is to allow the
user to close a session without calling `Dispose()` directly on the
session object, but being unable to set the reference to the session
object to null in the driver instance.
  • Loading branch information
jimevans committed Sep 28, 2021
1 parent ad13b0f commit 9f02125
Show file tree
Hide file tree
Showing 10 changed files with 194 additions and 119 deletions.
13 changes: 5 additions & 8 deletions dotnet/src/webdriver/Chromium/ChromiumDriver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -217,25 +217,22 @@ public DevToolsSession GetDevToolsSession(int devToolsProtocolVersion)
}

/// <summary>
/// Resets a DevTools session
/// Closes a DevTools session.
/// </summary>
public void ResetDevToolsSession()
public void CloseDevToolsSession()
{
if (this.devToolsSession != null)
{
this.devToolsSession.ActiveSessionId = null;
this.devToolsSession.InitializeSession().ConfigureAwait(false).GetAwaiter().GetResult();
this.devToolsSession.Dispose();
this.devToolsSession = null;
}
}

protected override void Dispose(bool disposing)
{
if (disposing)
{
if (this.devToolsSession != null)
{
this.devToolsSession.Dispose();
}
this.CloseDevToolsSession();
}

base.Dispose(disposing);
Expand Down
189 changes: 100 additions & 89 deletions dotnet/src/webdriver/DevTools/DevToolsSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@

using System;
using System.Collections.Concurrent;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Net.Http;
Expand All @@ -43,6 +42,9 @@ public class DevToolsSession : IDevToolsSession
private string websocketAddress;
private readonly TimeSpan closeConnectionWaitTimeSpan = TimeSpan.FromSeconds(2);

private bool isDisposed = false;
private string attachedTargetId;

private ClientWebSocket sessionSocket;
private ConcurrentDictionary<long, DevToolsCommandData> pendingCommands = new ConcurrentDictionary<long, DevToolsCommandData>();
private long currentCommandId = 0;
Expand Down Expand Up @@ -246,6 +248,14 @@ public T GetVersionSpecificDomains<T>() where T: DevToolsSessionDomains
return null;
}

/// <summary>
/// Disposes of the DevToolsSession and frees all resources.
///</summary>
public void Dispose()
{
this.Dispose(true);
}

/// <summary>
/// Asynchronously starts the session.
/// </summary>
Expand All @@ -256,36 +266,100 @@ internal async Task Start(int requestedProtocolVersion)
int protocolVersion = await InitializeProtocol(requestedProtocolVersion);
this.domains = DevToolsDomains.InitializeDomains(protocolVersion, this);
await this.InitializeSession();
this.domains.Target.TargetDetached += OnTargetDetached;
try
{
// Wrap this in a try-catch, because it's not the end of the
// world if clearing the log doesn't work.
await this.domains.Log.Clear();
LogTrace("Log cleared.", this.attachedTargetId);
}
catch (WebDriverException)
{
}
}

internal async Task InitializeSession()
{
string targetId = null;
LogTrace("Initializing session");
var targets = await this.domains.Target.GetTargets();
foreach (var target in targets)
{
if (target.Type == "page")
{
targetId = target.TargetId;
LogTrace("Found Target ID {0}.", targetId);
string sessionId = await this.domains.Target.AttachToTarget(targetId);
LogTrace("Target ID {0} attached. Active session ID: {1}", targetId, sessionId);
this.attachedTargetId = target.TargetId;
LogTrace("Found Target ID {0}.", this.attachedTargetId);
string sessionId = await this.domains.Target.AttachToTarget(this.attachedTargetId);
LogTrace("Target ID {0} attached. Active session ID: {1}", this.attachedTargetId, sessionId);
this.ActiveSessionId = sessionId;
break;
}
}

await this.domains.Target.SetAutoAttach();
LogTrace("AutoAttach is set.", targetId);
try
{
// Wrap this in a try-catch, because it's not the end of the
// world if clearing the log doesn't work.
await this.domains.Log.Clear();
LogTrace("Log cleared.", targetId);
}
catch (WebDriverException)
LogTrace("AutoAttach is set.", this.attachedTargetId);
}

protected void Dispose(bool disposing)
{
if (!isDisposed)
{
if (disposing)
{
this.domains.Target.TargetDetached -= OnTargetDetached;
if (sessionSocket != null)
{
if (receiveTask != null)
{
if (sessionSocket.State == WebSocketState.Open)
{
try
{
// Since Chromium-based DevTools does not respond to the close
// request with a correctly echoed WebSocket close packet, but
// rather just terminates the socket connection, so we have to
// catch the exception thrown when the socket is terminated
// unexpectedly. Also, because we are using async, waiting for
// the task to complete might throw a TaskCanceledException,
// which we should also catch. Additiionally, there are times
// when mulitple failure modes can be seen, which will throw an
// AggregateException, consolidating several exceptions into one,
// and this too must be caught. Finally, the call to CloseAsync
// will hang even though the connection is already severed.
// Wait for the task to complete for a short time (since we're
// restricted to localhost, the default of 2 seconds should be
// plenty; if not, change the initialization of the timout),
// and if the task is still running, then we assume the connection
// is properly closed.
Task closeTask = Task.Run(() => sessionSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None));
closeTask.Wait(closeConnectionWaitTimeSpan);
}
catch (WebSocketException)
{
}
catch (TaskCanceledException)
{
}
catch (AggregateException)
{
}
}

// Wait for the recieve task to be completely exited (for
// whatever reason) before attempting to dispose it.
receiveTask.Wait();
receiveTask.Dispose();
receiveTask = null;
}

sessionSocket.Dispose();
sessionSocket = null;
}

pendingCommands.Clear();
}

isDisposed = true;
}
}

Expand Down Expand Up @@ -448,6 +522,17 @@ private void ProcessIncomingMessage(string message)
LogTrace("Recieved Other: {0}", message);
}

private async void OnTargetDetached(object sender, TargetDetachedEventArgs e)
{
if (e.TargetId == this.attachedTargetId)
{
LogTrace("TargetDetached event received for session attached target (Target ID: {0}); reinitializing session", e.TargetId);
this.attachedTargetId = null;
this.ActiveSessionId = null;
await this.InitializeSession();
}
}

private void OnDevToolsEventReceived(DevToolsEventReceivedEventArgs e)
{
if (DevToolsEventReceived != null)
Expand All @@ -471,79 +556,5 @@ private void LogError(string message, params object[] args)
LogMessage(this, new DevToolsSessionLogMessageEventArgs(DevToolsSessionLogLevel.Error, message, args));
}
}

#region IDisposable Support
private bool isDisposed = false;

protected void Dispose(bool disposing)
{
if (!isDisposed)
{
if (disposing)
{
if (sessionSocket != null)
{
if (receiveTask != null)
{
if (sessionSocket.State == WebSocketState.Open)
{
try
{
// Since Chromium-based DevTools does not respond to the close
// request with a correctly echoed WebSocket close packet, but
// rather just terminates the socket connection, so we have to
// catch the exception thrown when the socket is terminated
// unexpectedly. Also, because we are using async, waiting for
// the task to complete might throw a TaskCanceledException,
// which we should also catch. Additiionally, there are times
// when mulitple failure modes can be seen, which will throw an
// AggregateException, consolidating several exceptions into one,
// and this too must be caught. Finally, the call to CloseAsync
// will hang even though the connection is already severed.
// Wait for the task to complete for a short time (since we're
// restricted to localhost, the default of 2 seconds should be
// plenty; if not, change the initialization of the timout),
// and if the task is still running, then we assume the connection
// is properly closed.
Task closeTask = Task.Run(() => sessionSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None));
closeTask.Wait(closeConnectionWaitTimeSpan);
}
catch (WebSocketException)
{
}
catch (TaskCanceledException)
{
}
catch (AggregateException)
{
}
}

// Wait for the recieve task to be completely exited (for
// whatever reason) before attempting to dispose it.
receiveTask.Wait();
receiveTask.Dispose();
receiveTask = null;
}

sessionSocket.Dispose();
sessionSocket = null;
}

pendingCommands.Clear();
}

isDisposed = true;
}
}

/// <summary>
/// Disposes of the DevToolsSession and frees all resources.
///</summary>
public void Dispose()
{
Dispose(true);
}
#endregion
}
}
4 changes: 2 additions & 2 deletions dotnet/src/webdriver/DevTools/IDevTools.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ public interface IDevTools
DevToolsSession GetDevToolsSession(int protocolVersion);

/// <summary>
/// Resets a DevTools session
/// Closes a DevTools session
/// </summary>
void ResetDevToolsSession();
void CloseDevToolsSession();
}
}
19 changes: 18 additions & 1 deletion dotnet/src/webdriver/DevTools/Target.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
// limitations under the License.
// </copyright>

using System.Collections.Generic;
using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;

Expand All @@ -27,6 +27,11 @@ namespace OpenQA.Selenium.DevTools
/// </summary>
public abstract class Target
{
/// <summary>
/// Occurs when a target is detached.
/// </summary>
public event EventHandler<TargetDetachedEventArgs> TargetDetached;

/// <summary>
/// Asynchronously gets the targets available for this session.
/// </summary>
Expand Down Expand Up @@ -62,5 +67,17 @@ public abstract class Target
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
public abstract Task SetAutoAttach();

/// <summary>
/// Raises the TargetDetached event.
/// </summary>
/// <param name="e">An <see cref="TargetDetachedEventArgs"/> that contains the event data.</param>
protected virtual void OnTargetDetached(TargetDetachedEventArgs e)
{
if (this.TargetDetached != null)
{
this.TargetDetached(this, e);
}
}
}
}
38 changes: 38 additions & 0 deletions dotnet/src/webdriver/DevTools/TargetDetachedEventArgs.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// <copyright file="TargetDetachedEventArgs.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>

using System;

namespace OpenQA.Selenium.DevTools
{
/// <summary>
/// Event arguments present when the TargetDetached event is raised.
/// </summary>
public class TargetDetachedEventArgs : EventArgs
{
/// <summary>
/// Gets the ID of the session of the target detached.
/// </summary>
public string SessionId { get; internal set; }

/// <summary>
/// Gets the ID of the target detached.
/// </summary>
public string TargetId { get; internal set; }
}
}
8 changes: 7 additions & 1 deletion dotnet/src/webdriver/DevTools/v85/V85Target.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
namespace OpenQA.Selenium.DevTools.V85
{
/// <summary>
/// Class providing functionality for manipulating targets for version 86 of the DevTools Protocol
/// Class providing functionality for manipulating targets for version 85 of the DevTools Protocol
/// </summary>
public class V85Target : DevTools.Target
{
Expand All @@ -39,6 +39,7 @@ public class V85Target : DevTools.Target
public V85Target(TargetAdapter adapter)
{
this.adapter = adapter;
adapter.DetachedFromTarget += OnDetachedFromTarget;
}

/// <summary>
Expand Down Expand Up @@ -110,5 +111,10 @@ public override async Task SetAutoAttach()
{
await adapter.SetAutoAttach(new SetAutoAttachCommandSettings() { AutoAttach = true, WaitForDebuggerOnStart = false, Flatten = true });
}

private void OnDetachedFromTarget(object sender, DetachedFromTargetEventArgs e)
{
this.OnTargetDetached(new TargetDetachedEventArgs() { SessionId = e.SessionId, TargetId = e.TargetId });
}
}
}
Loading

0 comments on commit 9f02125

Please sign in to comment.