Class: Woods::Notion::RateLimiter
- Inherits:
-
Object
- Object
- Woods::Notion::RateLimiter
- Defined in:
- lib/woods/notion/rate_limiter.rb
Overview
Thread-safe rate limiter for Notion API (3 requests/second default).
Enforces a minimum interval between API calls by sleeping when necessary. Uses a Mutex to ensure thread safety when called from concurrent contexts.
Instance Method Summary collapse
-
#initialize(requests_per_second: 3) ⇒ RateLimiter
constructor
A new instance of RateLimiter.
-
#throttle { ... } ⇒ Object
Execute a block after enforcing the rate limit.
Constructor Details
#initialize(requests_per_second: 3) ⇒ RateLimiter
Returns a new instance of RateLimiter.
18 19 20 21 22 23 24 25 26 |
# File 'lib/woods/notion/rate_limiter.rb', line 18 def initialize(requests_per_second: 3) unless requests_per_second.is_a?(Numeric) && requests_per_second.positive? raise ArgumentError, "requests_per_second must be positive, got #{requests_per_second.inspect}" end @min_interval = 1.0 / requests_per_second @last_request_at = nil @mutex = Mutex.new end |
Instance Method Details
#throttle { ... } ⇒ Object
Execute a block after enforcing the rate limit.
Sleeps if the minimum interval since the last request hasn’t elapsed. Thread-safe — only one request proceeds at a time.
36 37 38 39 40 41 42 43 44 45 |
# File 'lib/woods/notion/rate_limiter.rb', line 36 def throttle raise ArgumentError, 'block required' unless block_given? @mutex.synchronize do wait_for_interval @last_request_at = monotonic_now end yield end |