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
@@ -25,6 +25,7 @@ module Ferrum
25
25
  WEBSOCKET_BUG_SLEEP = 0.05
26
26
  DEFAULT_PORTS = { "ws" => 80, "wss" => 443 }.freeze
27
27
  WRITE_CHUNK_SIZE = 64 * 1024
28
+ WRITE_TIMEOUT = 30
28
29
  ESCAPE_OR_LONE_SURROGATE = /\\u[dD][89abAB]\h{2}\\u[dD][c-fC-F]\h{2}|\\u([dD][89a-fA-F]\h{2})|\\./
29
30
 
30
31
  attr_reader :url, :messages
@@ -33,21 +34,21 @@ module Ferrum
33
34
  # Why Ferrum closed the connection itself, `nil` if it didn't.
34
35
  attr_reader :close_reason
35
36
 
36
- def initialize(url, max_receive_size, log, write_timeout = nil)
37
+ def initialize(url, max_receive_size, log, write_timeout = WRITE_TIMEOUT, connect_timeout: nil)
37
38
  @url = url
38
39
  @log = log
39
40
  @write_timeout = write_timeout
40
41
  uri = URI.parse(@url)
41
42
  port = uri.port || DEFAULT_PORTS[uri.scheme]
42
43
 
44
+ tcp = connect(uri.host, port, connect_timeout)
43
45
  if port == 443 || url.scheme == "wss"
44
- tcp = TCPSocket.new(uri.host, port)
45
46
  ssl_context = OpenSSL::SSL::SSLContext.new
46
47
  @sock = OpenSSL::SSL::SSLSocket.new(tcp, ssl_context)
47
48
  @sock.sync_close = true
48
49
  @sock.connect
49
50
  else
50
- @sock = TCPSocket.new(uri.host, port)
51
+ @sock = tcp
51
52
  end
52
53
 
53
54
  max_receive_size ||= ::WebSocket::Driver::MAX_LENGTH
@@ -118,7 +119,7 @@ module Ferrum
118
119
  # @param [Hash] data
119
120
  # The message to send, must include an `:id` key.
120
121
  #
121
- # @param [Numeric, nil] timeout
122
+ # @param [Numeric, Deadline, nil] timeout
122
123
  # How long the frame may wait in the queue. A frame still queued after
123
124
  # that is dropped, nobody waits for its response anymore. `nil` keeps it
124
125
  # until it's written.
@@ -127,7 +128,7 @@ module Ferrum
127
128
  #
128
129
  def send_message(data, timeout = nil)
129
130
  json = data.to_json
130
- deadline = Utils::ElapsedTime.monotonic_time + timeout if timeout
131
+ deadline = Deadline.wrap(timeout) if timeout
131
132
  drive(deadline) { @driver.text(json) }
132
133
  @log&.sent(data, self)
133
134
  end
@@ -176,6 +177,12 @@ module Ferrum
176
177
 
177
178
  private
178
179
 
180
+ def connect(host, port, timeout)
181
+ TCPSocket.new(host, port, connect_timeout: timeout)
182
+ rescue IO::TimeoutError, Errno::ETIMEDOUT
183
+ raise ConnectTimeoutError.new("#{host}:#{port}", timeout)
184
+ end
185
+
179
186
  def drive(deadline = nil)
180
187
  @mutex.synchronize do
181
188
  yield
@@ -195,7 +202,7 @@ module Ferrum
195
202
  @writer = Utils::Thread.spawn do
196
203
  while (frame = @outgoing.pop)
197
204
  data, deadline = frame
198
- write_frame(data) unless deadline && Utils::ElapsedTime.monotonic_time > deadline
205
+ write_frame(data) unless deadline&.expired?
199
206
  end
200
207
  rescue EOFError, Errno::ECONNRESET, Errno::EPIPE, Errno::EBADF, IOError # rubocop:disable Lint/ShadowedException
201
208
  # The browser went away, nothing to report.
data/lib/ferrum/client.rb CHANGED
@@ -1,8 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "concurrent-ruby"
4
3
  require "forwardable"
5
- require "ferrum/client/subscriber"
6
4
  require "ferrum/client/web_socket"
7
5
  require "ferrum/utils/thread"
8
6
 
@@ -45,22 +43,35 @@ module Ferrum
45
43
  # @param [String] method
46
44
  # The CDP method name, e.g. `"Page.navigate"`.
47
45
  #
48
- # @param [Boolean] async
49
- # Whether to send the command without waiting for a response.
46
+ # @param [Numeric, Deadline] timeout
47
+ # How long to wait for this command's response. See {Client#send_message}.
50
48
  #
