summaryrefslogtreecommitdiff
path: root/qa/qa/support/retrier.rb
blob: aa568d633fc7d0569277f1c6f5e097487aa7f3d6 (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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# 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, log: true)
        if log
          msg = ["with retry_on_exception: max_attempts: #{max_attempts}"]
          msg << "reload_page: #{reload_page}" if reload_page
          msg << "sleep_interval: #{sleep_interval}"
          QA::Runtime::Logger.debug(msg.join('; '))
        end

        result = nil
        repeat_until(
          max_attempts: max_attempts,
          reload_page: reload_page,
          sleep_interval: sleep_interval,
          retry_on_exception: true,
          log: log
        ) 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") if log

        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.push(*[
                           "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") if log

        result
      end
    end
  end
end