ferrum 0.20.2 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +2 -4
  3. data/lib/ferrum/accessibility.rb +40 -6
  4. data/lib/ferrum/browser/command.rb +2 -11
  5. data/lib/ferrum/browser/options/chrome.rb +58 -1
  6. data/lib/ferrum/browser/options.rb +63 -9
  7. data/lib/ferrum/browser/process.rb +12 -4
  8. data/lib/ferrum/browser/xvfb.rb +22 -2
  9. data/lib/ferrum/browser.rb +74 -35
  10. data/lib/ferrum/client/web_socket.rb +13 -6
  11. data/lib/ferrum/client.rb +119 -81
  12. data/lib/ferrum/concurrency/awaitable_map.rb +171 -0
  13. data/lib/ferrum/concurrency/cell.rb +128 -0
  14. data/lib/ferrum/concurrency/dispatcher.rb +146 -0
  15. data/lib/ferrum/console.rb +3 -2
  16. data/lib/ferrum/context.rb +162 -27
  17. data/lib/ferrum/contexts.rb +45 -22
  18. data/lib/ferrum/cookies/collection.rb +93 -0
  19. data/lib/ferrum/cookies/cookie.rb +0 -11
  20. data/lib/ferrum/cookies.rb +79 -86
  21. data/lib/ferrum/deadline.rb +140 -0
  22. data/lib/ferrum/dialog.rb +22 -0
  23. data/lib/ferrum/downloads.rb +83 -10
  24. data/lib/ferrum/errors.rb +96 -6
  25. data/lib/ferrum/frame/dom.rb +147 -38
  26. data/lib/ferrum/frame/runtime.rb +40 -32
  27. data/lib/ferrum/frame/script.rb +7 -38
  28. data/lib/ferrum/frame.rb +57 -20
  29. data/lib/ferrum/headers.rb +32 -27
  30. data/lib/ferrum/interceptable/chain.rb +99 -0
  31. data/lib/ferrum/interceptable.rb +44 -27
  32. data/lib/ferrum/isolated_world.rb +9 -10
  33. data/lib/ferrum/keyboard.rb +27 -6
  34. data/lib/ferrum/mouse.rb +139 -52
  35. data/lib/ferrum/network/auth_request.rb +42 -7
  36. data/lib/ferrum/network/error.rb +34 -4
  37. data/lib/ferrum/network/exchange.rb +35 -7
  38. data/lib/ferrum/network/intercepted_request.rb +42 -9
  39. data/lib/ferrum/network/request.rb +33 -9
  40. data/lib/ferrum/network/request_params.rb +11 -2
  41. data/lib/ferrum/network/response.rb +23 -2
  42. data/lib/ferrum/network.rb +267 -64
  43. data/lib/ferrum/node.rb +430 -62
  44. data/lib/ferrum/page/animation.rb +4 -0
  45. data/lib/ferrum/page/cookies.rb +133 -0
  46. data/lib/ferrum/page/frames.rb +7 -7
  47. data/lib/ferrum/page/navigation.rb +430 -0
  48. data/lib/ferrum/page/screencast.rb +4 -0
  49. data/lib/ferrum/page/screenshot.rb +13 -1
  50. data/lib/ferrum/page/stream.rb +13 -5
  51. data/lib/ferrum/page/tracing.rb +12 -7
  52. data/lib/ferrum/page.rb +168 -190
  53. data/lib/ferrum/remote_object.rb +4 -0
  54. data/lib/ferrum/target.rb +49 -11
  55. data/lib/ferrum/utils/deprecate.rb +73 -2
  56. data/lib/ferrum/utils/poll.rb +57 -0
  57. data/lib/ferrum/version.rb +1 -1
  58. data/lib/ferrum/worker.rb +34 -19
  59. data/lib/ferrum.rb +5 -1
  60. metadata +11 -6
  61. data/lib/ferrum/browser/options/base.rb +0 -112
  62. data/lib/ferrum/client/subscriber.rb +0 -145
  63. data/lib/ferrum/frame/runtime/legacy.rb +0 -336
  64. data/lib/ferrum/utils/event.rb +0 -33