51
49
  # @param [Hash] params
52
50
  # The command's parameters.
53
51
  #
54
- # @param [Numeric, nil] timeout
55
- # How long to wait for this command's response, overriding
56
- # {Browser::Options#protocol_timeout}. See {Client#send_message}.
52
+ # @return [Hash]
53
+ # The command's result.
57
54
  #
58
- # @return [Boolean, Hash]
59
- # `true` when sent asynchronously, otherwise the command's result.
55
+ # @raise [TimeoutError]
60
56
  #
61
- def command(method, async: false, timeout: nil, **params)
57
+ def command(method, timeout:, **params)
62
58
  message = build_message(method, params)
63
- @client.send_message(message, async: async, timeout: timeout)
59
+ @client.send_message(message, timeout: timeout)
60
+ end
61
+
62
+ #
63
+ # Sends a CDP command scoped to this session without waiting for a response.
64
+ #
65
+ # @param [String] method
66
+ # The CDP method name, e.g. `"Runtime.runIfWaitingForDebugger"`.
67
+ #
68
+ # @param [Hash] params
69
+ # The command's parameters.
70
+ #
71
+ # @return [true]
72
+ #
73
+ def notify(method, **params)
74
+ @client.send_notification(build_message(method, params))
64
75
  end
65
76
 
66
77
  #
@@ -122,12 +133,12 @@ module Ferrum
122
133
 
123
134
  #
124
135
  # Removes all event callbacks registered for this session from the
125
- # underlying client's subscriber.
136
+ # underlying client's dispatcher.
126
137
  #
127
138
  # @return [void]
128
139
  #
129
140
  def close
130
- @client.subscriber.clear(session_id: session_id)
141
+ @client.dispatcher.clear { |k| k.match?(session_id) }
131
142
  end
132
143
 
133
144
  private
@@ -144,24 +155,27 @@ module Ferrum
144
155
  #
145
156
  # The low-level CDP client. Owns the {WebSocket} connection to the browser,
146
157
  # assigns command ids, matches responses back to their pending commands and
147
- # dispatches incoming events to the {Subscriber}. {SessionClient} builds on
158
+ # dispatches incoming events to the {Concurrency::Dispatcher}. {SessionClient} builds on
148
159
  # top of it to scope commands/events to a particular target's session.
149
160
  #
150
161
  class Client
151
162
  extend Forwardable
152
163
 
153
- delegate %i[protocol_timeout protocol_timeout=] => :options
164
+ PROTOCOL_TIMEOUT = 5
165
+ INTERRUPTIONS = %w[Fetch.requestPaused Fetch.authRequired].freeze
154
166
 
155
- attr_reader :ws_url, :options, :subscriber
167
+ delegate %i[timeout] => :options
168
+
169
+ attr_reader :ws_url, :options, :dispatcher
156
170
 
157
171
  def initialize(ws_url, options)
158
172
  @command_id = 0
159
173
  @command_id_mutex = Mutex.new
160
174
  @ws_url = ws_url
161
175
  @options = options
162
- @pendings = Concurrent::Hash.new
163
- @ws = WebSocket.new(ws_url, options.ws_max_receive_size, options.log, options.protocol_timeout)
164
- @subscriber = Subscriber.new
176
+ @responses = Concurrency::AwaitableMap.new
177
+ @ws = WebSocket.new(ws_url, options.ws_max_receive_size, options.log, connect_timeout: options.process_timeout)
178
+ @dispatcher = Concurrency::Dispatcher.new
165
179
 
166
180
  start
167
181
  end
@@ -172,74 +186,86 @@ module Ferrum
172
186
  # @param [String] method
173
187
  # The CDP method name, e.g. `"Target.createTarget"`.
174
188
  #
175
- # @param [Boolean] async
176
- # Whether to send the command without waiting for a response.
189
+ # @param [Numeric, Deadline] timeout
190
+ # How long to wait for this command's response. See {#send_message}.
177
191
  #
178
192
  # @param [Hash] params
179
193
  # The command's parameters.
180
194
  #
181
- # @param [Numeric, nil] timeout
182
- # How long to wait for this command's response, overriding
183
- # {Browser::Options#protocol_timeout}. See {#send_message}.
184
- #
185
- # @return [Boolean, Hash]
186
- # `true` when sent asynchronously, otherwise the command's result.
195
+ # @return [Hash]
196
+ # The command's result.
187
197
  #
188
- def command(method, async: false, timeout: nil, **params)
198
+ def command(method, timeout:, **params)
189
199
  message = build_message(method, params)
