ratelimit

package
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: Apache-2.0 Imports: 36 Imported by: 0

Documentation

Overview

Package ratelimit enforces rate limit policies on tile requests and holds the built-in counter stores

Index

Constants

View Source
const (
	HeadersStandard = "standard"
	HeadersMin      = "min"
	HeadersNone     = "none"
)
View Source
const (
	OnErrorAllow = "allow"
	OnErrorDeny  = "deny"
)
View Source
const (
	HeaderRateLimit       = "RateLimit"
	HeaderRateLimitPolicy = "RateLimit-Policy"
	HeaderRetryAfter      = "Retry-After"
)
View Source
const (
	SegmentUser   = "user"
	SegmentTenant = "tenant"
	SegmentIP     = "ip"
	SegmentLayer  = "layer"
)
View Source
const (
	CalendarHour  = "hour"
	CalendarDay   = "day"
	CalendarWeek  = "week"
	CalendarMonth = "month"
	CalendarYear  = "year"
)
View Source
const SegmentAll = "all"

Matches rules with no segments, the same word used in their names

Variables

View Source
var ErrNotInspectable = errors.New("the rate limit store can't be read or reset from outside the server")

Functions

func ExposedHeaders

func ExposedHeaders() []string

The headers to let browser scripts read when rate limiting is enabled

func ParsePrefix

func ParsePrefix(raw string) (netip.Prefix, error)

Accepts a single address or a CIDR range

func StoreDatastoreID

func StoreDatastoreID(rawConfig map[string]interface{}) string

Exposed for the ratelimit command, which only needs the store's own datastore

Types

type CommonConfig

type CommonConfig struct {
	Policies   []PolicyConfig
	Headers    string
	Timeout    uint // In milliseconds
	OnError    string
	IPv6Prefix *uint
}

Accepted by every store, so they're split off before the store decodes the rest

type Limiter

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

Enforces the policies of one configuration

func ConstructLimiter

func ConstructLimiter(ctx context.Context, cfg config.Config, secreter secret.Secreter, deps ratelimit.RateLimiterDeps) (*Limiter, error)

Validates the whole rate limit configuration, including the policies layers refer to. secreter is separate from deps because it resolves the raw config before the store is constructed

func ConstructPolicies

func ConstructPolicies(ctx context.Context, cfg config.Config, secreter secret.Secreter, messages config.ErrorMessages) (*Limiter, error)

Never constructs the store, so the result is disabled and only useful for describing rules

func (*Limiter) Check

func (l *Limiter) Check(ctx context.Context, layerID string) Result

Checks and counts a tile request for the layer. The identity comes from the request context

func (*Limiter) Close

func (l *Limiter) Close(ctx context.Context) error

func (*Limiter) Enabled

func (l *Limiter) Enabled() bool

False for the none store, in which case Check always allows without headers

func (*Limiter) ResetRule

func (l *Limiter) ResetRule(ctx context.Context, name string, segments map[string]string, dryRun bool) (int64, []string, error)

Clears one counter, including the previous bucket of a rolling period. Returns the count beforehand. segments must hold a value, possibly empty, for exactly the segments of the rule

func (*Limiter) Rules

func (l *Limiter) Rules(filter RuleFilter) ([]RuleInfo, error)

Every rule matching the filter, in configuration order. Never touches the store

func (*Limiter) Status

func (l *Limiter) Status(ctx context.Context, layerID string, req Request) (Status, []string, error)

Reads the counters without counting a request. Rules needing an IP are skipped, with a warning, when none is supplied

type Memory

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

Deliberately not a Resetter, since the ratelimit command runs in a different process

func (*Memory) Get

func (m *Memory) Get(_ context.Context, counters []ratelimit.RateLimitCounter) ([]int64, error)

func (*Memory) Increment

func (m *Memory) Increment(_ context.Context, counters []ratelimit.RateLimitCounter) error

type MemoryConfig

type MemoryConfig struct {
	MaxSize uint32 // Maximum number of counters to hold. Defaults to 100000
}

type MemoryRegistration

type MemoryRegistration struct{}

func (MemoryRegistration) Initialize

func (MemoryRegistration) InitializeConfig

func (MemoryRegistration) InitializeConfig() any

func (MemoryRegistration) Name

func (MemoryRegistration) Name() string

type None

type None struct{}

Never called, since the limiter treats this store as disabled

func (None) Get

func (None) Get(_ context.Context, counters []ratelimit.RateLimitCounter) ([]int64, error)

func (None) Increment

func (None) Increment(_ context.Context, _ []ratelimit.RateLimitCounter) error

type NoneConfig

type NoneConfig struct{}

type NoneRegistration

type NoneRegistration struct{}

func (NoneRegistration) Initialize

func (NoneRegistration) InitializeConfig

func (NoneRegistration) InitializeConfig() any

func (NoneRegistration) Name

func (NoneRegistration) Name() string

type Outcome

type Outcome int
const (
	Allowed Outcome = iota
	Rejected
	// The store failed and onError is deny
	Unavailable
)

