summaryrefslogtreecommitdiff
path: root/qa/qa/support/retrier.rb
blob: 25dbb42cf6f0314771f773905cb4ff9b8e68506c (plain)
1
2
3
4
5
6
7
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# frozen_string_literal: true

module QA
  module Support
    module Retrier
      extend Repeater

      module_function

      def retry_on_exception(max_attempts: 3, reload_page: nil, sleep_interval: 0.5)
        QA::Runtime::Logger.debug(
          <<~MSG.tr("\n", ' ')
            with retry_on_exception: max_attempts: #{max_attempts};
            reload_page: #{reload_page};
            sleep_interval: #{sleep_interval}
        MSG
        )

        result = nil
        repeat_until(
          max_attempts: max_attempts,
          reload_page: reload_page,
          sleep_interval: sleep_interval,
          retry_on_exception: true
        ) do
          result = yield

          # This method doesn't care what the return value of the block is.
          # We set it to `true` so that it doesn't repeat if there's no exception
          true
        end
        QA::Runtime::Logger.debug("ended retry_on_exception")

        result
      end

      def retry_until(max_attempts: nil, max_duration: nil, reload_page: nil, sleep_interval: 0, raise_on_failure: true, retry_on_exception: false, log: true)
        # For backwards-compatibility
        max_attempts = 3 if max_attempts.nil? && max_duration.nil?

        if log
          start_msg ||= ["with retry_until:"]
          start_msg << "max_attempts: #{max_attempts};" if max_attempts
          start_msg << "max_duration: #{max_duration};" if max_duration
          start_msg << "reload_page: #{reload_page}; sleep_interval: #{sleep_interval}; raise_on_failure: #{raise_on_failure}; retry_on_exception: #{retry_on_exception}"
          QA::Runtime::Logger.debug(start_msg.join(' '))
        end

        result = nil
        repeat_until(
          max_attempts: max_attempts,
          max_duration: max_duration,
          reload_page: reload_page,
          sleep_interval: sleep_interval,
          raise_on_failure: raise_on_failure,
          retry_on_exception: retry_on_exception,
          log: log
        ) do
          result = yield
        end
        QA::Runtime::Logger.debug("ended retry_until")

        result
      end
    end
  end
end