Class: Agent99::TcpMessageClient

Inherits:
Object
  • Object
show all
Defined in:
lib/agent99/tcp_message_client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(agents: {}, logger: Logger.new($stdout)) ⇒ TcpMessageClient

Returns a new instance of TcpMessageClient.



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/agent99/tcp_message_client.rb', line 14

def initialize(
    agents: {},
    logger: Logger.new($stdout)
  )
  @agents             = agents
  @logger             = logger
  @server_socket      = nil
  @client_connections = {}
  @handlers           = {}
  @running            = false
end

Instance Attribute Details

#agentsObject

Returns the value of attribute agents.



12
13
14
# File 'lib/agent99/tcp_message_client.rb', line 12

def agents
  @agents
end

Instance Method Details

#listen_for_messages(queue, request_handler:, response_handler:, control_handler:) ⇒ Object



26
27
28
29
30
31
32
33
34
# File 'lib/agent99/tcp_message_client.rb', line 26

def listen_for_messages(queue, request_handler:, response_handler:, control_handler:)
  @handlers = {
    request:  request_handler,
    response: response_handler,
    control:  control_handler
  }
  
  start_server(queue[:port])
end

#publish(message) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/agent99/tcp_message_client.rb', line 36

def publish(message)
  target = message.dig(:header, :to_uuid)
  return unless target

  agent_info = agents(target)
  return unless agent_info

  socket = connect_to_agent(agent_info[:ip], agent_info[:port])
  return unless socket

  begin
    socket.puts(message.to_json)
    true
  
  rescue StandardError => e
    @logger.error("Failed to send message: #{e.message}")
    false
  
  ensure
    socket.close unless socket.closed?
  end
end

#stopObject



59
60
61
62
63
64
# File 'lib/agent99/tcp_message_client.rb', line 59

def stop
  @running = false
  @server_socket&.close
  @client_connections.each_value(&:close)
  @client_connections.clear
end