@@ -0,0 +1,140 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ferrum
4
+ #
5
+ # A point in time by which an operation has to finish, on the monotonic
6
+ # clock. One deadline is shared by every step of an operation, so the whole
7
+ # operation is bounded by a single budget instead of each step getting its
8
+ # own.
9
+ #
10
+ # A deadline can be set for a block with {.within}, then every call made in it, by the same thread, runs under
11
+ # whatever is left of it. A call can only shorten that budget, never extend it.
12
+ #
13
+ # @example
14
+ # deadline = Ferrum::Deadline.after(10)
15
+ # deadline.remaining # => 9.99
16
+ # deadline.expired? # => false
17
+ #
18
+ # @example
19
+ # Ferrum::Deadline.within(10) do
20
+ # page.go_to("https://example.com")
21
+ # page.cookies.to_a
22
+ # page.evaluate("document.title")
23
+ # end
24
+ #
25
+ class Deadline
26
+ THREAD_KEY = :ferrum_deadline
27
+
28
+ #
29
+ # The deadline set by the enclosing {.within} block of this thread.
30
+ #
31
+ # @return [Deadline, nil]
32
+ #
33
+ def self.current
34
+ Thread.current.thread_variable_get(THREAD_KEY)
35
+ end
36
+
37
+ #
38
+ # Runs the block with every Ferrum call made by this thread bound by the same budget. A block inside another
39
+ # one can only shorten it. Other threads, event callbacks for instance, don't inherit it.
40
+ #
41
+ # @param [Numeric, Deadline] timeout
42
+ #
43
+ # @return [Object]
44
+ # What the block returns.
45
+ #
46
+ # @raise [TimeoutError]
47
+ # From the calls in the block once the budget is used up.
48
+ #
49
+ def self.within(timeout)
50
+ previous = current
51
+ Thread.current.thread_variable_set(THREAD_KEY, wrap(timeout))
52
+ yield
53
+ ensure
54
+ Thread.current.thread_variable_set(THREAD_KEY, previous)
55
+ end
56
+
57
+ #
58
+ # Runs the block outside the budget of the enclosing {.within} block, for cleanup that has to reach the browser
59
+ # even when the budget is used up, like releasing a held key. The calls in it follow their own timeouts.
60
+ #
61
+ # @api private
62
+ #
63
+ # @return [Object]
64
+ # What the block returns.
65
+ #
66
+ def self.suspend
67
+ previous = current
68
+ Thread.current.thread_variable_set(THREAD_KEY, nil)
69
+ yield
70
+ ensure
71
+ Thread.current.thread_variable_set(THREAD_KEY, previous)
72
+ end
73
+
74
+ #
75
+ # Starts a deadline that expires in `seconds`.
76
+ #
77
+ # @param [Numeric] seconds
78
+ #
79
+ # @return [Deadline]
80
+ #
81
+ def self.after(seconds)
82
+ new(Utils::ElapsedTime.monotonic_time + seconds)
83
+ end
84
+
85
+ #
86
+ # Returns a {Deadline} as is, and starts one for a number of seconds. Within a {.within} block it returns
87
+ # whichever of the two expires first.
88
+ #
89
+ # @param [Deadline, Numeric] timeout
90
+ #
91
+ # @return [Deadline]
92
+ #
93
+ def self.wrap(timeout)
94
+ deadline = timeout.is_a?(self) ? timeout : after(timeout)
95
+ ambient = current
96
+ ambient ? deadline.min(ambient) : deadline
97
+ end
98
+
99
+ #
100
+ # @param [Float] at
101
+ # Monotonic time at which the deadline expires.
102
+ #
103
+ def initialize(at)
104
+ @at = at
105
+ end
106
+
107
+ #
108
+ # Seconds left before the deadline expires, never negative.
109
+ #
110
+ # @return [Float]
111
+ #
112
+ def remaining
113
+ [@at - Utils::ElapsedTime.monotonic_time, 0.0].max
114
+ end
115
+
116
+ #
117
+ # The one of the two deadlines that expires first.
118
+ #
119
+ # @param [Deadline] other
120
+ #
121
+ # @return [Deadline]
122
+ #
123
+ def min(other)
124
+ at <= other.at ? self : other
125
+ end
126
+
127
+ #
128
+ # Whether the deadline has expired.
129
+ #
130
+ # @return [Boolean]
131
+ #
132
+ def expired?
133
+ remaining.zero?
134
+ end
135
+
136
+ protected
137
+
138
+ attr_reader :at
139
+ end
140
+ end
data/lib/ferrum/dialog.rb CHANGED
@@ -14,6 +14,16 @@ module Ferrum
14
14
  @page = page
15
15
  @message = params["message"]
16
16
  @default_prompt = params["defaultPrompt"]
17
+ @handled = false
18
+ end
19
+
20
+ #
21
+ # Whether the dialog was accepted or dismissed.
22
+ #
23
+ # @return [Boolean]
24
+ #
25
+ def handled?
26
+ @handled
17
27
  end
18
28
 
