rpcpool

package
v0.0.12 Latest Latest
Warning

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

Go to latest
Published: Jan 13, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client interface {
	// Ping performs a basic health check on the client
	Ping(ctx context.Context) error

	// Close closes the client connection
	Close() error
}

Client defines a generic interface for RPC clients that can be used in the pool Both EVM (*ethclient.Client) and SVM (*rpc.Client) clients implement this through adapters

type ClientFactory

type ClientFactory func(url string) (Client, error)

ClientFactory creates chain-specific clients for a given URL This function is provided by each chain implementation (EVM, SVM) to create their specific client types

type Endpoint

type Endpoint struct {
	URL        string
	Client     Client // Generic client interface
	State      EndpointState
	Metrics    *EndpointMetrics
	LastUsed   time.Time
	ExcludedAt time.Time // When this endpoint was excluded
	// contains filtered or unexported fields
}

Endpoint represents a single RPC endpoint with its client and metrics

func NewEndpoint

func NewEndpoint(url string) *Endpoint

NewEndpoint creates a new RPC endpoint

func (*Endpoint) GetClient

func (e *Endpoint) GetClient() Client

GetClient returns the RPC client (thread-safe)

func (*Endpoint) GetState

func (e *Endpoint) GetState() EndpointState

GetState returns the current state (thread-safe)

func (*Endpoint) IsHealthy

func (e *Endpoint) IsHealthy() bool

IsHealthy returns true if endpoint is in a usable state

func (*Endpoint) SetClient

func (e *Endpoint) SetClient(client Client)

SetClient sets the RPC client for this endpoint

func (*Endpoint) UpdateState

func (e *Endpoint) UpdateState(state EndpointState)

UpdateState updates the endpoint state (thread-safe)

type EndpointInfo

type EndpointInfo struct {
	URL            string    `json:"url"`
	State          string    `json:"state"`
	HealthScore    float64   `json:"health_score"`
	LastUsed       time.Time `json:"last_used"`
	RequestCount   uint64    `json:"request_count"`
	FailureCount   uint64    `json:"failure_count"`
	TotalLatency   int64     `json:"total_latency_ms"`
	AverageLatency float64   `json:"average_latency_ms"`
}

EndpointInfo represents information about a single endpoint

type EndpointMetrics

type EndpointMetrics struct {
	TotalRequests       uint64
	SuccessfulRequests  uint64
	FailedRequests      uint64
	AverageLatency      time.Duration
	ConsecutiveFailures int
	LastSuccessTime     time.Time
	LastErrorTime       time.Time
	LastError           error
	HealthScore         float64 // 0-100, calculated from success rate and latency
	// contains filtered or unexported fields
}

EndpointMetrics tracks performance and health metrics for an endpoint

func (*EndpointMetrics) GetConsecutiveFailures

func (m *EndpointMetrics) GetConsecutiveFailures() int

GetConsecutiveFailures returns consecutive failure count (thread-safe)

func (*EndpointMetrics) GetHealthScore

func (m *EndpointMetrics) GetHealthScore() float64

GetHealthScore returns the current health score (thread-safe)

func (*EndpointMetrics) GetSuccessRate

func (m *EndpointMetrics) GetSuccessRate() float64

GetSuccessRate returns the success rate (thread-safe)

func (*EndpointMetrics) UpdateFailure

func (m *EndpointMetrics) UpdateFailure(err error, latency time.Duration)

UpdateFailure updates metrics for a failed request

func (*EndpointMetrics) UpdateSuccess

func (m *EndpointMetrics) UpdateSuccess(latency time.Duration)

UpdateSuccess updates metrics for a successful request

type EndpointSelector

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

EndpointSelector handles endpoint selection based on different strategies

func NewEndpointSelector

func NewEndpointSelector(strategy LoadBalancingStrategy) *EndpointSelector

NewEndpointSelector creates a new endpoint selector with the specified strategy

func (*EndpointSelector) GetStrategy

func (s *EndpointSelector) GetStrategy() LoadBalancingStrategy

GetStrategy returns the current strategy

func (*EndpointSelector) SelectEndpoint

func (s *EndpointSelector) SelectEndpoint(healthyEndpoints []*Endpoint) *Endpoint

SelectEndpoint selects an endpoint from the healthy endpoints based on the configured strategy

type EndpointState

type EndpointState int

EndpointState represents the current state of an RPC endpoint

const (
	StateHealthy EndpointState = iota
	StateDegraded
	StateUnhealthy
	StateExcluded
)

