java.lang.Object
com.irurueta.authserver.authorization.api.web.ratelimit.FixedWindowBuckets

public final class FixedWindowBuckets extends Object
The token buckets of one kind of key (a client address, an e-mail address, an identifier), built on Bucket4j and kept in a Caffeine cache. Each bucket holds the limit of its key and is refilled all at once at the end of every window. The cache is bounded to a number of keys and drops a bucket idle for a whole window (it would be full again anyway). Maintenance runs on the calling thread, so eviction is deterministic and needs no extra thread, and the time of both libraries is read from the injected Clock, so tests can move it. The buckets live in this instance only: several instances each apply the limits on their own.
  • Field Details

    • window

      private final Duration window
      Length of the window a limit is counted in.
    • timeMeter

      private final FixedWindowBuckets.ClockTimeMeter timeMeter
      Time source of the buckets and of the cache.
    • buckets

      private final com.github.benmanes.caffeine.cache.Cache<String,io.github.bucket4j.Bucket> buckets
      Buckets per key.
  • Constructor Details

    • FixedWindowBuckets

      public FixedWindowBuckets(Clock clock, Duration window, int maxTrackedKeys)
      Creates the buckets of one kind of key.
      Parameters:
      clock - source of the current time.
      window - length of the window a limit is counted in.
      maxTrackedKeys - keys tracked at most; the oldest is forgotten first.
  • Method Details

    • tryConsume

      public Optional<Duration> tryConsume(String key, int limit)
      Takes one token from the bucket of a key, creating the bucket on first use.
      Parameters:
      key - the key.
      limit - requests the key may make per window.
      Returns:
      empty when the request is within the limit, else how long until the window ends and the key is accepted again.
    • trackedKeys

      public long trackedKeys()
      Tells how many keys are tracked, after any pending eviction.
      Returns:
      the number of keys.
    • bucket

      private io.github.bucket4j.Bucket bucket(int limit)
      Builds the bucket of a key: the whole limit, refilled at once at the end of every window.
      Parameters:
      limit - requests per window.
      Returns:
      the bucket.