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 thancapacity. - 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):nmust be a positive integer; for any othernit returnsfalseand changes nothing. If at leastntokens are available it removesnand returnstrue; otherwise it returnsfalseand removes nothing.available(): the current number of tokens, rounded down to an integer.retryAfterMs(n): how many milliseconds untiltryTake(n)would succeed, assuming nothing else takes tokens meanwhile. It is0whentryTake(n)would succeed right now; otherwise the time until enough tokens have refilled, rounded up to a whole millisecond. It is absent whentryTake(n)can never succeed:nis not a positive integer,nis greater thancapacity, or more tokens are needed and the bucket never refills. It never consumes tokens.