Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

Markdown · 1.7 KiB · at 9ba9e6b

Write createLimiter, a token-bucket rate limiter that reads time from an injected clock.

createLimiter(config, now):

  • config.capacity: the most tokens the bucket can hold. Must be a finite number greater than 0.
  • config.refillPerSecond: tokens added per second. Must be a finite number, 0 or greater (0 means the bucket never refills).
  • now() returns the current time in milliseconds. The limiter reads it once at creation and once at the start of every method call.
  • An invalid config fails at creation with { kind: "invalid_config" }.

Behaviour of the returned limiter:

  • The bucket starts full at creation time.
  • Refill is continuous: fractional tokens accumulate at refillPerSecond, and the bucket never holds more than capacity.
  • Time never runs backwards inside the limiter. If now() returns a time earlier than the latest time already seen, no tokens are added for that call, and later refills are measured from the latest time seen.
  • tryTake(n): n must be a positive integer; for any other n it returns false and changes nothing. If at least n tokens are available it removes n and returns true; otherwise it returns false and removes nothing.
  • available(): the current number of tokens, rounded down to an integer.
  • retryAfterMs(n): how many milliseconds until tryTake(n) would succeed, assuming nothing else takes tokens meanwhile. It is 0 when tryTake(n) would succeed right now; otherwise the time until enough tokens have refilled, rounded up to a whole millisecond. It is absent when tryTake(n) can never succeed: n is not a positive integer, n is greater than capacity, or more tokens are needed and the bucket never refills. It never consumes tokens.