190
- send_message(message, async: async, timeout: timeout)
200
+ send_message(message, timeout: timeout)
201
+ end
202
+
203
+ #
204
+ # Sends a CDP command to the browser-wide session without waiting for a response.
205
+ #
206
+ # @param [String] method
207
+ # The CDP method name, e.g. `"Target.closeTarget"`.
208
+ #
209
+ # @param [Hash] params
210
+ # The command's parameters.
211
+ #
212
+ # @return [true]
213
+ #
214
+ def notify(method, **params)
215
+ send_notification(build_message(method, params))
191
216
  end
192
217
 
193
218
  #
194
- # Sends a raw CDP message over the websocket. Synchronous calls block
195
- # until a matching response arrives, or `timeout` elapses, defaulting to
196
- # `protocol_timeout` (delegated to {Browser::Options#protocol_timeout}).
197
- # That default is the transport-level budget for internal CDP bookkeeping
198
- # (e.g. `Target.createTarget`). {Page#command} overrides
199
- # this back to `timeout`, or a caller-supplied budget (e.g. `#pdf`/
200
- # `#screenshot`'s own `timeout:` argument), for the user-facing commands
201
- # it issues -- some of which (e.g. `Page.navigate`, `Page.printToPDF`)
202
- # rely on their own response latency to detect a stuck operation.
219
+ # Sends a raw CDP message over the websocket and blocks until a matching
220
+ # response arrives or `timeout` elapses. The caller says how long that is,
221
+ # so the budget it runs under is visible. Pass the {Deadline} of the
222
+ # surrounding operation to share its budget; inside {Deadline.within} the
223
+ # budget is also bound by the one that block sets.
203
224
  #
204
225
  # @param [Hash] message
205
226
  # The message to send, must include an `:id` key.
206
227
  #
207
- # @param [Boolean] async
208
- # Whether to return immediately instead of waiting for a response.
209
- #
210
- # @param [Numeric, nil] timeout
228
+ # @param [Numeric, Deadline] timeout
211
229
  # How long to wait for the response, counting the time the message waits
212
- # to be sent. Defaults to `protocol_timeout`.
230
+ # to be sent.
213
231
  #
214
- # @return [Boolean, Hash]
215
- # `true` when sent asynchronously, otherwise the parsed `"result"`
216
- # from the response.
232
+ # @return [Hash]
233
+ # The parsed `"result"` from the response.
217
234
  #
218
- def send_message(message, async:, timeout: nil)
219
- timeout ||= protocol_timeout
235
+ def send_message(message, timeout:)
236
+ deadline = Deadline.wrap(timeout)
220
237
 
221
- if async
222
- @ws.send_message(message, timeout)
223
- true
224
- else
225
- raise dead_browser_error if @ws.messages.closed?
226
-
227
- pending = Concurrent::IVar.new
228
- @pendings[message[:id]] = pending
229
- begin
230
- @ws.send_message(message, timeout)
231
- data = pending.value!(timeout)
232
- ensure
233
- @pendings.delete(message[:id])
234
- end
238
+ raise dead_browser_error if @ws.messages.closed?
235
239
 
236
- raise dead_browser_error if data.nil? && @ws.messages.closed?
237
- raise TimeoutError.new(message[:method], session_id: message[:sessionId]) unless data
238
-
239
- error, response = data.values_at("error", "result")
240
- raise_browser_error(error) if error
241
- response
240
+ @responses.expect(message[:id])
241
+ begin
242
+ @ws.send_message(message, deadline)
243
+ data = @responses.await(message[:id], deadline)
244
+ ensure
245
+ @responses.delete(message[:id])
242
246
  end
247
+
248
+ raise dead_browser_error if data.nil? && @ws.messages.closed?
249
+ raise TimeoutError.new(message[:method], session_id: message[:sessionId]) unless data
250
+
251
+ error, response = data.values_at("error", "result")
252
+ raise_browser_error(error) if error
253
+ response
254
+ end
255
+
256
+ #
257
+ # Sends a raw CDP message over the websocket without waiting for a
258
+ # response, which is dropped when it arrives. Nothing bounds it: a browser
259
+ # that stops reading is detected by the write watchdog.
260
+ #
261
+ # @param [Hash] message
262
+ # The message to send, must include an `:id` key.
263
+ #
264
+ # @return [true]
265
+ #
266
+ def send_notification(message)
267
+ @ws.send_message(message)
268
+ true
243
269
  end
244
270
 
245
271
  #