func (EndpointState) String

func (s EndpointState) String() string

type EndpointStats

type EndpointStats struct {
	ChainID        string         `json:"chain_id"`
	TotalEndpoints int            `json:"total_endpoints"`
	Strategy       string         `json:"strategy"`
	Endpoints      []EndpointInfo `json:"endpoints"`
}

EndpointStats represents statistics for endpoints

type EndpointStatus

type EndpointStatus struct {
	URL          string    `json:"url"`
	State        string    `json:"state"`
	HealthScore  float64   `json:"health_score"`
	ResponseTime int64     `json:"response_time_ms"`
	LastChecked  time.Time `json:"last_checked"`
	LastError    string    `json:"last_error,omitempty"`
}

EndpointStatus represents the status of a single endpoint

type HealthChecker

type HealthChecker interface {
	CheckHealth(ctx context.Context, client Client) error
}

HealthChecker defines the interface for checking endpoint health Each chain type (EVM, SVM) implements this with chain-specific logic

type HealthMonitor

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

HealthMonitor monitors the health of RPC endpoints and manages recovery

func NewHealthMonitor

func NewHealthMonitor(manager *Manager, config *config.RPCPoolConfig, logger zerolog.Logger) *HealthMonitor

NewHealthMonitor creates a new health monitor

func (*HealthMonitor) GetHealthStatus

func (h *HealthMonitor) GetHealthStatus() *HealthStatus

GetHealthStatus returns a summary of endpoint health

func (*HealthMonitor) SetHealthChecker

func (h *HealthMonitor) SetHealthChecker(checker HealthChecker)

SetHealthChecker sets the health checker implementation

func (*HealthMonitor) Start

func (h *HealthMonitor) Start(ctx context.Context, wg *sync.WaitGroup)

Start begins the health monitoring loop

func (*HealthMonitor) Stop

func (h *HealthMonitor) Stop()

Stop stops the health monitor

type HealthStatus

type HealthStatus struct {
	ChainID        string           `json:"chain_id"`
	TotalEndpoints int              `json:"total_endpoints"`
	HealthyCount   int              `json:"healthy_count"`
	UnhealthyCount int              `json:"unhealthy_count"`
	DegradedCount  int              `json:"degraded_count"`
	ExcludedCount  int              `json:"excluded_count"`
	Strategy       string           `json:"strategy"`
	Endpoints      []EndpointStatus `json:"endpoints"`
}

HealthStatus represents the health status of the RPC pool

type LoadBalancingStrategy

type LoadBalancingStrategy string

LoadBalancingStrategy defines how requests are distributed across endpoints

const (
	StrategyRoundRobin LoadBalancingStrategy = "round-robin"
	StrategyWeighted   LoadBalancingStrategy = "weighted"
)

type Manager

type Manager struct {
	HealthMonitor *HealthMonitor // Exported for external access
	// contains filtered or unexported fields
}

Manager manages a pool of RPC endpoints with load balancing and health checking

func NewManager

func NewManager(
	chainID string,
	urls []string,
	poolConfig *config.RPCPoolConfig,
	clientFactory ClientFactory,
	logger zerolog.Logger,
) *Manager

NewManager creates a new RPC pool manager

func (*Manager) GetConfig

func (m *Manager) GetConfig() *config.RPCPoolConfig

GetConfig returns the pool configuration (for health monitor access)

func (*Manager) GetEndpointStats

func (m *Manager) GetEndpointStats() *EndpointStats

GetEndpointStats returns statistics about all endpoints

func (*Manager) GetEndpoints

func (m *Manager) GetEndpoints() []*Endpoint

GetEndpoints returns all endpoints (for health monitor access)

func (*Manager) GetHealthyEndpointCount

func (m *Manager) GetHealthyEndpointCount() int

GetHealthyEndpointCount returns the count of healthy endpoints

func (*Manager) SelectEndpoint

func (m *Manager) SelectEndpoint() (*Endpoint, error)

SelectEndpoint selects an available endpoint based on the configured strategy

func (*Manager) Start

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

Start initializes all endpoints and starts health monitoring

func (*Manager) Stop

func (m *Manager) Stop()

Stop stops the pool manager and health monitoring

func (*Manager) UpdateEndpointMetrics

func (m *Manager) UpdateEndpointMetrics(endpoint *Endpoint, success bool, latency time.Duration, err error)

UpdateEndpointMetrics updates metrics for an endpoint after a request

Jump to

Keyboard shortcuts

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