Playground
gnomod.toml
module = "gno.land/p/nym-moultest123/x/daily/ratelimit/v0" gno = "0.9" [addpkg] creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv" height = 186405 max_deposit = "5000000ugnot"
ratelimit.gno
// Package ratelimit is a deterministic token-bucket rate limiter — a port of
// golang.org/x/time/rate with the wall clock replaced by a caller-supplied
// monotonic tick (on-chain, that tick is the block height).
//
// It is a pure library: it imports no chain APIs and reads no ambient state.
// A [Limiter] owns a set of per-key token buckets sharing one rate/burst
// config; the caller decides what a key is (typically an address string) and
// supplies the current tick on every call. Between two observations at ticks
// `last` and `now`, a bucket gains (now-last)*rate tokens, capped at `burst`.
// Everything is integer/float arithmetic over persistent avl state, hence
// deterministic and replayable.
//
// A realm wires it up by holding a *Limiter in a package-level var and feeding
// it runtime.ChainHeight() as the tick. For a complete, live example see the
// demo realm [r/moul/x/daily/ratelimitdemo](/r/nym-moultest123/x/daily/ratelimitdemo/v0).
package ratelimit
import "gno.land/p/nt/avl/v0"
// bucket is the per-key state persisted in the avl tree.
type bucket struct {
tokens float64 // tokens available as of `last`
last int64 // tick at which `tokens` was computed
}
// Limiter is a set of per-key token buckets sharing one rate/burst config.
// The zero value is not usable; construct one with [New].
type Limiter struct {
rate float64 // tokens replenished per tick
burst float64 // bucket capacity (max tokens, largest single burst)
buckets *avl.Tree // key string -> *bucket, ordered by key (deterministic)
}
// New returns a Limiter replenishing `rate` tokens per tick, each bucket capped
// at `burst`. rate is clamped to >= 0, burst to >= 1.
func New(rate, burst float64) *Limiter {
l := &Limiter{buckets: avl.NewTree()}
l.SetConfig(rate, burst)
return l
}
// SetConfig updates the shared rate and burst. rate is clamped to >= 0, burst
// to >= 1. Existing buckets keep their stored tokens; the new config applies
// from the next refill.
func (l *Limiter) SetConfig(rate, burst float64) {
if rate < 0 {
rate = 0
}
if burst < 1 {
burst = 1
}
l.rate = rate
l.burst = burst
}
// Config returns the current rate (tokens/tick) and burst (capacity).
func (l *Limiter) Config() (rate, burst float64) { return l.rate, l.burst }
// Allow consumes one token for `key` at tick `now` and reports whether the
// request is permitted. When the bucket is empty it returns false and consumes
// nothing. Equivalent to AllowN(key, now, 1).
func (l *Limiter) Allow(key string, now int64) bool {
return l.AllowN(key, now, 1)
}
// AllowN consumes `n` tokens for `key` at tick `now` and reports whether the
// request is permitted. When fewer than `n` tokens are available it returns
// false and consumes nothing. A key is seen for the first time with a full
// bucket of `burst` tokens.
func (l *Limiter) AllowN(key string, now int64, n float64) bool {
b := l.load(key, now)
ok := b.tokens >= n
if ok {
b.tokens -= n
}
l.buckets.Set(key, b)
return ok
}
// Tokens is a read-only view of how many whole tokens `key` has available at
// tick `now`, without mutating any state.
func (l *Limiter) Tokens(key string, now int64) int {
if !l.buckets.Has(key) {
return tokensToInt(l.burst)
}
b := l.buckets.Get(key).(*bucket)
return tokensToInt(refill(b.tokens, b.last, now, l.rate, l.burst))
}
// Len returns the number of keys the limiter has seen.
func (l *Limiter) Len() int { return l.buckets.Size() }
// Iterate calls fn for every known key in ascending order, passing the whole
// tokens available at tick `now` and the last tick the key was observed.
// Returning true from fn stops the iteration early; Iterate reports whether it
// was stopped that way.
func (l *Limiter) Iterate(now int64, fn func(key string, tokens int, last int64) bool) bool {
return l.buckets.Iterate("", "", func(key string, value any) bool {
b := value.(*bucket)
return fn(key, tokensToInt(refill(b.tokens, b.last, now, l.rate, l.burst)), b.last)
})
}
// load returns the live bucket for key, refilled to `now`, creating a full
// bucket the first time a key is seen. The returned bucket is not yet stored;
// callers that mutate it must Set it back.
func (l *Limiter) load(key string, now int64) *bucket {
if l.buckets.Has(key) {
b := l.buckets.Get(key).(*bucket)
b.tokens = refill(b.tokens, b.last, now, l.rate, l.burst)
b.last = now
return b
}
return &bucket{tokens: l.burst, last: now}
}
// --- pure helpers (unit-tested) -------------------------------------------
// fmin returns the smaller of two float64 values.
func fmin(a, b float64) float64 {
if a < b {
return a
}
return b
}
// refill returns the token count at tick `now` given `tokens` observed at tick
// `last`, replenishing at `r` tokens/tick up to capacity `cap`. It never
// decreases below the stored value and never exceeds `cap`.
func refill(tokens float64, last, now int64, r, cap float64) float64 {
if now <= last {
return fmin(tokens, cap)
}
elapsed := float64(now - last)
return fmin(cap, tokens+elapsed*r)
}
// tokensToInt floors a token count to a whole, non-negative token.
func tokensToInt(t float64) int {
if t < 0 {
return 0
}
return int(t)
}
ratelimit_test.gno
package ratelimit
import (
"testing"
"gno.land/p/nt/uassert/v0"
)
func TestRefill(t *testing.T) {
// Start with 1 token, 4 ticks elapse at 0.5 tokens/tick, cap 5.
// 1 + 4*0.5 = 3.
got := refill(1.0, 10, 14, 0.5, 5.0)
uassert.True(t, got == 3.0, "expected 3 tokens after refill")
// No time elapsed -> unchanged (but clamped to cap).
got = refill(2.0, 10, 10, 0.5, 5.0)
uassert.True(t, got == 2.0, "no elapsed ticks should not add tokens")
// Going backwards (now < last) never adds tokens.
got = refill(2.0, 10, 5, 0.5, 5.0)
uassert.True(t, got == 2.0, "negative elapsed should not add tokens")
}
func TestRefillCap(t *testing.T) {
// Long idle period must saturate at burst capacity.
got := refill(0.0, 0, 1000, 0.5, 5.0)
uassert.True(t, got == 5.0, "refill must cap at burst")
// Already-full bucket stays full.
got = refill(5.0, 0, 100, 0.5, 5.0)
uassert.True(t, got == 5.0, "full bucket stays capped")
}
func TestTokensToInt(t *testing.T) {
uassert.Equal(t, 3, tokensToInt(3.9))
uassert.Equal(t, 0, tokensToInt(0.4))
uassert.Equal(t, 0, tokensToInt(-2.0))
uassert.Equal(t, 5, tokensToInt(5.0))
}
func TestFmin(t *testing.T) {
uassert.True(t, fmin(1.0, 2.0) == 1.0, "fmin picks smaller")
uassert.True(t, fmin(4.0, 2.5) == 2.5, "fmin picks smaller")
uassert.True(t, fmin(3.0, 3.0) == 3.0, "fmin on equals")
}
func TestNewClampsConfig(t *testing.T) {
l := New(-1, 0) // rate < 0 -> 0, burst < 1 -> 1
r, b := l.Config()
uassert.True(t, r == 0.0, "rate clamped to 0")
uassert.True(t, b == 1.0, "burst clamped to 1")
}
func TestAllowConsumesAndDenies(t *testing.T) {
l := New(0.5, 5.0)
const k = "g1caller"
// A fresh key starts full (burst=5): first 5 Allow succeed, 6th fails.
for i := 0; i < 5; i++ {
uassert.True(t, l.Allow(k, 0), "burst token should be granted")
}
uassert.False(t, l.Allow(k, 0), "6th call at same tick must be denied")
// After 4 ticks at 0.5/tick, 2 whole tokens refilled -> 2 more allowed.
uassert.True(t, l.Allow(k, 4), "refilled token granted")
uassert.True(t, l.Allow(k, 4), "refilled token granted")
uassert.False(t, l.Allow(k, 4), "empty again")
}
func TestAllowNAtomic(t *testing.T) {
l := New(1, 5.0)
const k = "g1caller"
uassert.False(t, l.AllowN(k, 0, 6), "cannot take more than burst")
uassert.Equal(t, 5, l.Tokens(k, 0), "denied AllowN consumes nothing")
uassert.True(t, l.AllowN(k, 0, 3), "3 of 5 taken")
uassert.Equal(t, 2, l.Tokens(k, 0), "2 remain")
}
func TestTokensReadOnly(t *testing.T) {
l := New(0.5, 5.0)
const k = "g1caller"
// Unseen key reports a full bucket without creating it.
uassert.Equal(t, 5, l.Tokens(k, 100), "unseen key is full")
uassert.Equal(t, 0, l.Len(), "Tokens must not create a bucket")
// Reading does not consume.
uassert.Equal(t, 5, l.Tokens(k, 200), "still full on second read")
}
func TestPerKeyIsolation(t *testing.T) {
l := New(0.5, 5.0)
l.Allow("g1a", 0)
uassert.Equal(t, 4, l.Tokens("g1a", 0), "a spent one")
uassert.Equal(t, 5, l.Tokens("g1b", 0), "b untouched")
uassert.Equal(t, 1, l.Len(), "only a exists")
}
func TestIterate(t *testing.T) {
l := New(0.5, 5.0)
l.Allow("g1a", 0)
l.Allow("g1b", 0)
seen := 0
stopped := l.Iterate(0, func(key string, tokens int, last int64) bool {
seen++
return false
})
uassert.Equal(t, 2, seen, "iterate visits every key")
uassert.False(t, stopped, "not stopped early")
// Early stop.
count := 0
stopped = l.Iterate(0, func(key string, tokens int, last int64) bool {
count++
return true
})
uassert.Equal(t, 1, count, "stops after first")
uassert.True(t, stopped, "reported as stopped")
}