limiter

package
v0.0.0-...-7333294 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: MPL-2.0 Imports: 29 Imported by: 0

Documentation

Overview

Package limiter is to control the links that go into the dispatcher

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrGlobalAdmissionQuota reports that the effective per-UID source-IP
	// quota is full. Callers should reject the connection.
	ErrGlobalAdmissionQuota = errors.New("global device admission quota reached")
	// ErrGlobalAdmissionUnavailable reports that Redis-backed admission could
	// not be verified in FailMode=closed. Callers should reject the connection.
	ErrGlobalAdmissionUnavailable = errors.New("global device admission backend unavailable")
)

Functions

func NormalizeGlobalIP

func NormalizeGlobalIP(ip string, prefix *int) (string, error)

NormalizeGlobalIP returns a canonical source-IP identity. IPv4 and IPv4-mapped addresses ignore prefix; IPv6 is masked to prefix (nil means /64, 0 means the full /128 address). Addresses with a zone are rejected.

func ValidateGlobalDeviceLimitConfig

func ValidateGlobalDeviceLimitConfig(config *GlobalDeviceLimitConfig, forwardedConfigured bool) error

ValidateGlobalDeviceLimitConfig validates an enabled configuration without mutating it. forwardedConfigured reports whether trusted forwarded source headers are configured. Strict mode requires an explicit acknowledgement that those headers are the intended source identity.

func WaitN

func WaitN(ctx context.Context, limiter *rate.Limiter, count uint64) error

WaitN admits count bytes without asking the limiter for more than its burst in one operation. The first wait failure stops admission.

Types

type BucketSnapshot

type BucketSnapshot struct {
	Limit float64
	Burst int
}

BucketSnapshot contains the observable value state of one rate limiter.

type GlobalAdmission

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

GlobalAdmission coordinates cross-node source-IP quotas for one panel namespace. It is safe for concurrent use. Managers with the same Redis connection share one process-wide client; each manager owns its policies, holders and renewal worker.

func NewGlobalAdmission

func NewGlobalAdmission(config *GlobalDeviceLimitConfig, panelType, apiHost string) (*GlobalAdmission, error)

NewGlobalAdmission builds a Redis-backed admission manager. It returns (nil, nil) when global device limiting is disabled.

func (*GlobalAdmission) Acquire

func (a *GlobalAdmission) Acquire(ctx context.Context, uid int, ip string, limit int) (*GlobalLease, error)

Acquire reserves one normalized source IP for uid and returns a tentative lease. Callers must Commit after local admission accepts the connection, Abort when downstream admission fails, and Close when the connection ends.

On Redis failure, FailMode=open still enforces this process's local quota and returns a local-only lease (GlobalConfirmed false); FailMode=closed returns ErrGlobalAdmissionUnavailable. A closed manager always returns ErrGlobalAdmissionUnavailable. A nil receiver returns (nil, nil).

func (*GlobalAdmission) Close

func (a *GlobalAdmission) Close() error

Close stops renewal, cancels in-flight Redis work, joins the worker, and releases the shared backend reference. It performs no network I/O and is idempotent. Live leases stop being renewed and expire by TTL; callers that replace a node identity while its links are still alive should reuse the same manager rather than closing it.

func (*GlobalAdmission) LiveIPs

func (a *GlobalAdmission) LiveIPs() map[int][]string

LiveIPs returns committed, currently held source IPs grouped by UID. It is detached and intended for idle online-user reporting, not authentication.

func (*GlobalAdmission) SetUsers

func (a *GlobalAdmission) SetUsers(limits map[int]int)

SetUsers replaces the complete known policy view without network I/O. Zero limits are registered but do not participate in the positive minimum.

func (*GlobalAdmission) StatusSnapshot

func (a *GlobalAdmission) StatusSnapshot() GlobalAdmissionStatus

StatusSnapshot reports whether the distributed guarantee is currently degraded. It never contains addresses, credentials, UIDs or IPs.

func (*GlobalAdmission) UpdateLimit

func (a *GlobalAdmission) UpdateLimit(uid int, limit int)

UpdateLimit records the latest device limit for uid without network I/O. The renewal worker publishes it, including when the user has no connection.

type GlobalAdmissionStatus

type GlobalAdmissionStatus struct {
	Degraded bool
	Reason   string
}

GlobalAdmissionStatus is a credential-free readiness view. Degraded means the distributed guarantee is currently weakened: Redis admission failed or a live holder lost its reservation. It clears only after every live holder is reserved again.