@@ -252,7 +278,7 @@ module Ferrum
252
278
  # The subscription id, used to unsubscribe via {#off}.
253
279
  #
254
280
  def on(event, &)
255
- @subscriber.on(event, &)
281
+ @dispatcher.on(event, &)
256
282
  end
257
283
 
258
284
  #
@@ -267,7 +293,7 @@ module Ferrum
267
293
  # @return [void]
268
294
  #
269
295
  def off(event, id)
270
- @subscriber.off(event, id)
296
+ @dispatcher.off(event, id)
271
297
  end
272
298
 
273
299
  # Whether there's at least one callback registered for the event.
@@ -277,7 +303,7 @@ module Ferrum
277
303
  #
278
304
  # @return [Boolean]
279
305
  def subscribed?(event)
280
- @subscriber.subscribed?(event)
306
+ @dispatcher.subscribed?(event)
281
307
  end
282
308
 
283
309
  #
@@ -295,16 +321,16 @@ module Ferrum
295
321
 
296
322
  #
297
323
  # Closes the underlying websocket, drops pending commands and stops
298
- # the message-processing thread and subscriber.
324
+ # the message-processing thread and dispatcher.
299
325
  #
300
326
  # @return [void]
301
327
  #
302
328
  def close
303
329
  @ws.close
304
330
  # Give a thread some time to handle a tail of messages
305
- @pendings.clear
331
+ @responses.close
306
332
  @thread.kill unless @thread.join(1)
307
- @subscriber.close
333
+ @dispatcher.close
308
334
  @ws.force_close
309
335
  end
310
336
 
@@ -316,7 +342,7 @@ module Ferrum
316
342
  def inspect
317
343
  "#<#{self.class} " \
318
344
  "@command_id=#{@command_id.inspect} " \
319
- "@pendings=#{@pendings.inspect} " \
345
+ "@responses=#{@responses.inspect} " \
320
346
  "@ws=#{@ws.inspect}>"
321
347
  end
322
348
 
@@ -331,7 +357,12 @@ module Ferrum
331
357
  #
332
358
  # @return [Hash]
333
359
  #
360
+ # @raise [ArgumentError]
361
+ # When given the removed `async:`, which would otherwise be sent to the browser as a parameter.
362
+ #
334
363
  def build_message(method, params)
364
+ raise ArgumentError, "async: is removed, use notify to send #{method} without waiting" if params.key?(:async)
365
+
335
366
  { method: method, params: params }.merge(id: next_command_id)
336
367
  end
337
368
 
@@ -344,9 +375,9 @@ module Ferrum
344
375
  break unless message
345
376
 
346
377
  if message.key?("method")
347
- @subscriber << message
378
+ dispatch(message)
348
379
  else
349
- @pendings[message["id"]]&.set(message)
380
+ @responses.fulfill(message["id"], message)
350
381
  end
351
382
  end
352
383
  rescue StandardError => e
@@ -355,14 +386,21 @@ module Ferrum
355
386
  warn("Ferrum: dispatch stopped, #{e.class}: #{e.message}\n #{e.backtrace&.first}")
356
387
  @ws.messages.close
357
388
  ensure
358
- release_pendings
389
+ release_commands
359
390
  end
360
391
  end
361
392
 
393
+ # Request interception events take the priority lane so they aren't delayed behind the others.
394
+ def dispatch(message)
395
+ method, session_id, params = message.values_at("method", "sessionId", "params")
396
+ lane = INTERRUPTIONS.include?(method) ? :priority : :regular
397
+ @dispatcher.publish(SessionClient.event_name(method, session_id), params, lane: lane)
398
+ end
399
+
362
400
  # Nothing is going to answer the commands still in flight once the socket
363
401
  # is gone, release them instead of making each wait out its timeout.
364
- def release_pendings
365
- @pendings.each_value { |pending| pending.try_set(nil) }
402
+ def release_commands
403
+ @responses.close
366
404
  end
367
405
 
368
406
  def dead_browser_error
@@ -370,7 +408,7 @@ module Ferrum
370
408
  end
371
409
 
372
410
  # Locked so two concurrent commands never share an id and read each
373
- # other's responses from @pendings.
411
+ # other's responses from @responses.
374
412
  def next_command_id
375
413
  @command_id_mutex.synchronize { @command_id += 1 }
376
414
  end
