ratelimit

package
v0.0.0-...-230ac96 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: Apache-2.0 Imports: 4 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package ratelimit provides rate limiting and quota management for agentmon.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ActionConfig

type ActionConfig struct {
	FileOps      LimitAction `json:"file_ops" yaml:"file_ops"`
	NetworkConns LimitAction `json:"network_conns" yaml:"network_conns"`
	DNSQueries   LimitAction `json:"dns_queries" yaml:"dns_queries"`
}

ActionConfig defines actions when limits are exceeded.

type ActionType

type ActionType string

ActionType represents the type of action to take.

const (
	ActionThrottle ActionType = "throttle"
	ActionBlock    ActionType = "block"
	ActionAlert    ActionType = "alert"
)

type AgentLimits

type AgentLimits struct {
	MaxConcurrentSessions     int   `json:"max_concurrent_sessions" yaml:"max_concurrent_sessions"`
	MaxTotalOperationsPerHour int64 `json:"max_total_operations_per_hour" yaml:"max_total_operations_per_hour"`
}

AgentLimits defines per-agent limits.

type ApprovalLimiter

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

ApprovalLimiter limits the number of pending approvals.

func NewApprovalLimiter

func NewApprovalLimiter(maxPending int) *ApprovalLimiter

NewApprovalLimiter creates a new approval limiter.

func (*ApprovalLimiter) MaxPending

func (a *ApprovalLimiter) MaxPending() int

MaxPending returns the maximum allowed pending approvals.

func (*ApprovalLimiter) Pending

func (a *ApprovalLimiter) Pending() int

Pending returns the current number of pending approvals.

func (*ApprovalLimiter) Release

func (a *ApprovalLimiter) Release()

Release releases a pending approval slot.

func (*ApprovalLimiter) TryAcquire

func (a *ApprovalLimiter) TryAcquire() bool

TryAcquire attempts to acquire a pending approval slot.

type Config

type Config struct {
	// Session limits
	Session SessionLimits `json:"session" yaml:"session"`

	// Agent limits (across all sessions)
	Agent AgentLimits `json:"agent" yaml:"agent"`

	// Tenant limits
	Tenant TenantLimits `json:"tenant" yaml:"tenant"`

	// Global limits
	Global GlobalLimits `json:"global" yaml:"global"`

	// Actions when limits exceeded
	Actions ActionConfig `json:"actions" yaml:"actions"`
}

Config defines rate limit configuration.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns sensible default rate limit configuration.

type GlobalLimits

type GlobalLimits struct {
	MaxConcurrentSessions int `json:"max_concurrent_sessions" yaml:"max_concurrent_sessions"`
	MaxPendingApprovals   int `json:"max_pending_approvals" yaml:"max_pending_approvals"`
}

GlobalLimits defines global limits.

type LimitAction

type LimitAction struct {
	Action  ActionType `json:"action" yaml:"action"`
	DelayMs int        `json:"delay_ms,omitempty" yaml:"delay_ms,omitempty"`
	Message string     `json:"message,omitempty" yaml:"message,omitempty"`
}

LimitAction defines what happens when a limit is exceeded.

type Limiter

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

Limiter provides token bucket rate limiting.

func NewLimiter

func NewLimiter(rate float64, burst int) *Limiter

NewLimiter creates a new rate limiter.

func (*Limiter) Allow

func (l *Limiter) Allow() bool

Allow checks if an operation is allowed and consumes a token if so.

func (*Limiter) AllowN

func (l *Limiter) AllowN(n int) bool

AllowN checks if n operations are allowed and consumes n tokens if so.

func (*Limiter) Burst

func (l *Limiter) Burst() int

Burst returns the maximum burst size.

func (*Limiter) ForceConsumeN

func (l *Limiter) ForceConsumeN(n int)

ForceConsumeN unconditionally deducts n tokens, allowing the bucket to go negative. Use this for post-fact accounting where the operation already happened.

func (*Limiter) Rate

func (l *Limiter) Rate() float64

Rate returns the token refill rate per second.

func (*Limiter) SetBurst

func (l *Limiter) SetBurst(burst int)

SetBurst updates the burst limit.

func (*Limiter) SetRate

func (l *Limiter) SetRate(rate float64)

SetRate updates the rate limit.

func (*Limiter) Tokens

func (l *Limiter) Tokens() float64

Tokens returns the current number of available tokens.

func (*Limiter) Wait

func (l *Limiter) Wait() time.Duration

Wait waits until a token is available and consumes it.

func (*Limiter) WaitN

func (l *Limiter) WaitN(n int) time.Duration

WaitN waits until n tokens are available, consumes them, and returns the wait duration.

type QuotaExceededError

type QuotaExceededError struct {
	Resource  ResourceType
	Limit     int64
	Used      int64
	Requested int64
}