type GlobalDeviceLimitConfig

type GlobalDeviceLimitConfig struct {
	Enable        bool   `mapstructure:"Enable"`
	RedisNetwork  string `mapstructure:"RedisNetwork"` // tcp or unix
	RedisAddr     string `mapstructure:"RedisAddr"`    // host:port, or /path/to/unix.sock
	RedisUsername string `mapstructure:"RedisUsername"`
	RedisPassword string `mapstructure:"RedisPassword"`
	RedisDB       int    `mapstructure:"RedisDB"`
	Timeout       int    `mapstructure:"Timeout"`
	Expiry        int    `mapstructure:"Expiry"` // second

	// Mode "cache" (default) reuses a live same-UID/IP holder without a Redis
	// round trip; "strict" verifies every Acquire against Redis.
	Mode string `mapstructure:"Mode"`
	// FailMode "open" (default) keeps local admission on Redis failures;
	// "closed" rejects all new connections while Redis cannot be verified.
	FailMode string `mapstructure:"FailMode"`
	// Namespace overrides the derived shared key space. It is hashed and is
	// never used verbatim, so it cannot leak panel identity or credentials.
	Namespace string `mapstructure:"Namespace"`
	// IPv6Prefix masks IPv6 sources into a shared prefix; nil means /64 and an
	// explicit 0 means the full /128 address.
	IPv6Prefix *int `mapstructure:"IPv6Prefix"`
	// StrictClientIPSource acknowledges header-derived source identity in
	// strict mode: "peer" (direct transport address) or "forwarded".
	StrictClientIPSource string `mapstructure:"StrictClientIPSource"`

	// PanelType and APIHost are internal wiring hints filled by the runtime;
	// they derive the stable namespace when Namespace is empty.
	PanelType string `mapstructure:"-"`
	APIHost   string `mapstructure:"-"`
	// RuntimeOwner identifies the in-process runtime that owns this config so
	// node-tag replacement can reuse one admission manager and keep existing
	// lease renewal alive. It is never part of any Redis key.
	RuntimeOwner string `mapstructure:"-"`
}

type GlobalLease

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

GlobalLease is one connection's tentative or committed global hold. Methods are idempotent and safe on a nil receiver.

func (*GlobalLease) Abort

func (l *GlobalLease) Abort() error

Abort removes a tentative reservation that was never committed. It removes only this holder's token and preserves every other holder, including the prior grace lease this instance may hold for the same IP.

func (*GlobalLease) Close

func (l *GlobalLease) Close() error

Close stops this local hold. The normal last close never deletes Redis state; the lease expires by TTL. Close on an uncommitted lease behaves like Abort.

func (*GlobalLease) Commit

func (l *GlobalLease) Commit() error

Commit marks the hold live. It is local-only: Acquire already performed the atomic reservation, so a successful local admission cannot be rejected by a second Redis round trip. The renewal worker promotes the reservation state and keeps it alive. It returns non-nil only if the manager is already closed.

func (*GlobalLease) GlobalConfirmed

func (l *GlobalLease) GlobalConfirmed() bool

GlobalConfirmed reports whether this lease's slot is currently confirmed in Redis. False means the caller still gets local-only protection and must treat the shared quota as suspended (status is degraded).

type InboundInfo

type InboundInfo struct {
	Tag            string
	NodeSpeedLimit uint64
	UserInfo       *sync.Map // Key: user tag (inboundUserKey) -> UserInfo
	BucketHub      *sync.Map // Key: user tag -> *rate.Limiter
	UserOnlineIP   *sync.Map // Key: user tag -> *userOnlineEntry

	GlobalDevices *globalDeviceState
	GlobalLimit   *globalLimitState
	// contains filtered or unexported fields
}

type InboundLimiterStateSnapshot

type InboundLimiterStateSnapshot struct {
	UserInfo map[string]UserInfo
	Buckets  map[string]bucketStateSnapshot
	// contains filtered or unexported fields
}

type InboundSnapshot

type InboundSnapshot struct {
	Tag                    string
	NodeSpeedLimit         uint64
	Users                  map[string]UserInfo
	Buckets                map[string]BucketSnapshot
	OnlineUsers            []api.OnlineUser
	GlobalDevices          map[int][]string
	GlobalDevicesUpdatedAt time.Time
	GlobalDevicesFresh     bool
	GlobalLimitEnabled     bool
	GlobalLimitClosed      bool
}

