Files
gateway/internal/plugin/ratelimit/tokenbucket.go
zeekayandHanzo Dev 53350699b6 deps(vendor): fold the krakend/lura module set into internal/
Every import in this module now resolves to github.com/hanzoai/gateway/v2.
The 34 github.com/krakend/* + github.com/luraproject/lura modules that
supplied the engine and its components are vendored under internal/ and
their 91 packages rewritten onto our own path.

Why fold rather than mirror into 34 hanzoai/* repos:

  - It removes the exposure outright. 34 rows leave 34 rows of go.sum to
    reason about; zero modules leave nothing. `go list -m all` and go.sum
    now contain no krakend/lura entry at all.
  - Cross-references cannot go wrong. 28 of the 34 import lura (97 files
    inside lura self-reference it). Mirroring means rewriting every one of
    those to our lura, and a single miss silently links a SECOND copy of
    lura into the binary. With one module that is structurally impossible.
  - It creates no duplicates. These are lura-coupled gateway glue with no
    consumer outside this binary; publishing 34 repos would be 34 new
    things to maintain for zero second caller. internal/ makes that
    guarantee mechanical — Go forbids importing it from outside this
    module, so none of it can become a competing public package. Verified
    no repo outside gateway imports any hanzoai/gateway/v2 subpackage.

Layout mirrors provenance so an upstream re-sync stays a diff:

  luraproject/lura/v2  -> internal/lura         (the engine, 20 pkgs)
  krakend/krakend-<x>  -> internal/plugin/<x>   (28 components)
  krakend/<x>          -> internal/pkg/<x>      (6 standalone libs)

This commit is PURELY MECHANICAL: 196 of the 197 vendored files are
byte-identical to their upstream original once the import rewrite is
applied. The single exception is bloomfilter's subpackage, which upstream
names `krakend` — the one package name that could not survive as-is; it
becomes internal/pkg/bloomfilter/register. Hand edits land separately in
the next commit so they are readable on their own.

Per `go mod vendor` semantics, dependencies' _test.go files are not
vendored. They test upstream code at a pinned version that we do not
modify, several cannot run at all from a module distribution (they need
TLS certs and compiled .so plugins upstream generates but never ships),
and one is a 100k-request stress test that exhausts the ephemeral port
range and fails every package running beside it. Fold integrity is proven
by the byte-diff above instead, which is the stronger check.

Preserved deliberately — each of these is behaviour, not branding:
  - the `github.com/devopsfaith/krakend*` extra_config namespace strings
    (35 of them). These are config-surface keys, not import paths;
    renaming one silently stops that component finding its config. The
    jose validator namespace backs `auth/validator` on 212 endpoints.
  - core.KrakendVersion / KrakendUserAgent / the X-KRAKEND consts, whose
    VALUES rebrand.go overwrites — that seam is unchanged.
  - the KRAKEND_ koanf env prefix (a hardcoded upstream const).
  - every vendored module's LICENSE (34 files, Apache-2.0/MIT).

The Makefile/CI -X paths move with the engine. An -X naming a symbol that
does not exist is silently ignored by the linker, so a stale path here
would have shipped an "undefined" version in the backend User-Agent and
X-Api-Version with a perfectly green build. Verified live:
`gateway version` reports 2.13.0, not undefined.

Verification (GOWORK=off CGO_ENABLED=0, both tag modes):
  go build ./...              OK      go build -tags legacy ./...   OK
  go vet ./...                clean   go vet -tags legacy ./...     clean
  go test ./...               6/6 ok  go test -tags legacy          5/5 ok
  tests/ integration harness  47 fixtures pass
  gateway check -c configs/{hanzo,lux}/gateway.json  -> Syntax OK!
  go list -m all | grep -iE 'krakend|lura'  -> empty
  go mod verify -> all modules verified

Co-authored-by: Hanzo Dev <[email protected]>
2026-07-25 14:57:19 -07:00

137 lines
3.2 KiB
Go

package krakendrate
import (
"sync"
"time"
)
// NewTokenBucket returns a token bucket with the given rate and capacity, using the default clock and
// an initial stock of cap
func NewTokenBucket(rate float64, capacity uint64) *TokenBucket {
return NewTokenBucketWithClock(rate, capacity, nil)
}
// Clock defines the interface for clock sources
type Clock interface {
Now() time.Time
Since(time.Time) time.Duration
}
// NewTokenBucketWithClock returns a token bucket with the given rate, capacity, and clock and
// an initial stock of capacity
func NewTokenBucketWithClock(rate float64, capacity uint64, c Clock) *TokenBucket {
return NewTokenBucketWithInitialStock(rate, capacity, capacity, c)
}
// NewTokenBucketWithInitialStock returns a token bucket with the given rate, capacity, clock
// and initial stock
func NewTokenBucketWithInitialStock(r float64, capacity, i uint64, c Clock) *TokenBucket {
if c == nil {
c = defaultClock{}
}
if capacity < 1 {
capacity = 1
}
if i > capacity {
i = capacity
}
if r < 1e-9 {
r = 1e-9
}
return &TokenBucket{
fillInterval: time.Duration(int64(1e9 / r)),
capacity: capacity,
clock: c,
tokens: i,
lastRefill: c.Now(),
mu: new(sync.Mutex),
}
}
func NewTokenBucketBuilder(rate float64, capacity, initialStock uint64, clk Clock) LimiterBuilderFn {
// we do not call NewTokenBucketWithIntialStock inside the returned function to
// avoid the following block of checks that can be done just once
if clk == nil {
clk = defaultClock{}
}
if capacity < 1 {
capacity = 1
}
if initialStock > capacity {
initialStock = capacity
}
if rate < 1e-9 {
rate = 1e-9
}
fillInterval := time.Duration(int64(1e9 / rate))
return func() interface{} {
return &TokenBucket{
fillInterval: fillInterval,
capacity: capacity,
clock: clk,
tokens: initialStock,
lastRefill: clk.Now(),
mu: new(sync.Mutex),
}
}
}
// TokenBucket is an implementation of the token bucket pattern
type TokenBucket struct {
fillInterval time.Duration
capacity uint64
tokens uint64
clock Clock
lastRefill time.Time
mu *sync.Mutex
}
// Allow flags if the current request can be processed or not. It updates the internal state if
// the request can be processed
func (t *TokenBucket) Allow() bool {
t.mu.Lock()
r := t.canConsume()
t.mu.Unlock()
return r
}
func (t *TokenBucket) canConsume() bool {
if t.tokens > 0 {
// delay the refill until the bucket is empty
t.tokens--
return true
}
// if there are no more tokens in the bucket, calculate how many tokens should be added
tokensToAdd := uint64(t.clock.Since(t.lastRefill) / t.fillInterval)
// if there are no tokens to be added to the empty bucket
if tokensToAdd == 0 {
return false
}
// update the time of the last refill depending on how many tokens we added
t.lastRefill = t.lastRefill.Add(time.Duration(tokensToAdd) * t.fillInterval)
// normalize the amount of tokens to add
if t.tokens+tokensToAdd > t.capacity {
t.tokens = t.capacity
return true
}
t.tokens += tokensToAdd - 1
return true
}
type defaultClock struct{}
func (defaultClock) Now() time.Time {
return time.Now()
}
func (defaultClock) Since(t time.Time) time.Duration {
return time.Since(t)
}