Class: Ferrum::Client::Subscriber

Inherits:
Object
  • Object
show all
Defined in:
lib/ferrum/client/subscriber.rb

Overview

Dispatches incoming CDP events to registered callbacks. Messages are queued and processed on dedicated threads, with Fetch.requestPaused and Fetch.authRequired given priority so request interception isn't delayed behind other events.

Constant Summary collapse

INTERRUPTIONS =
%w[Fetch.requestPaused Fetch.authRequired].freeze

Instance Method Summary collapse

Constructor Details

#initializeSubscriber

Returns a new instance of Subscriber.



14
15
16
17
18
19
20
# File 'lib/ferrum/client/subscriber.rb', line 14

def initialize
  @regular = Queue.new
  @priority = Queue.new
  @on = Concurrent::Hash.new

  start
end

Instance Method Details

#<<(message) ⇒ void

This method returns an undefined value.

Enqueues an incoming CDP message for dispatch to subscribers. Fetch.requestPaused/Fetch.authRequired messages jump the regular queue so request interception isn't delayed behind other events.

Parameters:

  • message (Hash)

    The raw CDP message, as parsed from the websocket.



32
33
34
35
36
37
38
# File 'lib/ferrum/client/subscriber.rb', line 32

def <<(message)
  if INTERRUPTIONS.include?(message["method"])
    @priority.push(message)
  else
    @regular.push(message)
  end
end

#clear(session_id:) ⇒ void

This method returns an undefined value.

Removes all callbacks registered for a given session.

Parameters:

  • session_id (String)

    The session id to match against registered event keys.



102
103
104
# File 'lib/ferrum/client/subscriber.rb', line 102

def clear(session_id:)
  @on.delete_if { |k, _| k.match?(session_id) }
end

#closevoid

This method returns an undefined value.

Stops the regular and priority dispatch threads.



89
90
91
92
# File 'lib/ferrum/client/subscriber.rb', line 89

def close
  @regular_thread&.kill
  @priority_thread&.kill
end

#off(event, id) ⇒ Boolean

Unregisters a callback for a CDP event.

Parameters:

Returns:

  • (Boolean)


67
68
69
70
# File 'lib/ferrum/client/subscriber.rb', line 67

def off(event, id)
  @on[event].delete_at(id)
  true
end

#on(event, &block) ⇒ Integer

Registers a callback for a CDP event.

Parameters:

Returns:

  • (Integer)

    The callback's index within the event's callback list, used to unsubscribe via #off.



50
51
52
53
54
# File 'lib/ferrum/client/subscriber.rb', line 50

def on(event, &block)
  @on[event] ||= Concurrent::Array.new
  @on[event] << block
  @on[event].index(block)
end

#subscribed?(event) ⇒ Boolean

Whether there's at least one callback registered for the event.

Parameters:

Returns:

  • (Boolean)


80
81
82
# File 'lib/ferrum/client/subscriber.rb', line 80

def subscribed?(event)
  @on.key?(event)
end