InboundSnapshot is a detached read-only view of one applied inbound. Runtime objects, cache backends, and global-limit credentials are omitted.

type Limiter

type Limiter struct {
	InboundInfo *sync.Map
	// contains filtered or unexported fields
}

func New

func New() *Limiter

func (*Limiter) AddInboundLimiter

func (l *Limiter) AddInboundLimiter(tag string, nodeSpeedLimit uint64, userList *[]api.UserInfo, globalLimit *GlobalDeviceLimitConfig) error

func (*Limiter) Admit

func (l *Limiter) Admit(tag, userKey, ip string, reader buf.Reader, writer buf.Writer) (buf.Reader, buf.Writer, bool)

func (*Limiter) AdmitContext

func (l *Limiter) AdmitContext(ctx context.Context, tag, userKey, ip string, reader buf.Reader, writer buf.Writer) (buf.Reader, buf.Writer, bool)

func (*Limiter) ApplyInboundUserDiff

func (l *Limiter) ApplyInboundUserDiff(tag string, added, updated, deleted []api.UserInfo) error

ApplyInboundUserDiff updates user policies in place, retaining online IPs and compatible buckets for every user that is not deleted.

func (*Limiter) ClearGlobalDevices

func (l *Limiter) ClearGlobalDevices(tag string) error

func (*Limiter) Close

func (l *Limiter) Close() error

func (*Limiter) DeleteInboundLimiter

func (l *Limiter) DeleteInboundLimiter(tag string) error

func (*Limiter) GetOnlineDevice

func (l *Limiter) GetOnlineDevice(tag string) (*[]api.OnlineUser, error)

func (*Limiter) GetUserBucket

func (l *Limiter) GetUserBucket(tag string, userKey string, ip string) (*rate.Limiter, bool, bool)

func (*Limiter) GlobalDeviceDegraded

func (l *Limiter) GlobalDeviceDegraded() bool

GlobalDeviceDegraded reports the Redis guarantee for applied inbounds only.

func (*Limiter) RateReader

func (l *Limiter) RateReader(reader buf.Reader, limiter *rate.Limiter) buf.Reader

func (*Limiter) RateWriter

func (l *Limiter) RateWriter(writer buf.Writer, limiter *rate.Limiter) buf.Writer

func (*Limiter) ReplaceInboundUsers

func (l *Limiter) ReplaceInboundUsers(tag string, userList *[]api.UserInfo) error

ReplaceInboundUsers applies an authoritative user policy snapshot for one inbound. State for users absent from the replacement is not retained.

func (*Limiter) RestoreInboundLimiterState

func (l *Limiter) RestoreInboundLimiterState(tag string, snapshot *InboundLimiterStateSnapshot) error

func (*Limiter) SnapshotInboundLimiterState

func (l *Limiter) SnapshotInboundLimiterState(tag string) (*InboundLimiterStateSnapshot, error)

func (*Limiter) StateSnapshot

func (l *Limiter) StateSnapshot() LimiterSnapshot

StateSnapshot returns a detached snapshot of valid applied inbounds. Forged or detached entries in the legacy mutable map are not published.

func (*Limiter) SyncAliveList

func (l *Limiter) SyncAliveList(tag string, aliveList map[int][]string) error

SyncAliveList synchronizes the alive list from panel to local tracking

func (*Limiter) SyncAliveSnapshot

func (l *Limiter) SyncAliveSnapshot(tag string, snapshot *api.AliveSnapshot, reportedIPs map[int][]string) error

SyncAliveSnapshot applies a complete typed panel snapshot. A nil snapshot is not an update. Counts advance only when reportedIPs is non-nil, the receipt of a successful report from the same cycle; an empty non-nil map is a valid empty report.

func (*Limiter) UpdateGlobalDevices

func (l *Limiter) UpdateGlobalDevices(tag string, devices map[int][]string) error

func (*Limiter) UpdateInboundLimiter

func (l *Limiter) UpdateInboundLimiter(tag string, updatedUserList *[]api.UserInfo) error

type LimiterSnapshot

type LimiterSnapshot struct {
	Closed   bool
	Inbounds map[string]InboundSnapshot
}

LimiterSnapshot is a detached read-only view of the currently applied limiter state. Mutating its maps or slices does not change admission state. It contains user keys and IP addresses and must not be logged unredacted or used as metrics labels.

type Reader

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

type UserInfo

type UserInfo struct {
	UID         int
	SpeedLimit  uint64
	DeviceLimit int
}

type Writer

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

Jump to

Keyboard shortcuts

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