type OverrideConfig

type OverrideConfig struct {
	Users     []string
	Tenants   []string
	IPs       []string
	Anonymous bool
	// A pointer since 0 is meaningful and the key is required
	Limit *int
}

type OverrideInfo

type OverrideInfo struct {
	Users     []string `json:"users,omitempty"`
	Tenants   []string `json:"tenants,omitempty"`
	IPs       []string `json:"ips,omitempty"`
	Anonymous bool     `json:"anonymous,omitempty"`
	Limit     int64    `json:"limit"`
}

type PolicyConfig

type PolicyConfig struct {
	ID     string
	Rules  []RuleConfig
	Extend []string
}

type Postgresql

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

func (*Postgresql) Get

func (p *Postgresql) Get(ctx context.Context, counters []ratelimit.RateLimitCounter) ([]int64, error)

func (*Postgresql) Increment

func (p *Postgresql) Increment(ctx context.Context, counters []ratelimit.RateLimitCounter) error

func (*Postgresql) Now

func (p *Postgresql) Now(ctx context.Context) (time.Time, error)

func (*Postgresql) Reset

func (p *Postgresql) Reset(ctx context.Context, counters []ratelimit.RateLimitCounter) error

type PostgresqlConfig

type PostgresqlConfig struct {
	Datastore string // ID of a postgresql datastore
	Table     string // Never created by tilegroxy. See the docs for the DDL
}

type PostgresqlRegistration

type PostgresqlRegistration struct{}

func (PostgresqlRegistration) Initialize

func (PostgresqlRegistration) InitializeConfig

func (PostgresqlRegistration) InitializeConfig() any

func (PostgresqlRegistration) Name

type Redis

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

func (*Redis) Get

func (r *Redis) Get(ctx context.Context, counters []ratelimit.RateLimitCounter) ([]int64, error)

Pipelined rather than MGET since counters can live on different cluster nodes

func (*Redis) Increment

func (r *Redis) Increment(ctx context.Context, counters []ratelimit.RateLimitCounter) error

The TTL is refreshed on every increment, each time from the server's own clock

func (*Redis) Now

func (r *Redis) Now(ctx context.Context) (time.Time, error)

func (*Redis) Reset

func (r *Redis) Reset(ctx context.Context, counters []ratelimit.RateLimitCounter) error

type RedisConfig

type RedisConfig struct {
	Datastore string // ID of a redis datastore
	KeyPrefix string // Prepended to every key. Defaults to ratelimit:
}

type RedisRegistration

type RedisRegistration struct{}

func (RedisRegistration) Initialize

func (RedisRegistration) InitializeConfig

func (RedisRegistration) InitializeConfig() any

func (RedisRegistration) Name

func (RedisRegistration) Name() string

type Request

type Request struct {
	User   string
	Tenant string
	IP     string
}

Stands in for the identity a tile request would have. An empty IP means not supplied

type Result

type Result struct {
	Outcome Outcome
	Header  http.Header
	// The first exceeded rule, for logging
	Rule string
}

What to do with one request. Header holds the headers to add to the response either way

type RuleConfig

type RuleConfig struct {
	Limit    uint
	Period   uint
	Calendar string
	// A pointer because an empty list is valid and differs from a missing one
	Segment   *[]string
	Overrides []OverrideConfig
}

type RuleFilter

type RuleFilter struct {
	// Case-insensitive substring of the rule name
	Search   string
	Policies []string
	// Layer IDs
	Layers   []string
	Segments []string
}

Each field narrows the result. A rule matches a field if it matches any of its values

type RuleInfo

type RuleInfo struct {
	Rule     string   `json:"rule"`
	Policy   string   `json:"policy"`
	Segments []string `json:"segments"`
	// In seconds. Zero for a calendar period
	Period    int64          `json:"period,omitempty"`
	Calendar  string         `json:"calendar,omitempty"`
	Limit     int64          `json:"limit"`
	Overrides []OverrideInfo `json:"overrides"`
	// Layers enforcing the rule, directly or through extend
	Layers []string `json:"layers"`
}

type Status

type Status struct {
	Layer string `json:"layer"`
	// Empty when the layer isn't rate limited
	Policy  string `json:"policy,omitempty"`
	Allowed bool   `json:"allowed"`
	// In seconds. Absent when allowed, or when a limit of 0 means it never will be
	RetryAfter *int64  `json:"retryAfter,omitempty"`
	Rules      []Usage `json:"rules"`
}

Whether the next tile request to one layer would be allowed

type Usage

type Usage struct {
	Rule      string    `json:"rule"`
	Policy    string    `json:"policy"`
	Used      int64     `json:"used"`
	Limit     int64     `json:"limit"`
	Unlimited bool      `json:"unlimited"`
	Remaining int64     `json:"remaining"`
	Resets    time.Time `json:"resets"`
	// False for a calendar period
	Rolling bool `json:"rolling"`
	// True when the rule would reject the next request
	Blocking bool `json:"blocking"`
}

One rule's state for the given identity

Jump to

Keyboard shortcuts

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