nodes

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: MIT Imports: 26 Imported by: 0 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

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNodeNotFound      = errors.New("nodes: node not found")
	ErrInvalidNode       = errors.New("nodes: invalid registration")   // the node's fault, not the pool's
	ErrCorruptNode       = errors.New("nodes: unreadable node record") // Redis answered; the data is bad
	ErrNodeSlotExhausted = &nodeCapacityError{msg: "nodes: max concurrent requests reached"}
	ErrNodePoolFull      = &nodeCapacityError{msg: "nodes: all candidate nodes at capacity"}
	ErrNoAvailableNodes  = &nodeCapacityError{msg: "nodes: no healthy nodes available for model"}
)

Functions

func ValidateCIDRs

func ValidateCIDRs(remoteAddr string, allowedCIDRs []string) error

ValidateCIDRs checks whether remoteAddr belongs to any of the allowed CIDRs. If allowedCIDRs is empty, any remote address is permitted.

func ValidateEndpoint

func ValidateEndpoint(ctx context.Context, endpoint string, allowLocalhost bool) error

ValidateEndpoint checks that the endpoint URL is valid HTTP/HTTPS and prevents SSRF against localhost/loopback/link-local/cloud-metadata unless allowLocalhost is enabled.

Types

type Candidate

type Candidate struct {
	Snapshot        *NodeSnapshot
	ModelSpec       *pb.NodeModelSpec
	EffectiveWeight float64
	IsWarm          bool
}

type CircuitBreaker

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

CircuitBreaker manages failure tracking and half-open state for nodes. When error rate or consecutive errors trip the breaker, state transitions to CIRCUIT_BROKEN. A probe request can attempt half-open recovery using Redis SET NX.

func NewCircuitBreaker

func NewCircuitBreaker(rdb redis.UniversalClient, store *Store, failThresh int, cooldown time.Duration) *CircuitBreaker

func (*CircuitBreaker) IsBroken

func (cb *CircuitBreaker) IsBroken(ctx context.Context, nodeID string) (bool, error)

IsBroken checks if the circuit breaker is tripped.

func (*CircuitBreaker) RecordFailure

func (cb *CircuitBreaker) RecordFailure(ctx context.Context, nodeID string) error

RecordFailure increments consecutive failures; trips breaker if threshold exceeded.

func (*CircuitBreaker) RecordSuccess

func (cb *CircuitBreaker) RecordSuccess(ctx context.Context, nodeID string) error

RecordSuccess resets consecutive failure counters and clears circuit broken status.

func (*CircuitBreaker) TryAcquireProbe

func (cb *CircuitBreaker) TryAcquireProbe(ctx context.Context, nodeID string) (bool, error)

TryAcquireProbe attempts to acquire single probe slot during half-open state.

type Config

type Config struct {
	HeartbeatInterval time.Duration
	HeartbeatTTL      time.Duration
	RetentionTTL      time.Duration
	AllowLocalhost    bool
}

type LeaseManager

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

func NewLeaseManager

func NewLeaseManager(rdb redis.UniversalClient, store *Store) *LeaseManager

func (*LeaseManager) AcquireLease

func (lm *LeaseManager) AcquireLease(ctx context.Context, nodeID, reqID string, maxConc int32, ttl time.Duration) (bool, error)

AcquireLease attempts to take a slot on nodeID. Returns true if acquired.

func (*LeaseManager) ReleaseLease

func (lm *LeaseManager) ReleaseLease(ctx context.Context, nodeID, reqID string) error

ReleaseLease removes the lease from the ZSET.

func (*LeaseManager) RenewLease

func (lm *LeaseManager) RenewLease(ctx context.Context, nodeID, reqID string, extension time.Duration) (bool, error)

RenewLease extends lease expiration for streaming or long requests.

type Manager

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

func NewManager

func NewManager(store *Store, slots *LeaseManager, circuit *CircuitBreaker, telemetry *TelemetryTracker, cfg Config) *Manager

func (*Manager) Circuit

func (m *Manager) Circuit() *CircuitBreaker

func (*Manager) Config

func (m *Manager) Config() Config

func (*Manager) Drain

func (m *Manager) Drain(ctx context.Context, nodeID string) error

Drain marks a node for draining.

func (*Manager) GetNodeState

func (m *Manager) GetNodeState(ctx context.Context, nodeID string, hb *NodeHeartbeatData) (pb.NodeState, error)

GetNodeState calculates node state based on: 1. OFFLINE (heartbeat missing / expired) 2. DRAINING (operator requested or self reported) 3. CIRCUIT_BROKEN (circuit tripped) 4. SUSPECT (GPU temp >= 88C or high utilization) 5. HEALTHY

