Module: RunApi::Core::Polling

Defined in:
lib/runapi/core/polling.rb

Constant Summary collapse

ACTIVE_STATUSES =
%w[pending processing].freeze

Class Method Summary collapse

Class Method Details

.poll_until_complete(options = PollingOptions.new) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/runapi/core/polling.rb', line 8

def self.poll_until_complete(options = PollingOptions.new)
  deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + options.max_wait

  loop do
    response = yield
    status = value_for(response, "status").to_s.downcase

    return response if status == "completed"

    if status == "failed"
      message = value_for(response, "error") || "Task failed"
      raise TaskFailedError.new(message, details: details_for(response))
    end

    if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline
      raise TaskTimeoutError, "Task polling timed out after #{options.max_wait}s"
    end

    unless ACTIVE_STATUSES.include?(status)
      raise TaskFailedError.new("Unknown task status: #{status}", details: details_for(response))
    end

    sleep(options.poll_interval)
  end
end