class NewlineHw::StreamProcessor

Constants

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.

Attributes

logger[R]

Public Class Methods

new(stdin, stdout, opts = {}) click to toggle source
# File lib/newline_hw/stream_processor.rb, line 9
def initialize(stdin, stdout, opts = {})
  @logger = opts[:logger]
  @stdin = stdin
  @stdout = stdout
end
read_native_json_message(io) click to toggle source
# 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) click to toggle source
# 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

Public Instance Methods

on_message(&block) click to toggle source
# 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) click to toggle source
# 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