lib/puppeteer/cdp_session.rb in puppeteer-ruby-0.0.22 vs lib/puppeteer/cdp_session.rb in puppeteer-ruby-0.0.23

- old
+ new

@@ -7,11 +7,11 @@ # @param {!Connection} connection # @param {string} targetType # @param {string} sessionId def initialize(connection, target_type, session_id) - @callbacks = {} + @callbacks = Concurrent::Hash.new @connection = connection @target_type = target_type @session_id = session_id end @@ -29,27 +29,31 @@ # @returns [Future<Hash>] def async_send_message(method, params = {}) if !@connection raise Error.new("Protocol error (#{method}): Session closed. Most likely the #{@target_type} has been closed.") end - id = @connection.raw_send(message: { sessionId: @session_id, method: method, params: params }) + promise = resolvable_future - callback = Puppeteer::Connection::MessageCallback.new(method: method, promise: promise) - @callbacks[id] = callback + + @connection.generate_id do |id| + @callbacks[id] = Puppeteer::Connection::MessageCallback.new(method: method, promise: promise) + @connection.raw_send(id: id, message: { sessionId: @session_id, method: method, params: params }) + end + promise end # @param {{id?: number, method: string, params: Object, error: {message: string, data: any}, result?: *}} object def handle_message(message) if message['id'] if callback = @callbacks.delete(message['id']) callback_with_message(callback, message) else - raise Error.new("unknown id: #{id}") + raise Error.new("unknown id: #{message['id']}") end else - emit_event message['method'], message['params'] + emit_event(message['method'], message['params']) end end private def callback_with_message(callback, message) if message['error'] @@ -77,10 +81,10 @@ method: callback.method, error_message: 'Target Closed.')) end @callbacks.clear @connection = nil - emit_event 'Events.CDPSession.Disconnected' + emit_event(CDPSessionEmittedEvents::Disconnected) end # @param event_name [String] def on(event_name, &block) add_event_listener(event_name, &block)