Class: Bidi2pdf::Bidi::CommandManager

Inherits:
Object
  • Object
show all
Defined in:
lib/bidi2pdf/bidi/command_manager.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(socket) ⇒ CommandManager

Returns a new instance of CommandManager.



16
17
18
19
20
# File 'lib/bidi2pdf/bidi/command_manager.rb', line 16

def initialize(socket)
  @socket = socket

  @pending_responses = Concurrent::Hash.new
end

Class Method Details

.initialize_counterObject



7
8
9
# File 'lib/bidi2pdf/bidi/command_manager.rb', line 7

def initialize_counter
  @id = Concurrent::AtomicFixnum.new(0)
end

.next_idObject



11
# File 'lib/bidi2pdf/bidi/command_manager.rb', line 11

def next_id = @id.increment

Instance Method Details

#handle_response(data) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/bidi2pdf/bidi/command_manager.rb', line 60

def handle_response(data)
  Bidi2pdf.notification_service.instrument("handle_response.bidi2pdf", data: data) do |instrumentation_payload|
    instrumentation_payload[:error] = data["error"] if data["error"]

    if (id = data["id"])
      instrumentation_payload[:handled] = true
      instrumentation_payload[:id] = id

      if @pending_responses.key?(id)
        @pending_responses[id]&.push(data)

        return true
      end
    end

    instrumentation_payload[:handled] = false

    false
  ensure
    @pending_responses.delete id
  end
end

#send_cmd(cmd, result_queue: nil) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/bidi2pdf/bidi/command_manager.rb', line 22

def send_cmd(cmd, result_queue: nil)
  id = next_id

  Bidi2pdf.notification_service.instrument("send_cmd.bidi2pdf", id: id, cmd: cmd) do |instrumentation_payload|
    init_queue_for id, result_queue

    payload = cmd.as_payload(id)

    instrumentation_payload[:cmd_payload] = payload

    @socket.send(payload.to_json)
  end

  id
end

#send_cmd_and_wait(cmd, timeout: Bidi2pdf.default_timeout, &block) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/bidi2pdf/bidi/command_manager.rb', line 38

def send_cmd_and_wait(cmd, timeout: Bidi2pdf.default_timeout, &block)
  result_queue = Thread::Queue.new

  Bidi2pdf.notification_service.instrument("send_cmd_and_wait.bidi2pdf", cmd: cmd, timeout: timeout) do |instrumentation_payload|
    id = send_cmd(cmd, result_queue: result_queue)

    instrumentation_payload[:id] = id

    response = result_queue.pop(timeout: timeout)

    instrumentation_payload[:response] = response

    raise CmdTimeoutError, "Timeout waiting for response to command ID #{id}" if response.nil?

    raise Bidi2pdf::CmdError.new(cmd, response) if response["error"]

    block ? block.call(response) : response
  ensure
    @pending_responses.delete(id)
  end
end