Class: NewlineHw::StreamProcessor

Inherits:
Object
  • Object
show all
Defined in:
lib/newline_hw/stream_processor.rb

Constant Summary collapse

SHUTDOWN_PAUSE =

Don’t instant shutdown wait for messages to clear, as chrome is much faster to trigger disconnect callback over wait for succesful messages.

0.5

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(stdin, stdout, opts = {}) ⇒ StreamProcessor

Returns a new instance of StreamProcessor.



9
10
11
12
13
# File 'lib/newline_hw/stream_processor.rb', line 9

def initialize(stdin, stdout, opts = {})
  @logger = opts[:logger]
  @stdin = stdin
  @stdout = stdout
end

Instance Attribute Details

#loggerObject (readonly)

Returns the value of attribute logger.



8
9
10
# File 'lib/newline_hw/stream_processor.rb', line 8

def logger
  @logger
end

Class Method Details

.read_native_json_message(io) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/newline_hw/stream_processor.rb', line 36

def self.read_native_json_message(io)
  # Read signed integer with a max length of 4 bytes.
  text_length_bytes = io.read(4)
  return unless text_length_bytes

  # Unpack bytes in a ruby int.
  text_length = text_length_bytes.unpack("i")[0]
  text = io.read(text_length)
  JSON.parse(text)
rescue JSON::ParserError
  puts text
end

.write_message(io, msg) ⇒ Object



29
30
31
32
33
34
# File 'lib/newline_hw/stream_processor.rb', line 29

def self.write_message(io, msg)
  msg = msg.to_json
  io.write [msg.length].pack("I")
  io.write(msg)
  io.flush
end

Instance Method Details

#on_message(&block) ⇒ Object



15
16
17
18
19
20
21
22
# File 'lib/newline_hw/stream_processor.rb', line 15

def on_message(&block)
  loop do
    msg = self.class.read_native_json_message(@stdin)
    sleep(SHUTDOWN_PAUSE) && exit(0) unless msg
    @logger.debug "Receiving Message #{msg} of size:#{msg.length}"
    instance_exec(msg, &block)
  end
end

#send_message(message) ⇒ Object



24
25
26
27
# File 'lib/newline_hw/stream_processor.rb', line 24

def send_message(message)
  @logger.debug "Sending Message: #{message}"
  self.class.write_message(@stdout, message)
end