19
29
  #
@@ -21,6 +31,10 @@ module Ferrum
21
31
  #
22
32
  # @param [String, nil] prompt_text
23
33
  #
34
+ # @return [nil]
35
+ #
36
+ # @raise [TimeoutError]
37
+ #
24
38
  # @example
25
39
  # browser = Ferrum::Browser.new
26
40
  # browser.on(:dialog) do |dialog|
@@ -36,12 +50,18 @@ module Ferrum
36
50
  options = { accept: true }
37
51
  response = prompt_text || default_prompt
38
52
  options.merge!(promptText: response) if response
53
+ @handled = true
39
54
  @page.command("Page.handleJavaScriptDialog", slowmoable: true, **options)
55
+ nil
40
56
  end
41
57
 
42
58
  #
43
59
  # Dismiss dialog.
44
60
  #
61
+ # @return [nil]
62
+ #
63
+ # @raise [TimeoutError]
64
+ #
45
65
  # @example
46
66
  # browser = Ferrum::Browser.new
47
67
  # browser.on(:dialog) do |dialog|
@@ -54,7 +74,9 @@ module Ferrum
54
74
  # browser.go_to("https://google.com")
55
75
  #
56
76
  def dismiss
77
+ @handled = true
57
78
  @page.command("Page.handleJavaScriptDialog", slowmoable: true, accept: false)
79
+ nil
58
80
  end
59
81
 
60
82
  #
@@ -9,12 +9,17 @@ module Ferrum
9
9
  # current download finishes via {#wait}.
10
10
  #
11
11
  class Downloads
12
+ WAIT_TIMEOUT = 5
13
+ WAIT_DEPRECATED = "downloads.wait will be removed in Ferrum 0.22. Use page.await_download { ... } around the " \
14
+ "code that starts the download."
12
15
  VALID_BEHAVIOR = %i[deny allow allowAndName default].freeze
13
16
 
14
17
  def initialize(page)
15
18
  @page = page
16
- @event = Utils::Event.new.tap(&:set)
19
+ @idle = Concurrency::Cell.set(true)
17
20
  @files = {}
21
+ @waiters = []
22
+ @waiters_mutex = Mutex.new
18
23
  end
19
24
 
20
25
  #
@@ -26,10 +31,61 @@ module Ferrum
26
31
  @files.values
27
32
  end
28
33
 
34
+ #
35
+ # Runs the block and waits for the download it starts to finish.
36
+ #
37
+ # @param [Numeric, Deadline] timeout
38
+ # How long the block and the download may take together, in seconds.
39
+ #
40
+ # @yield The code that starts the download, e.g. clicking a link.
41
+ #
42
+ # @return [Hash, nil]
43
+ # The finished download, like an entry of {#files}, its `"state"` is
44
+ # `"completed"` or `"canceled"`. `nil` if it doesn't finish in time.
45
+ #
46
+ # @raise [ArgumentError]
47
+ # If no block is given.
48
+ #
49
+ # @example
50
+ # page.await_download { page.at_css("#download").click } # => {"suggestedFilename" => "file.pdf", ...}
51
+ #
52
+ def await_download(timeout: WAIT_TIMEOUT)
53
+ raise ArgumentError, "await_download needs a block that starts the download" unless block_given?
54
+
55
+ deadline = Deadline.wrap(timeout)
56
+ waiter = { guid: nil, cell: Concurrency::Cell.new }
57
+ @waiters_mutex.synchronize { @waiters << waiter }
58
+ yield
59
+ waiter[:cell].value if waiter[:cell].wait(deadline)
60
+ ensure
61
+ @waiters_mutex.synchronize { @waiters.delete(waiter) }
62
+ end
63
+
64
+ #
65
+ # Same as {#await_download}, but raises if the download doesn't finish in time.
66
+ #
67
+ # @param [Numeric, Deadline] timeout
68
+ #
69
+ # @yield The code that starts the download.
70
+ #
71
+ # @return [Hash]
72
+ #
73
+ # @raise [TimeoutError]
74
+ # If the download doesn't finish in time.
75
+ #
76
+ # @raise [ArgumentError]
77
+ # If no block is given.
78
+ #
79
+ def await_download!(timeout: WAIT_TIMEOUT, &)
80
+ await_download(timeout: timeout, &) || raise(TimeoutError)
81
+ end
82
+
29
83
  #
30
84
  # Waits until the current download finishes.
31
85
  #
32
- # @param [Integer] timeout
86
+ # @deprecated Will be removed in Ferrum 0.22. Use {#await_download} around the code that starts the download.
87
+ #
88
+ # @param [Numeric, Deadline] timeout
33
89
  # How long to wait in seconds.
