Method: RunLoop.send_command

Defined in:
lib/run_loop.rb

.send_command(run_loop, cmd, options = {timeout: 60}, num_retries = 0, last_error = nil) ⇒ Object



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/run_loop.rb', line 115

def self.send_command(run_loop, cmd, options={timeout: 60}, num_retries=0, last_error=nil)
  if num_retries > 3
    if last_error
      raise last_error
    else
      raise "Max retries exceeded #{num_retries} > 3. No error recorded."
    end
  end

  if options.is_a?(Numeric)
    options = {timeout: options}
  end

  if not cmd.is_a?(String)
    raise "Illegal command #{cmd} (must be a string)"
  end

  if not options.is_a?(Hash)
    raise "Illegal options #{options} (must be a Hash (or number for compatibility))"
  end

  timeout = options[:timeout] || 60
  logger = options[:logger]
  interrupt_retry_timeout = options[:interrupt_retry_timeout] || 25

  expected_index = run_loop[:index]
  result = nil
  begin
    expected_index = Core.write_request(run_loop, cmd, logger)
  rescue RunLoop::WriteFailedError, Errno::EINTR => write_error
    # Attempt recover from interrupt by attempting to read result (assuming write went OK)
    # or retry if attempted read result fails
    run_loop[:index] = expected_index # restore expected index in case it changed
    log_info(logger, "Core.write_request failed: #{write_error}. Attempting recovery...")
    log_info(logger, "Attempting read in case the request was received... Please wait (#{interrupt_retry_timeout})...")
    begin
      Timeout::timeout(interrupt_retry_timeout, TimeoutError) do
        result = Core.read_response(run_loop, expected_index)
      end
      # Update run_loop expected index since we succeeded in reading the index
      run_loop[:index] = expected_index + 1
      log_info(logger, "Did read response for interrupted request of index #{expected_index}... Proceeding.")
      return result
    rescue TimeoutError => _
      log_info(logger, "Read did not result in a response for index #{expected_index}... Retrying send_command...")
      return send_command(run_loop, cmd, options, num_retries+1, write_error)
    end
  end


  begin
    Timeout::timeout(timeout, TimeoutError) do
      result = Core.read_response(run_loop, expected_index)
    end
  rescue TimeoutError => _
    raise TimeoutError, "Time out waiting for UIAutomation run-loop for command #{cmd}. Waiting for index:#{expected_index}"
  end

  result
end