Class: Html2rss::RequestService::Budget

Inherits:
Object
  • Object
show all
Defined in:
lib/html2rss/request_service/budget.rb

Overview

Tracks how many outbound requests a single feed build may still perform.

Instance Method Summary collapse

Constructor Details

#initialize(max_requests:, total_timeout_seconds: nil) ⇒ Budget

Returns a new instance of Budget.

Parameters:

  • max_requests (Integer)

    the maximum number of requests allowed

  • total_timeout_seconds (Integer, nil) (defaults to: nil)

    the total timeout for the feed build



12
13
14
15
16
17
18
19
20
21
# File 'lib/html2rss/request_service/budget.rb', line 12

def initialize(max_requests:, total_timeout_seconds: nil)
  unless max_requests.is_a?(Integer) && max_requests.positive?
    raise ArgumentError, 'max_requests must be positive'
  end

  @remaining = max_requests
  @start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  @total_timeout_seconds = total_timeout_seconds
  @mutex = Mutex.new
end

Instance Method Details

#consume!Integer

Consumes one request from the budget.

Returns:

  • (Integer)

    remaining request count after consumption

Raises:



28
29
30
31
32
33
34
# File 'lib/html2rss/request_service/budget.rb', line 28

def consume!
  @mutex.synchronize do
    raise RequestBudgetExceeded, 'Request budget exhausted' if @remaining.zero?

    @remaining -= 1
  end
end

#remainingInteger

Returns requests still available.

Returns:

  • (Integer)

    requests still available



38
39
40
# File 'lib/html2rss/request_service/budget.rb', line 38

def remaining
  @mutex.synchronize { @remaining }
end

#remaining_timeout_secondsFloat?

Returns the remaining timeout in seconds, or nil if not tracked.

Returns:

  • (Float, nil)

    the remaining timeout in seconds, or nil if not tracked



44
45
46
47
48
49
50
# File 'lib/html2rss/request_service/budget.rb', line 44

def remaining_timeout_seconds
  return unless @total_timeout_seconds

  elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - @start_time
  remaining = @total_timeout_seconds - elapsed
  [remaining, 0.0].max
end