From 7815291c9acd534c9e76f976111348ed0f874d94 Mon Sep 17 00:00:00 2001 From: Dmitry Vorotilin Date: Mon, 30 Nov 2026 14:38:00 +0300 Subject: [PATCH] fix(browser): disconnect in shutdown when Browser.close raises shutdown ran disconnect in the same begin as Browser.close, so a TimeoutError from a hung browser or a CDP error from a remote endpoint skipped it and left the client's threads and socket open. Disconnect in the ensure, before stopping the process, as quit does. Also drop the stale mention of page connections from the disconnect docs. --- lib/ferrum/browser.rb | 17 ++++++++++------- spec/browser_spec.rb | 19 +++++++++++++++++++ 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/lib/ferrum/browser.rb b/lib/ferrum/browser.rb index bc7b6bac..2234897f 100644 --- a/lib/ferrum/browser.rb +++ b/lib/ferrum/browser.rb @@ -262,19 +262,22 @@ def shutdown(wait: true) begin close_browser if @client - disconnect ensure - thread = @process&.stop(wait: wait, grace: Process::Killer::KILL_TIMEOUT) - @process = nil + begin + disconnect + ensure + thread = @process&.stop(wait: wait, grace: Process::Killer::KILL_TIMEOUT) + @process = nil + end end thread end # - # Closes the page connections and the client connection, leaving the - # browser running, whether Ferrum launched it or connected to it. A - # launched browser stays reachable through {#process}, so it can be - # stopped later with `browser.process.stop` or {#quit}. + # Closes the client connection, leaving the browser running, whether + # Ferrum launched it or connected to it. A launched browser stays + # reachable through {#process}, so it can be stopped later with + # `browser.process.stop` or {#quit}. # # @return [nil] # diff --git a/spec/browser_spec.rb b/spec/browser_spec.rb index d2b4070b..227b6f4d 100644 --- a/spec/browser_spec.rb +++ b/spec/browser_spec.rb @@ -1235,6 +1235,25 @@ def closed_by_peer?(socket) ensure launched&.quit end + + it "disconnects and stops the process when Browser.close times out", :launch do + expect_cleanup_when_close_raises(Ferrum::TimeoutError) + end + + it "disconnects and stops the process when Browser.close returns an error", :launch do + expect_cleanup_when_close_raises(Ferrum::BrowserError.new("message" => "not allowed")) + end + + def expect_cleanup_when_close_raises(error) + browser = Ferrum::Browser.new + allow(browser).to receive(:close).and_raise(error) + + expect { browser.shutdown }.to raise_error(error.is_a?(Class) ? error : error.class) + expect(browser.client).to be_nil + expect(browser.process).to be_nil + ensure + browser&.quit + end end describe "#restart" do