tryConsume method

Future<bool> tryConsume()

Attempts to consume 1 token.

Returns true if the action is allowed (token consumed), or false if rate limited.

This method automatically handles token refill based on elapsed time since the last check. Attempts to consume 1 token atomically.

Implementation

Future<bool> tryConsume() => _lock.synchronized(() async {
      final now = DateTime.now();
      final tokens = await _tokenCount.getOrFallback(maxTokens.toDouble());
      final last = await _lastRefill.getOrFallback(now);

      final elapsedMs = now.difference(last).inMilliseconds;
      final refillRatePerMs = maxTokens / refillDuration.inMilliseconds;
      final refilledTokens = tokens + (elapsedMs * refillRatePerMs);
      final newTokenCount = min(maxTokens.toDouble(), refilledTokens);

      if (newTokenCount >= 1) {
        await _tokenCount.set(newTokenCount - 1);
        await _lastRefill.set(now);
        return true;
      } else {
        await _tokenCount.set(newTokenCount);
        await _lastRefill.set(now);
        return false;
      }
    });