Class: XRay::Reservoir

Inherits:
Object
  • Object
show all
Defined in:
lib/aws-xray-sdk/sampling/reservoir.rb

Overview

Centralized thread-safe reservoir which holds fixed sampling quota for the current instance, borrowed count and TTL.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeReservoir

Returns a new instance of Reservoir.



10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/aws-xray-sdk/sampling/reservoir.rb', line 10

def initialize
  @quota = nil
  @ttl = nil

  @this_sec = 0
  @taken_this_sec = 0
  @borrowed_this_sec = 0

  @report_interval = 1
  @report_elapsed = 0

  @lock = Mutex.new
end

Instance Attribute Details

#quotaObject (readonly)

Returns the value of attribute quota.



8
9
10
# File 'lib/aws-xray-sdk/sampling/reservoir.rb', line 8

def quota
  @quota
end

#ttlObject (readonly)

Returns the value of attribute ttl.



8
9
10
# File 'lib/aws-xray-sdk/sampling/reservoir.rb', line 8

def ttl
  @ttl
end

Instance Method Details

#borrow_or_take(now, borrowable) ⇒ Object

Decide whether to borrow or take one quota from the reservoir. Return ‘false` if it can neither borrow nor take. This method is thread-safe.



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/aws-xray-sdk/sampling/reservoir.rb', line 27

def borrow_or_take(now, borrowable)
  @lock.synchronize do
    reset_new_sec(now)
    # Don't borrow if the quota is available and fresh.
    if quota_fresh?(now)
      return SamplingDecision::NOT_SAMPLE if @taken_this_sec >= @quota
      @taken_this_sec += 1
      return SamplingDecision::TAKE
    end

    # Otherwise try to borrow if the quota is not present or expired.
    if borrowable
      return SamplingDecision::NOT_SAMPLE if @borrowed_this_sec >= 1
      @borrowed_this_sec += 1
      return SamplingDecision::BORROW
    end

    # Cannot sample if quota expires and cannot borrow
    SamplingDecision::NOT_SAMPLE
  end
end

#load_target_info(quota:, ttl:, interval:) ⇒ Object



49
50
51
52
53
# File 'lib/aws-xray-sdk/sampling/reservoir.rb', line 49

def load_target_info(quota:, ttl:, interval:)
  @quota = quota unless quota.nil?
  @ttl = ttl.to_i unless ttl.nil?
  @interval = interval / 10 unless interval.nil?
end

#time_to_report?Boolean

Returns:

  • (Boolean)


55
56
57
58
59
60
61
62
63
# File 'lib/aws-xray-sdk/sampling/reservoir.rb', line 55

def time_to_report?
  if @report_elapsed + 1 >= @report_interval
    @report_elapsed = 0
    true
  else
    @report_elapsed += 1
    false
  end
end