ratelimit

package
v0.1.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 29, 2026 License: AGPL-3.0 Imports: 5 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Bucket

type Bucket struct {
	// contains filtered or unexported fields
}

Bucket is a token-bucket rate limiter with separate refill rate and burst capacity.

func NewBucket

func NewBucket(ratePerSec, burstMax float64) *Bucket

NewBucket creates a token bucket that refills at ratePerSec tokens/second and allows bursts up to burstMax tokens.

func (*Bucket) LastCheck

func (b *Bucket) LastCheck() time.Time

LastCheck returns the last time the bucket was accessed. Used for staleness checks.

func (*Bucket) RetryAfterSecs

func (b *Bucket) RetryAfterSecs() int

RetryAfterSecs returns the estimated seconds until a token becomes available. Always returns at least 1.

func (*Bucket) TryConsume

func (b *Bucket) TryConsume() bool

TryConsume attempts to consume one token. Returns true if the token was available, false if the bucket is empty.

type BucketMap

type BucketMap[K comparable] struct {
	// contains filtered or unexported fields
}

BucketMap is a sharded, concurrent map of token buckets keyed by K. Each shard has an independent lock, eliminating global contention.

func NewBucketMap

func NewBucketMap[K comparable](maxPerShard int) *BucketMap[K]

NewBucketMap creates a sharded bucket map. maxPerShard caps entries per shard to prevent unbounded growth (0 means no cap).

func (*BucketMap[K]) Cleanup

func (bm *BucketMap[K]) Cleanup(staleAfter time.Duration)

Cleanup removes entries that haven't been accessed for staleAfter duration.

func (*BucketMap[K]) GetOrCreate

func (bm *BucketMap[K]) GetOrCreate(key K, ratePerSec, burstMax float64) *Bucket

GetOrCreate returns the bucket for key, creating one if it doesn't exist.

func (*BucketMap[K]) StartCleanupLoop

func (bm *BucketMap[K]) StartCleanupLoop(ctx context.Context, interval, staleAfter time.Duration)

StartCleanupLoop runs periodic cleanup in a background goroutine. Stops when ctx is cancelled or Stop is called.

func (*BucketMap[K]) Stop

func (bm *BucketMap[K]) Stop()

Stop halts the cleanup loop if running.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL