Class: ProcessBot::ClientSocket

Inherits:
Object
  • Object
show all
Defined in:
lib/process_bot/client_socket.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options:) ⇒ ClientSocket

Returns a new instance of ClientSocket.



7
8
9
# File 'lib/process_bot/client_socket.rb', line 7

def initialize(options:)
  @options = options
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



5
6
7
# File 'lib/process_bot/client_socket.rb', line 5

def options
  @options
end

Instance Method Details

#clientObject



11
12
13
14
15
16
# File 'lib/process_bot/client_socket.rb', line 11

def client
  return @client if @client

  logger.logs "Connecting to process on port #{options.fetch(:port)}"
  @client = Socket.tcp("localhost", options.fetch(:port).to_i, connect_timeout: 2)
end

#closeObject



18
19
20
# File 'lib/process_bot/client_socket.rb', line 18

def close
  client.close
end

#loggerObject



22
23
24
# File 'lib/process_bot/client_socket.rb', line 22

def logger
  @logger ||= ProcessBot::Logger.new(options: options)
end

#send_command(data) ⇒ Object

rubocop:disable Metrics/AbcSize



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/process_bot/client_socket.rb', line 26

def send_command(data) # rubocop:disable Metrics/AbcSize
  logger.logs "Sending: #{data}"
  begin
    client.puts(JSON.generate(data))
    loop do
      response_raw = client.gets
      return :nil if response_raw.nil?

      response = JSON.parse(response_raw)

      case response.fetch("type")
      when "log"
        write_log_output(response)
      when "success"
        return :success
      when "error"
        error = RuntimeError.new("Command raised an error: #{response.fetch("message")}")
        error.set_backtrace(response.fetch("backtrace") + Thread.current.backtrace)

        raise error
      else
        raise "Unknown response type: #{response.fetch("type")}"
      end
    end
  rescue Errno::ECONNRESET, Errno::EPIPE
    :nil
  end
end

#write_log_output(response) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/process_bot/client_socket.rb', line 55

def write_log_output(response)
  output = response["output"].to_s
  stream = response.fetch("stream", "stdout")

  if stream == "stderr"
    $stderr.print output
    $stderr.flush
  else
    $stdout.print output
    $stdout.flush
  end
end