34
90
  #
35
91
  # @yield
@@ -37,11 +93,13 @@ module Ferrum
37
93
  #
38
94
  # @return [void]
39
95
  #
40
- def wait(timeout = 5)
41
- @event.reset
96
+ def wait(timeout = WAIT_TIMEOUT)
97
+ Utils::Deprecate.warn(WAIT_DEPRECATED, user_code: true)
98
+ deadline = Deadline.wrap(timeout)
99
+ generation = @idle.clear
42
100
  yield if block_given?
43
- @event.wait(timeout)
44
- @event.set
101
+ @idle.wait(deadline)
102
+ @idle.set(true) if generation == @idle.generation
45
103
  end
46
104
 
47
105
  #
@@ -53,11 +111,13 @@ module Ferrum
53
111
  # @param [:deny, :allow, :allowAndName, :default] behavior
54
112
  # Whether/how to allow downloads.
55
113
  #
56
- # @return [void]
114
+ # @return [nil]
57
115
  #
58
116
  # @raise [ArgumentError]
59
117
  # @raise [Ferrum::Error]
60
118
  #
119
+ # @raise [TimeoutError]
120
+ #
61
121
  def set_behavior(save_path:, behavior: :allow)
62
122
  raise ArgumentError unless VALID_BEHAVIOR.include?(behavior.to_sym)
63
123
  raise Error, "supply absolute path for `:save_path` option" unless Pathname.new(save_path.to_s).absolute?
@@ -68,6 +128,7 @@ module Ferrum
68
128
  downloadPath: save_path,
69
129
  behavior: behavior,
70
130
  eventsEnabled: true)
131
+ nil
71
132
  end
72
133
 
73
134
  #
@@ -75,6 +136,7 @@ module Ferrum
75
136
  #
76
137
  # @return [void]
77
138
  #
139
+ # @api private
78
140
  def subscribe
79
141
  subscribe_download_will_begin
80
142
  subscribe_download_progress
@@ -85,10 +147,12 @@ module Ferrum
85
147
  #
86
148
  # @return [void]
87
149
  #
150
+ # @api private
88
151
  def subscribe_download_will_begin
89
152
  @page.on("Browser.downloadWillBegin") do |params|
90
- @event.reset
153
+ @idle.clear
91
154
  @files[params["guid"]] = params
155
+ @waiters_mutex.synchronize { @waiters.find { |w| w[:guid].nil? }&.store(:guid, params["guid"]) }
92
156
  end
93
157
  end
94
158
 
@@ -97,17 +161,26 @@ module Ferrum
97
161
  #
98
162
  # @return [void]
99
163
  #
164
+ # @api private
100
165
  def subscribe_download_progress
101
166
  @page.on("Browser.downloadProgress") do |params|
102
167
  @files[params["guid"]].merge!(params)
103
168
 
104
169
  case params["state"]
105
170
  when "completed", "canceled"
106
- @event.set
171
+ @idle.set(true)
172
+ finish_waiters(params["guid"])
107
173
  else
108
- @event.reset
174
+ @idle.clear
109
175
  end
110
176
  end
111
177
  end
178
+
179
+ private
180
+
181
+ def finish_waiters(guid)
182
+ waiters = @waiters_mutex.synchronize { @waiters.select { |w| w[:guid] == guid } }
183
+ waiters.each { |w| w[:cell].set(@files[guid]) }
184
+ end
112
185
  end
113
186
  end
data/lib/ferrum/errors.rb CHANGED
@@ -3,18 +3,16 @@
3
3
  module Ferrum
4
4
  # Base class for all errors raised by Ferrum.
5
5
  class Error < StandardError; end
6
- # Raised when the referenced page no longer exists.
7
- class NoSuchPageError < Error; end
8
6
  # Raised when the referenced browser target cannot be found.
9
7
  class NoSuchTargetError < Error; end
8
+ # Raised when Chrome reports that the referenced page no longer exists, a {NoSuchTargetError} for pages.
9
+ class NoSuchPageError < NoSuchTargetError; end
10
10
  # Raised when a requested feature isn't implemented for the current setup.
11
11
  class NotImplementedError < Error; end
12
12
  # Raised when no browser binary can be found at the configured path.
13
13
  class BinaryNotFoundError < Error; end
14
14
  # Raised when a required file path option is empty.
15
15
  class EmptyPathError < Error; end
16
- # Raised when the browser process server fails to start or crashes.
17
- class ServerError < Error; end
18
16
 
