ratelimit #
ratelimit
new_token_bucket(rate_per_sec: 100.0, burst: 20) creates a thread-safe token bucket. The bucket starts full; allow() consumes one token or returns false when empty. Tokens refill at the positive, finite rate_per_sec, capped at the positive burst capacity. stats() returns the numbers of allowed and denied requests.
The default clock is monotonic with millisecond resolution. new_token_bucket_with_clock(config, now) accepts a millisecond clock for deterministic tests. Backward clock readings do not refill the bucket or move its last-refill timestamp backward. The clock callback runs while the bucket mutex is locked; it must not reenter the same bucket.
fn new_token_bucket #
fn new_token_bucket(config TokenBucketConfig) &TokenBucket
new_token_bucket creates a full bucket reading a monotonic millisecond clock.
fn new_token_bucket_with_clock #
fn new_token_bucket_with_clock(config TokenBucketConfig, now fn () i64) &TokenBucket
new_token_bucket_with_clock is new_token_bucket with an injectable millisecond clock, for deterministic tests and custom time sources.
struct BucketStats #
struct BucketStats {
pub:
allowed u64
denied u64
}
BucketStats counts allowed and denied requests.
struct TokenBucket #
struct TokenBucket {
mut:
mutex &sync.Mutex
rate f64
cap f64
tokens f64
last i64 // millisecond timestamp of the last refill
now fn () i64
allowed u64
denied u64
}
TokenBucket is a thread-safe token-bucket rate limiter: tokens refill at rate_per_sec up to burst, and each allowed request costs one token. It is the V-idiomatic equivalent of .NET's token-bucket limiter, for veb/fasthttp handlers and metered API clients.
fn (TokenBucket) allow #
fn (mut b TokenBucket) allow() bool
allow consumes one token if available, refilling first from the elapsed time. It returns false (counted in stats) when empty.
fn (TokenBucket) stats #
fn (b &TokenBucket) stats() BucketStats
stats returns the allowed/denied counters.
struct TokenBucketConfig #
struct TokenBucketConfig {
pub:
// sustained rate in tokens (requests) per second
rate_per_sec f64
// maximum burst: bucket capacity and initial tokens
burst int
}
TokenBucketConfig configures a TokenBucket.