QuotaExceededError is returned when a quota is exceeded.

func (*QuotaExceededError) Error

func (e *QuotaExceededError) Error() string

type QuotaManager

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

QuotaManager manages resource quotas across sessions, agents, and tenants.

func NewQuotaManager

func NewQuotaManager(config Config) *QuotaManager

NewQuotaManager creates a new quota manager.

func (*QuotaManager) CheckAndConsume

func (q *QuotaManager) CheckAndConsume(ctx context.Context, scope, id string, resource ResourceType, amount int64) error

CheckAndConsume checks if quota allows consumption and consumes if so.

func (*QuotaManager) CheckRateLimit

func (q *QuotaManager) CheckRateLimit(sessionID string, resource ResourceType) (allowed bool, action LimitAction)

CheckRateLimit checks if an operation is allowed by rate limits.

func (*QuotaManager) GetQuota

func (q *QuotaManager) GetQuota(scope, id string, resource ResourceType) *ResourceQuota

GetQuota returns the current quota for a resource.

func (*QuotaManager) GetSessionLimiter

func (q *QuotaManager) GetSessionLimiter(sessionID string, resource ResourceType) *Limiter

GetSessionLimiter returns a rate limiter for a session and resource type.

func (*QuotaManager) GetUsage

func (q *QuotaManager) GetUsage(scope, id string, resource ResourceType) (used, limit int64, percentage float64)

GetUsage returns the current usage for a quota.

func (*QuotaManager) OnExceed

func (q *QuotaManager) OnExceed(fn func(id string, resource ResourceType, err *QuotaExceededError))

OnExceed sets a callback for quota exceeded events.

func (*QuotaManager) OnWarning

func (q *QuotaManager) OnWarning(fn func(id string, resource ResourceType, percentage float64))

OnWarning sets a callback for quota warnings (approaching limit).

func (*QuotaManager) ResetQuota

func (q *QuotaManager) ResetQuota(scope, id string, resource ResourceType)

ResetQuota resets a quota to zero usage.

func (*QuotaManager) WaitForRateLimit

func (q *QuotaManager) WaitForRateLimit(ctx context.Context, sessionID string, resource ResourceType) error

WaitForRateLimit waits until an operation is allowed by rate limits.

type ResourceQuota

type ResourceQuota struct {
	Resource   ResourceType `json:"resource"`
	Limit      int64        `json:"limit"`
	Used       int64        `json:"used"`
	ResetAt    time.Time    `json:"reset_at"`
	Percentage float64      `json:"percentage"`
	// contains filtered or unexported fields
}

ResourceQuota tracks usage of a resource.

type ResourceType

type ResourceType string

ResourceType identifies the type of resource being rate limited.

const (
	ResourceFileOps      ResourceType = "file_ops"
	ResourceNetworkConns ResourceType = "network_conns"
	ResourceDNSQueries   ResourceType = "dns_queries"
	ResourceOperations   ResourceType = "operations"
	ResourceStorage      ResourceType = "storage"
	ResourceNetworkBytes ResourceType = "network_bytes"
)

type SessionCounter

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

SessionCounter tracks concurrent session counts.

func NewSessionCounter

func NewSessionCounter(config Config) *SessionCounter

NewSessionCounter creates a new session counter.

func (*SessionCounter) GetCounts

func (c *SessionCounter) GetCounts() (global, agent, tenant map[string]int)

GetCounts returns current session counts.

func (*SessionCounter) ReleaseSession

func (c *SessionCounter) ReleaseSession(agentID, tenantID string)

ReleaseSession releases a session slot.

func (*SessionCounter) TryAcquireSession

func (c *SessionCounter) TryAcquireSession(agentID, tenantID string) error

TryAcquireSession attempts to acquire a session slot.

type SessionLimits

type SessionLimits struct {
	FileOpsPerSecond      float64 `json:"file_ops_per_second" yaml:"file_ops_per_second"`
	NetworkConnsPerSecond float64 `json:"network_conns_per_second" yaml:"network_conns_per_second"`
	DNSQueriesPerSecond   float64 `json:"dns_queries_per_second" yaml:"dns_queries_per_second"`
	BurstMultiplier       float64 `json:"burst_multiplier" yaml:"burst_multiplier"`
}

SessionLimits defines per-session rate limits.

type TenantLimits

type TenantLimits struct {
	MaxConcurrentSessions int   `json:"max_concurrent_sessions" yaml:"max_concurrent_sessions"`
	MaxStorageBytes       int64 `json:"max_storage_bytes" yaml:"max_storage_bytes"`
	MaxNetworkBytesPerDay int64 `json:"max_network_bytes_per_day" yaml:"max_network_bytes_per_day"`
}

TenantLimits defines per-tenant limits.

Jump to

Keyboard shortcuts

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