Class: RosettAi::DBus::RateLimiter

Inherits:
Object
  • Object
show all
Defined in:
lib/rosett_ai/dbus/rate_limiter.rb

Overview

Token bucket rate limiter for D-Bus method calls.

Provides application-level rate limiting to prevent resource exhaustion from rapid D-Bus method invocations. Each method type can have its own rate limit.

Thread-safe: uses mutex for bucket state.

Examples:

limiter = RateLimiter.new(rate: 10, burst: 20)
if limiter.allow?
  # process request
else
  raise RateLimitExceeded
end

Defined Under Namespace

Classes: RateLimitExceeded

Constant Summary collapse

DEFAULT_RATE =

Default limits (requests per second / burst capacity)

10
DEFAULT_BURST =
20

Instance Method Summary collapse

Constructor Details

#initialize(rate: DEFAULT_RATE, burst: DEFAULT_BURST) ⇒ RateLimiter

Returns a new instance of RateLimiter.

Parameters:

  • rate (Numeric) (defaults to: DEFAULT_RATE)

    tokens added per second

  • burst (Integer) (defaults to: DEFAULT_BURST)

    maximum bucket capacity



38
39
40
41
42
43
44
# File 'lib/rosett_ai/dbus/rate_limiter.rb', line 38

def initialize(rate: DEFAULT_RATE, burst: DEFAULT_BURST)
  @rate = rate.to_f
  @burst = burst
  @tokens = burst.to_f
  @last_update = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  @mutex = Mutex.new
end

Instance Method Details

#allow?Boolean

Check if a request is allowed and consume a token if so.

Returns:

  • (Boolean)

    true if request is allowed



49
50
51
52
53
54
55
56
57
58
59
# File 'lib/rosett_ai/dbus/rate_limiter.rb', line 49

def allow?
  @mutex.synchronize do
    refill_tokens
    if @tokens >= 1.0
      @tokens -= 1.0
      true
    else
      false
    end
  end
end

#available_tokensFloat

Current available tokens (for monitoring/debugging).

Returns:

  • (Float)

    current token count



72
73
74
75
76
77
# File 'lib/rosett_ai/dbus/rate_limiter.rb', line 72

def available_tokens
  @mutex.synchronize do
    refill_tokens
    @tokens
  end
end

#consume!(method_name = nil) ⇒ Object

Consume a token or raise RateLimitExceeded.

Parameters:

  • method_name (String, nil) (defaults to: nil)

    optional method name for error message

Raises:



65
66
67
# File 'lib/rosett_ai/dbus/rate_limiter.rb', line 65

def consume!(method_name = nil)
  raise RateLimitExceeded, method_name unless allow?
end