@@ -0,0 +1,171 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ferrum
4
+ module Concurrency
5
+ #
6
+ # A thread-safe hash that threads can wait on: {#await} returns the value of a key as soon as it is stored, at
7
+ # once if it already is, so it doesn't matter whether the waiter or the writer comes first.
8
+ #
9
+ # A writer that only answers waiters, like a response to a command that may have nobody waiting, uses
10
+ # {#expect} on the waiting side and {#fulfill} on the writing side: values nobody expects are dropped.
11
+ #
12
+ # @example
13
+ # map = Ferrum::Concurrency::AwaitableMap.new
14
+ # Thread.new { map["a"] = 1 }
15
+ # map.await("a", 5) # => 1
16
+ #
17
+ class AwaitableMap
18
+ def initialize
19
+ @mutex = Mutex.new
20
+ @condition = ConditionVariable.new
21
+ @map = {}
22
+ @expected = {}
23
+ @closed = false
24
+ end
25
+
26
+ #
27
+ # @param [Object] key
28
+ #
29
+ # @return [Object, nil]
30
+ #
31
+ def [](key)
32
+ @mutex.synchronize { @map[key] }
33
+ end
34
+
35
+ #
36
+ # Stores the value and wakes the threads waiting for the key.
37
+ #
38
+ # @param [Object] key
39
+ #
40
+ # @param [Object] value
41
+ #
42
+ # @return [Object]
43
+ #
44
+ def []=(key, value)
45
+ @mutex.synchronize do
46
+ @map[key] = value
47
+ @condition.broadcast
48
+ end
49
+ value
50
+ end
51
+
52
+ #
53
+ # Announces that a thread is going to wait for the key, so {#fulfill} keeps its value.
54
+ #
55
+ # @param [Object] key
56
+ #
57
+ # @return [Object]
58
+ # The key.
59
+ #
60
+ def expect(key)
61
+ @mutex.synchronize { @expected[key] = true }
62
+ key
63
+ end
64
+
65
+ #
66
+ # @param [Object] key
67
+ #
68
+ # @return [Boolean]
69
+ #
70
+ def expecting?(key)
71
+ @mutex.synchronize { @expected.key?(key) }
72
+ end
73
+
74
+ #
75
+ # Stores the value and wakes the waiters, only if the key was expected.
76
+ #
77
+ # @param [Object] key
78
+ #
79
+ # @param [Object] value
80
+ #
81
+ # @return [Boolean]
82
+ # Whether the value was stored.
83
+ #
84
+ def fulfill(key, value)
85
+ @mutex.synchronize do
86
+ next false unless @expected.key?(key)
87
+
88
+ @map[key] = value
89
+ @condition.broadcast
90
+ true
91
+ end
92
+ end
93
+
94
+ #
95
+ # Removes the key and the expectation of it.
96
+ #
97
+ # @param [Object] key
98
+ #
99
+ # @return [Object, nil]
100
+ # The removed value.
101
+ #
102
+ def delete(key)
103
+ @mutex.synchronize do
104
+ @expected.delete(key)
105
+ @map.delete(key)
106
+ end
107
+ end
108
+
109
+ #
110
+ # Wakes every waiter for good: once closed, {#await} doesn't block and returns what is stored.
111
+ #
112
+ # @return [void]
113
+ #
114
+ def close
115
+ @mutex.synchronize do
116
+ @closed = true
117
+ @condition.broadcast
118
+ end
119
+ end
120
+
121
+ #
122
+ # @param [Object] key
123
+ #
124
+ # @return [Boolean]
125
+ #
126
+ def key?(key)
127
+ @mutex.synchronize { @map.key?(key) }
128
+ end
129
+
130
+ #
131
+ # @return [Hash]
132
+ # A copy of the stored pairs.
133
+ #
134
+ def to_h
135
+ @mutex.synchronize { @map.dup }
136
+ end
137
+
138
+ #
139
+ # @return [Array<Object>]
140
+ #
141
+ def values
142
+ @mutex.synchronize { @map.values }
143
+ end
144
+
145
+ #
146
+ # Blocks until the key is stored or the timeout is reached.
147
+ #
148
+ # @param [Object] key
149
+ #
150
+ # @param [Numeric, Deadline] timeout
151
+ #
152
+ # @return [Object, nil]
153
+ # The value, `nil` when the timeout is reached.
154
+ #
155
+ def await(key, timeout)
156
+ deadline = Deadline.wrap(timeout)
157
+ @mutex.synchronize do
158
+ @condition.wait(@mutex, deadline.remaining) until @map.key?(key) || @closed || deadline.expired?
159
+ @map[key]
160
+ end
161
+ end
162
+
163
+ #
164
+ # @return [String]
165
+ #
166
+ def inspect
167
+ @mutex.synchronize { @map.inspect }
168
+ end
169
+ end
170
+ end
171
+ end