func (*Manager) Heartbeat

func (m *Manager) Heartbeat(ctx context.Context, hb *NodeHeartbeatData) (drainRequested bool, activeProxyRequests int32, err error)

Heartbeat processes node heartbeat and returns current state.

func (*Manager) ListNodes

func (m *Manager) ListNodes(ctx context.Context) ([]*NodeSnapshot, error)

ListNodes builds snapshot list for all known nodes.

func (*Manager) Register

func (m *Manager) Register(ctx context.Context, meta *NodeMeta) error

Register handles node self-registration.

func (*Manager) Slots

func (m *Manager) Slots() *LeaseManager

func (*Manager) Start

func (m *Manager) Start(ctx context.Context)

func (*Manager) Stop

func (m *Manager) Stop()

func (*Manager) Store

func (m *Manager) Store() *Store

func (*Manager) Telemetry

func (m *Manager) Telemetry() *TelemetryTracker

func (*Manager) Unregister

func (m *Manager) Unregister(ctx context.Context, nodeID string) error

Unregister handles graceful node unregistration.

type NodeHeartbeatData

type NodeHeartbeatData struct {
	NodeID         string              `json:"node_id"`
	LastHeartbeat  time.Time           `json:"last_heartbeat"`
	Draining       bool                `json:"draining"`
	ActiveRequests int32               `json:"active_requests"`
	QueueDepth     int32               `json:"queue_depth"`
	VRAMTotalMB    uint64              `json:"vram_total_mb"`
	VRAMFreeMB     uint64              `json:"vram_free_mb"`
	GPUUtilPercent float64             `json:"gpu_util_percent"`
	GPUTempC       uint32              `json:"gpu_temp_c"`
	GPUModel       string              `json:"gpu_model"`
	WarmModels     []string            `json:"warm_models"`
	ModelSpecs     []*pb.NodeModelSpec `json:"model_specs,omitempty"`
}

type NodeMeta

type NodeMeta struct {
	NodeID        string              `json:"node_id"`
	Name          string              `json:"name"`
	Endpoint      string              `json:"endpoint"`
	Engine        string              `json:"engine"`
	AuthToken     string              `json:"auth_token,omitempty"`
	BaseWeight    float64             `json:"base_weight"`
	MaxConcurrent int32               `json:"max_concurrent"`
	Models        []*pb.NodeModelSpec `json:"models"`
	Tags          map[string]string   `json:"tags,omitempty"`
	RegisteredAt  time.Time           `json:"registered_at"`
}

type NodePerfData

type NodePerfData struct {
	NodeID    string    `json:"node_id"`
	ModelID   string    `json:"model_id"`
	TPSEMA    float64   `json:"tps_ema"`
	TTFTEMAMs float64   `json:"ttft_ema_ms"`
	UpdatedAt time.Time `json:"updated_at"`
}

type NodeSnapshot

type NodeSnapshot struct {
	Meta      *NodeMeta
	Heartbeat *NodeHeartbeatData
	Perf      map[string]*NodePerfData // modelID -> perf
	Inflight  int32
	State     pb.NodeState
}

type PoolAdapter

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

func NewPoolAdapter

func NewPoolAdapter(selector *Selector, keyring *crypto.Keyring, model *proxydb.Model, leaseTTL time.Duration, userLimitResolver UserRateLimitResolver) *PoolAdapter

func (*PoolAdapter) EvaluateRollouts

func (pa *PoolAdapter) EvaluateRollouts(ctx context.Context, req *llm.EvaluateRolloutsRequest, userID string, meta map[string]string) (*llm.EvaluateRolloutsResult, error)

EvaluateRollouts scores multiple rollout candidate actions against a local node.

func (*PoolAdapter) GenerateText

func (pa *PoolAdapter) GenerateText(ctx context.Context, chat *llm.ChatContext) (*llm.Response, error)

func (*PoolAdapter) GenerateTextStream

func (pa *PoolAdapter) GenerateTextStream(ctx context.Context, chat *llm.ChatContext, onChunk func(llm.StreamChunk) error) error

func (*PoolAdapter) Judge

func (pa *PoolAdapter) Judge(ctx context.Context, req *llm.JudgeRequest, userID string, meta map[string]string) (*llm.JudgeResult, error)

Judge evaluates a decision request against a local node with judge capability.

func (*PoolAdapter) SupportsStreaming

func (pa *PoolAdapter) SupportsStreaming() bool

type PoolResolver

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

func NewPoolResolver

func NewPoolResolver(selector *Selector, keyring *crypto.Keyring, leaseTTL time.Duration) *PoolResolver