19
17
  # Raised when a request fails to reach the server, e.g. due to DNS or
20
18
  # connectivity issues.
@@ -26,6 +24,9 @@ module Ferrum
26
24
 
27
25
  # Raised when the request reached the server, but the page still has
28
26
  # pending network connections that never settled.
27
+ #
28
+ # @deprecated Will be removed in Ferrum 0.22 with the `:pending_connection_errors`
29
+ # option. `go_to!` raises {NavigationTimeoutError}.
29
30
  class PendingConnectionsError < StatusError
30
31
  attr_reader :pendings
31
32
 
@@ -73,8 +74,7 @@ module Ferrum
73
74
  "Timed out waiting for #{awaited}. It's possible that this happened " \
74
75
  "because something took a very long time (for example a page load " \
75
76
  "was slow). If so, setting the :timeout option to a higher value might " \
76
- "help. If this happened on an internal protocol call instead, try " \
77
- "raising :protocol_timeout."
77
+ "help."
78
78
  end
79
79
 
80
80
  private
@@ -98,6 +98,87 @@ module Ferrum
98
98
  end
99
99
  end
100
100
 
101
+ # Raised when connecting to a running browser at `:url` or `:ws_url` takes
102
+ # longer than `:process_timeout`.
103
+ class ConnectTimeoutError < TimeoutError
104
+ # The host and port connected to.
105
+ #
106
+ # @return [String]
107
+ attr_reader :address
108
+
109
+ # The seconds the connection was given.
110
+ #
111
+ # @return [Numeric]
112
+ attr_reader :timeout
113
+
114
+ #
115
+ # @param [String] address
116
+ # The host and port connected to.
117
+ #
118
+ # @param [Numeric] timeout
119
+ # The seconds the connection was given.
120
+ #
121
+ def initialize(address, timeout)
122
+ @address = address
123
+ @timeout = timeout
124
+ super()
125
+ end
126
+
127
+ #
128
+ # Explains that the browser couldn't be reached in time.
129
+ #
130
+ # @return [String]
131
+ #
132
+ def message
133
+ "Couldn't connect to the browser at #{address} within #{timeout} seconds. Check it's reachable, or set " \
134
+ "the :process_timeout option to a higher value if it's slow to answer."
135
+ end
136
+ end
137
+
138
+ # Raised by `go_to!`, `refresh!`, `back!` and `forward!` when the page
139
+ # doesn't load in time.
140
+ class NavigationTimeoutError < TimeoutError
141
+ # The URL navigated to.
142
+ #
143
+ # @return [String]
144
+ attr_reader :url
145
+
146
+ # URLs of the requests still pending when the timeout was reached.
147
+ #
148
+ # @return [Array<String>]
149
+ attr_reader :pendings
150
+
151
+ #
152
+ # @param [String] url
153
+ # The URL navigated to.
154
+ #
155
+ # @param [Array<String>] pendings
156
+ # URLs of the requests still pending.
157
+ #
158
+ def initialize(url, pendings = [])
159
+ @url = url
160
+ @pendings = pendings
161
+ super()
162
+ end
163
+
164
+ #
165
+ # Explains that the page didn't load in time, naming the requests that
166
+ # were still pending.
167
+ #
168
+ # @return [String]
169
+ #
170
+ def message
171
+ target = @url || "the page"
172
+ if @pendings.empty?
173
+ "Timed out waiting for #{target} to load. The page took too long, setting the :timeout option to a higher " \
174
+ "value might help."
175
+ else
176
+ "Timed out waiting for #{target} to load, still pending: #{@pendings.join(', ')}. If they're expected to be " \
177
+ "slow, setting the :timeout option to a higher value might help, otherwise block them with network.blacklist."
178
+ end
179
+ end
180
+ end
181
+
101
182
  # Raised when the browser process doesn't produce a websocket URL within
102
183
  # the configured `:process_timeout`.
103
184
  class ProcessTimeoutError < Error
@@ -198,6 +279,15 @@ module Ferrum
198
279
  end
199
280
  end
200
281
 
282
+ # Raised when an evaluated script returns a value nested too deeply for
283
+ # Chrome to serialize, around 100 levels.
284
+ class ResultTooDeepError < BrowserError
285
+ def initialize(response)
286
+ super(response.merge("message" => "The result is nested too deeply to be serialized, return less of it or " \
287
+ "use evaluate_handle"))
288
+ end
289
+ end
290
+
201
291
  # Raised when the browser reports that a DOM node no longer exists.
202
292
  class NodeNotFoundError < BrowserError; end
203
293