Class FixedWindowBuckets
java.lang.Object
com.irurueta.authserver.authorization.api.web.ratelimit.FixedWindowBuckets
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.-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprivate static final recordBucket4j and Caffeine time source backed by aClock. -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate final com.github.benmanes.caffeine.cache.Cache<String, io.github.bucket4j.Bucket> Buckets per key.private final FixedWindowBuckets.ClockTimeMeterTime source of the buckets and of the cache.private final DurationLength of the window a limit is counted in. -
Constructor Summary
ConstructorsConstructorDescriptionFixedWindowBuckets(Clock clock, Duration window, int maxTrackedKeys) Creates the buckets of one kind of key. -
Method Summary
Modifier and TypeMethodDescriptionprivate io.github.bucket4j.Bucketbucket(int limit) Builds the bucket of a key: the whole limit, refilled at once at the end of every window.longTells how many keys are tracked, after any pending eviction.tryConsume(String key, int limit) Takes one token from the bucket of a key, creating the bucket on first use.
-
Field Details
-
window
Length of the window a limit is counted in. -
timeMeter
Time source of the buckets and of the cache. -
buckets
Buckets per key.
-
-
Constructor Details
-
FixedWindowBuckets
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
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.
-