attemptSync method

RateLimitResult attemptSync(
  1. String key,
  2. int maxAttempts,
  3. Duration decay, {
  4. int cost = 1,
})

Synchronous variant (used by the coordinator service). cost counts several hits at once; the attempt is all-or-nothing.

Implementation

RateLimitResult attemptSync(
  String key,
  int maxAttempts,
  Duration decay, {
  int cost = 1,
}) {
  final now = _clock().millisecondsSinceEpoch;
  final bucket = _bucket(key, decay, now);
  final resetAt = DateTime.fromMillisecondsSinceEpoch(
    bucket.resetAtMs,
    isUtc: true,
  );
  if (bucket.hits + cost > maxAttempts) {
    return RateLimitResult(
      allowed: false,
      limit: maxAttempts,
      remaining: 0,
      resetAt: resetAt,
      retryAfter: Duration(milliseconds: bucket.resetAtMs - now),
    );
  }
  bucket.hits += cost;
  return RateLimitResult(
    allowed: true,
    limit: maxAttempts,
    remaining: maxAttempts - bucket.hits,
    resetAt: resetAt,
  );
}