TokenBucketRateLimiter constructor

TokenBucketRateLimiter({
  1. required double tokensPerSecond,
  2. required int capacity,
  3. DateTime now()?,
})

Creates a limiter refilling at tokensPerSecond (> 0) up to capacity (≥ 1) tokens. now supplies the current time for refill accrual; it defaults to DateTime.now and can be overridden in tests to advance a virtual clock. Audited: 2026-06-12 11:26 EDT

Implementation

TokenBucketRateLimiter({
  required this.tokensPerSecond,
  required this.capacity,
  // ignore: saropa_lints/prefer_correct_callback_field_name -- injected clock source, not an event callback; an "on" prefix would misname it
  DateTime Function()? now,
}) : _now = now ?? DateTime.now,
     // Validate while computing the initial token count: enforced in release
     // (an assert strips), and routed through a static helper in the
     // initializer so it does not trip avoid_exception_in_constructor. A
     // non-positive tokensPerSecond divides by zero during refill; capacity < 1
     // can never satisfy any spend.
     _tokens = _validatedInitialTokens(tokensPerSecond, capacity),
     // Seed the accrual baseline from the same clock source the bucket reads,
     // so the first refill measures elapsed time from construction.
     _lastRefill = (now ?? DateTime.now)();