func (*PoolResolver) PoolAdapter

func (pr *PoolResolver) PoolAdapter(m *proxydb.Model) (llm.ClientAdapter, error)

func (*PoolResolver) SetUserRateLimitResolver

func (pr *PoolResolver) SetUserRateLimitResolver(resolver UserRateLimitResolver)

type Selector

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

func NewSelector

func NewSelector(mgr *Manager) *Selector

func (*Selector) SelectNode

func (s *Selector) SelectNode(ctx context.Context, modelID string) (*Candidate, error)

SelectNode performs candidate filtering and weighted selection: 1. Filter by model support, state (HEALTHY over SUSPECT, probe CIRCUIT_BROKEN when no healthy/suspect). 2. Strict warm over cold filter: if any warm node has capacity, cold nodes are eliminated. 3. Compute effective weights: W_eff = base_weight * F_perf * F_load. 4. Smooth WRR selection.

func (*Selector) SelectNodeForCapability

func (s *Selector) SelectNodeForCapability(ctx context.Context, modelID string, capability string) (*Candidate, error)

SelectNodeForCapability performs candidate filtering and weighted selection, optionally filtering for a specific capability (e.g. "judge").

type Store

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

Store interacts with Redis to persist and query node status.

func NewStore

func NewStore(rdb redis.UniversalClient, keys rediskeys.Keys) *Store

func (*Store) ClearDrain

func (s *Store) ClearDrain(ctx context.Context, nodeID string) error

ClearDrain removes draining flag.

func (*Store) GetAllNodeIDs

func (s *Store) GetAllNodeIDs(ctx context.Context) ([]string, error)

GetAllNodeIDs returns all node IDs in the pool.

func (*Store) GetHeartbeat

func (s *Store) GetHeartbeat(ctx context.Context, nodeID string) (*NodeHeartbeatData, error)

GetHeartbeat retrieves node heartbeat.

func (*Store) GetInflightCount

func (s *Store) GetInflightCount(ctx context.Context, nodeID string, now time.Time) (int32, error)

GetInflightCount returns the number of active leases in the ZSET.

func (*Store) GetMeta

func (s *Store) GetMeta(ctx context.Context, nodeID string) (*NodeMeta, error)

GetMeta retrieves node metadata.

func (*Store) IsDraining

func (s *Store) IsDraining(ctx context.Context, nodeID string) (bool, error)

IsDraining checks if node is marked for draining.

func (*Store) Keys

func (s *Store) Keys() rediskeys.Keys

Keys returns the configured rediskeys.Keys.

func (*Store) RemoveNode

func (s *Store) RemoveNode(ctx context.Context, nodeID string) error

RemoveNode completely evicts a node from Redis.

func (*Store) SaveHeartbeat

func (s *Store) SaveHeartbeat(ctx context.Context, hb *NodeHeartbeatData, ttl time.Duration) error

SaveHeartbeat updates the dynamic heartbeat record with TTL.

func (*Store) SaveMeta

func (s *Store) SaveMeta(ctx context.Context, meta *NodeMeta, ttl time.Duration) error

SaveMeta saves static node metadata and adds nodeID to nodes:all set.

func (*Store) SetDrain

func (s *Store) SetDrain(ctx context.Context, nodeID string) error

SetDrain marks a node for draining.

func (*Store) UpdateMeta added in v0.14.0

func (s *Store) UpdateMeta(ctx context.Context, nodeID string, fn func(*NodeMeta) bool) (bool, error)

UpdateMeta rewrites a node's meta in place when fn reports a change. It keeps the remaining TTL and, through WATCH, gives up rather than overwrite a registration or removal that happened meanwhile; a missing node is left missing.

type TelemetryTracker

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

func NewTelemetryTracker

func NewTelemetryTracker(rdb redis.UniversalClient, store *Store, alpha float64, ttl time.Duration) *TelemetryTracker

func (*TelemetryTracker) GetPerf

func (tt *TelemetryTracker) GetPerf(ctx context.Context, nodeID, modelID string) (*NodePerfData, error)

GetPerf retrieves performance metrics for node and model.

func (*TelemetryTracker) RecordMetrics

func (tt *TelemetryTracker) RecordMetrics(ctx context.Context, nodeID, modelID string, tps float64, ttftNormalizedMs float64) error

RecordMetrics updates EWMA for a node & model. For unary calls, ttftNormalizedMs may be <= 0.

type UserRateLimitResolver

type UserRateLimitResolver func(userID, modelID string) *proxydb.UserRateLimit

Jump to

Keyboard shortcuts

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