tryAcquire method
Fills the bucket for the time since updatedMicros, then takes
permits when they are there. A clock that went back fills nothing.
Throws an ArgumentError for a limit that is not valid (RateLimit.requireValid), before anything changes: the bucket is as it was.
Implementation
RateLimitDecision tryAcquire(
RateLimit limit,
int nowMicros, {
int permits = 1,
}) {
final rate = limit.refillPerSecond;
final elapsed = nowMicros > updatedMicros ? nowMicros - updatedMicros : 0;
final filled = tokens + elapsed * rate / Duration.microsecondsPerSecond;
tokens = filled > limit.capacity ? limit.capacity.toDouble() : filled;
updatedMicros = nowMicros;
if (tokens >= permits) {
tokens -= permits;
return RateLimitDecision(allowed: true, remaining: tokens.floor());
}
return RateLimitDecision(
allowed: false,
remaining: tokens.floor(),
retryAfter: Duration(
microseconds: ((permits - tokens) / rate * 1e6).ceil(),
),
);
}