Class: Datadog::Core::Utils::OnlyOnceSuccessful

Inherits:
OnlyOnce
  • Object
show all
Defined in:
lib/datadog/core/utils/only_once_successful.rb

Overview

Helper class to execute something with only one successful execution.

If limit is not provided to the constructor, run will execute the block an unlimited number of times until the block indicates that it executed successfully by returning a truthy value. After a block executes successfully, subsequent run calls will not invoke the block.

If a non-zero limit is provided to the constructor, run will execute the block up to that many times, and will mark the instance of OnlyOneSuccessful as failed if none of the executions succeeded.

One consumer of this class is sending the app-started telemetry event.

Successful execution is determined by the return value of the block: any truthy value is considered success.

This class is thread-safe (however, instances of it must also be created in a thread-safe manner).

Note: In its current state, this class is not Ractor-safe. In github.com/DataDog/dd-trace-rb/pull/1398#issuecomment-797378810 we have a discussion of alternatives, including an alternative implementation that is Ractor-safe once spent.

Instance Method Summary collapse

Methods inherited from OnlyOnce

#ran?

Constructor Details

#initialize(limit = 0) ⇒ OnlyOnceSuccessful

Returns a new instance of OnlyOnceSuccessful.



32
33
34
35
36
37
38
# File 'lib/datadog/core/utils/only_once_successful.rb', line 32

def initialize(limit = 0)
  super()

  @limit = limit
  @failed = false
  @retries = 0
end

Instance Method Details

#failed?Boolean

Returns:

  • (Boolean)


60
61
62
# File 'lib/datadog/core/utils/only_once_successful.rb', line 60

def failed?
  @mutex.synchronize { @ran_once && @failed }
end

#runObject



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/datadog/core/utils/only_once_successful.rb', line 40

def run
  @mutex.synchronize do
    return if @ran_once

    result = yield
    @ran_once = !!result

    if !@ran_once && limited?
      @retries += 1
      check_limit!
    end

    result
  end
end

#success?Boolean

Returns:

  • (Boolean)


56
57
58
# File 'lib/datadog/core/utils/only_once_successful.rb', line 56

def success?
  @mutex.synchronize { @ran_once && !@failed }
end