Documentation
¶
Overview ¶
Package limiter is to control the links that go into the dispatcher
Index ¶
- Variables
- func NormalizeGlobalIP(ip string, prefix *int) (string, error)
- func ValidateGlobalDeviceLimitConfig(config *GlobalDeviceLimitConfig, forwardedConfigured bool) error
- func WaitN(ctx context.Context, limiter *rate.Limiter, count uint64) error
- type BucketSnapshot
- type GlobalAdmission
- func (a *GlobalAdmission) Acquire(ctx context.Context, uid int, ip string, limit int) (*GlobalLease, error)
- func (a *GlobalAdmission) Close() error
- func (a *GlobalAdmission) LiveIPs() map[int][]string
- func (a *GlobalAdmission) SetUsers(limits map[int]int)
- func (a *GlobalAdmission) StatusSnapshot() GlobalAdmissionStatus
- func (a *GlobalAdmission) UpdateLimit(uid int, limit int)
- type GlobalAdmissionStatus
- type GlobalDeviceLimitConfig
- type GlobalLease
- type InboundInfo
- type InboundLimiterStateSnapshot
- type InboundSnapshot
- type Limiter
- func (l *Limiter) AddInboundLimiter(tag string, nodeSpeedLimit uint64, userList *[]api.UserInfo, ...) error
- func (l *Limiter) Admit(tag, userKey, ip string, reader buf.Reader, writer buf.Writer) (buf.Reader, buf.Writer, bool)
- func (l *Limiter) AdmitContext(ctx context.Context, tag, userKey, ip string, reader buf.Reader, ...) (buf.Reader, buf.Writer, bool)
- func (l *Limiter) ApplyInboundUserDiff(tag string, added, updated, deleted []api.UserInfo) error
- func (l *Limiter) ClearGlobalDevices(tag string) error
- func (l *Limiter) Close() error
- func (l *Limiter) DeleteInboundLimiter(tag string) error
- func (l *Limiter) GetOnlineDevice(tag string) (*[]api.OnlineUser, error)
- func (l *Limiter) GetUserBucket(tag string, userKey string, ip string) (*rate.Limiter, bool, bool)
- func (l *Limiter) GlobalDeviceDegraded() bool
- func (l *Limiter) RateReader(reader buf.Reader, limiter *rate.Limiter) buf.Reader
- func (l *Limiter) RateWriter(writer buf.Writer, limiter *rate.Limiter) buf.Writer
- func (l *Limiter) ReplaceInboundUsers(tag string, userList *[]api.UserInfo) error
- func (l *Limiter) RestoreInboundLimiterState(tag string, snapshot *InboundLimiterStateSnapshot) error
- func (l *Limiter) SnapshotInboundLimiterState(tag string) (*InboundLimiterStateSnapshot, error)
- func (l *Limiter) StateSnapshot() LimiterSnapshot
- func (l *Limiter) SyncAliveList(tag string, aliveList map[int][]string) error
- func (l *Limiter) SyncAliveSnapshot(tag string, snapshot *api.AliveSnapshot, reportedIPs map[int][]string) error
- func (l *Limiter) UpdateGlobalDevices(tag string, devices map[int][]string) error
- func (l *Limiter) UpdateInboundLimiter(tag string, updatedUserList *[]api.UserInfo) error
- type LimiterSnapshot
- type Reader
- type UserInfo
- type Writer
Constants ¶
This section is empty.
Variables ¶
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") // not be verified in FailMode=closed. Callers should reject the connection. ErrGlobalAdmissionUnavailable = errors.New("global device admission backend unavailable") )
Functions ¶
func NormalizeGlobalIP ¶
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.
Types ¶
type BucketSnapshot ¶
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 ¶
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 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 ¶
func (*Limiter) AddInboundLimiter ¶
func (*Limiter) AdmitContext ¶
func (*Limiter) ApplyInboundUserDiff ¶
ApplyInboundUserDiff updates user policies in place, retaining online IPs and compatible buckets for every user that is not deleted.
func (*Limiter) ClearGlobalDevices ¶
func (*Limiter) DeleteInboundLimiter ¶
func (*Limiter) GetOnlineDevice ¶
func (l *Limiter) GetOnlineDevice(tag string) (*[]api.OnlineUser, error)
func (*Limiter) GetUserBucket ¶
func (*Limiter) GlobalDeviceDegraded ¶
GlobalDeviceDegraded reports the Redis guarantee for applied inbounds only.
func (*Limiter) RateReader ¶
func (*Limiter) RateWriter ¶
func (*Limiter) ReplaceInboundUsers ¶
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 ¶
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 ¶
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.