|
| 1 | +require 'httpx' |
| 2 | +require 'json' |
| 3 | +require 'logger' |
| 4 | + |
| 5 | +class CommandExecutor |
| 6 | + attr_reader :logger, :client_uuid, :endpoint_url |
| 7 | + REACTOR_URL = ENV['MOCKSI_REACTOR_URL'] || "https://crowllectordb.onrender.com/api/v1/reactor" |
| 8 | + |
| 9 | + def initialize(logger, client_uuid) |
| 10 | + @logger = logger |
| 11 | + @client_uuid = client_uuid |
| 12 | + @endpoint_url = REACTOR_URL |
| 13 | + end |
| 14 | + |
| 15 | + def execute_command(command, params) |
| 16 | + request_body = build_request_body(command, params) |
| 17 | + response = send_request(request_body) |
| 18 | + |
| 19 | + if response.nil? |
| 20 | + logger.error "Failed to execute command due to a request error." |
| 21 | + elsif response.is_a?(HTTPX::ErrorResponse) |
| 22 | + logger.error "HTTPX Error: #{response.error.message}" |
| 23 | + elsif response.status == 200 |
| 24 | + process_response(response) |
| 25 | + else |
| 26 | + logger.error "Command execution failed. Status: #{response.status}, Body: #{response.body}" |
| 27 | + end |
| 28 | + end |
| 29 | + |
| 30 | + private |
| 31 | + |
| 32 | + def build_request_body(command, params) |
| 33 | + { |
| 34 | + client_id: client_uuid, |
| 35 | + command: command, |
| 36 | + instructions: params.join(' ') |
| 37 | + }.to_json |
| 38 | + end |
| 39 | + |
| 40 | + def send_request(request_body) |
| 41 | + logger.info "sending request to #{endpoint_url}" |
| 42 | + logger.info "request body: #{request_body}" |
| 43 | + HTTPX.post(endpoint_url, headers: { "Content-Type" => "application/json", "x-client-id" => client_uuid }, body: request_body) |
| 44 | + rescue => e |
| 45 | + logger.error "Failed to send request: #{e.message}" |
| 46 | + nil |
| 47 | + end |
| 48 | + |
| 49 | + def process_response(response) |
| 50 | + result = JSON.parse(response.body) |
| 51 | + log_command_result(result) |
| 52 | + rescue JSON::ParserError => e |
| 53 | + logger.error "Failed to parse response JSON: #{e.message}" |
| 54 | + end |
| 55 | + |
| 56 | + def log_command_result(result) |
| 57 | + if result['result'] == 'error' |
| 58 | + logger.error "Error during command execution: #{result['message']}" |
| 59 | + else |
| 60 | + logger.info "Command executed successfully. #{result}" |
| 61 | + end |
| 62 | + end |
| 63 | +end |
0 commit comments