gravity

package
v1.0.99 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2025 License: MIT Imports: 36 Imported by: 0

README

Gravity Client

Generic gRPC client for connecting to Gravity servers. This package was extracted from the hadron project to enable reuse across multiple tools and projects.

Package Structure

  • gravity/ - Main gravity client implementation
  • gravity/proto/ - Protocol buffer definitions and generated code
  • gravity/provider/ - Provider interface definitions
  • gravity/network/ - Network interface definitions
  • gravity/api/ - API helper utilities

Module Path Conventions

All packages use the base module path: github.com/agentuity/go-common

  • Proto package: github.com/agentuity/go-common/gravity/proto
  • Provider interfaces: github.com/agentuity/go-common/gravity/provider
  • Network interfaces: github.com/agentuity/go-common/gravity/network
  • API utilities: github.com/agentuity/go-common/gravity/api

Usage

import (
    "github.com/agentuity/go-common/gravity"
    "github.com/agentuity/go-common/gravity/provider"
    "github.com/agentuity/go-common/gravity/network"
)

// Create gravity client with your provider and network implementations
config := gravity.GravityConfig{
    Provider:     myProvider,
    NetworkInterface: myNetworkInterface,
    // ... other config
}

client, err := gravity.New(config)
if err != nil {
    return err
}

if err := client.Start(); err != nil {
    return err
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrCircuitBreakerOpen    = errors.New("circuit breaker is open")
	ErrCircuitBreakerTimeout = errors.New("circuit breaker operation timeout")
	ErrTooManyFailures       = errors.New("too many consecutive failures")
)
View Source
var ErrConnectionClosed = errors.New("gravity connection closed")

Error variables for consistency with old implementation

Functions

func DefaultRetryableErrors

func DefaultRetryableErrors(err error) bool

DefaultRetryableErrors determines if an error is retryable by default

func ExponentialBackoff

func ExponentialBackoff(ctx context.Context, maxRetries int, initialBackoff time.Duration, fn RetryableFunc) error

ExponentialBackoff is a convenience function for exponential backoff retry

func LinearBackoff

func LinearBackoff(ctx context.Context, maxRetries int, backoffDuration time.Duration, fn RetryableFunc) error

LinearBackoff is a convenience function for linear backoff retry

func Provision added in v1.0.96

func Provision(request ProvisionRequest) (*pb.ProvisionResponse, error)

Provision calls the Provision gRPC method with TLS verification disabled This is a standalone method that should be used for initial provisioning

func Retry

func Retry(ctx context.Context, config RetryConfig, fn RetryableFunc) error

Retry executes a function with retry logic

func RetryWithCircuitBreaker

func RetryWithCircuitBreaker(ctx context.Context, retryConfig RetryConfig, circuitBreaker *CircuitBreaker, fn RetryableFunc) error

RetryWithCircuitBreaker combines retry logic with circuit breaker

Types

type CircuitBreaker

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

CircuitBreaker implements the circuit breaker pattern for fault tolerance

func NewCircuitBreaker

func NewCircuitBreaker(config CircuitBreakerConfig) *CircuitBreaker

NewCircuitBreaker creates a new circuit breaker with the given configuration

func (*CircuitBreaker) Execute

func (cb *CircuitBreaker) Execute(ctx context.Context, fn func() error) error

Execute wraps a function call with circuit breaker logic

func (*CircuitBreaker) Failures

func (cb *CircuitBreaker) Failures() int

Failures returns the current failure count

func (*CircuitBreaker) Reset

func (cb *CircuitBreaker) Reset()

Reset manually resets the circuit breaker to closed state

func (*CircuitBreaker) State

func (cb *CircuitBreaker) State() CircuitBreakerState

State returns the current state of the circuit breaker

func (*CircuitBreaker) Stats

func (cb *CircuitBreaker) Stats() CircuitBreakerStats

Stats returns current statistics

func (*CircuitBreaker) Successes

func (cb *CircuitBreaker) Successes() int

Successes returns the current success count (only relevant in half-open state)

func (*CircuitBreaker) TransitionToHalfOpen

func (cb *CircuitBreaker) TransitionToHalfOpen()

TransitionToHalfOpen transitions the circuit breaker to half-open state

type CircuitBreakerConfig

type CircuitBreakerConfig struct {
	// MaxFailures is the maximum number of failures before opening the circuit
	MaxFailures int

	// Timeout is how long to wait before transitioning from Open to Half-Open
	Timeout time.Duration

	// MaxConcurrentRequests is the max requests allowed in Half-Open state
	MaxConcurrentRequests int

	// SuccessThreshold is the number of consecutive successes needed in Half-Open to go to Closed
	SuccessThreshold int

	// RequestTimeout is the maximum time to wait for a single request
	RequestTimeout time.Duration
}

CircuitBreakerConfig defines configuration for the circuit breaker

func DefaultCircuitBreakerConfig

func DefaultCircuitBreakerConfig() CircuitBreakerConfig

DefaultCircuitBreakerConfig returns a default configuration

type CircuitBreakerState

type CircuitBreakerState int32

CircuitBreakerState represents the state of a circuit breaker

const (
	StateClosed CircuitBreakerState = iota
	StateHalfOpen
	StateOpen
)

func (CircuitBreakerState) String

func (s CircuitBreakerState) String() string

type CircuitBreakerStats

type CircuitBreakerStats struct {
	State     CircuitBreakerState
	Failures  int
	Successes int
	Requests  int
}

Stats returns statistics about the circuit breaker

type ConnectionPoolConfig

type ConnectionPoolConfig struct {
	// Connection pool size (4-8 connections as per PLAN.md)
	PoolSize int

	// Streams per connection for packet multiplexing
	StreamsPerConnection int

	// Stream allocation strategy
	AllocationStrategy StreamAllocationStrategy

	// Health check and failover settings
	HealthCheckInterval time.Duration
	FailoverTimeout     time.Duration
}

ConnectionPoolConfig holds configuration for gRPC connection pool optimization

type ErrorRateSample

type ErrorRateSample = pb.ErrorRateSample

Type aliases for protobuf types to maintain API compatibility

type GRPCConnectionMetrics

type GRPCConnectionMetrics = pb.GRPCConnectionMetrics

Type aliases for protobuf types to maintain API compatibility

type GravityClient

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

GravityClient implements the provider.Server interface using gRPC transport

func New

func New(config GravityConfig) (*GravityClient, error)

New creates a new gRPC-based Gravity server client

func (*GravityClient) Close

func (g *GravityClient) Close() error

Close will shutdown the client

func (*GravityClient) GetAPIURL

func (g *GravityClient) GetAPIURL() string

GetAPIURL returns the API URL received from gravity server

func (*GravityClient) GetConnectionPoolStats

func (g *GravityClient) GetConnectionPoolStats() map[string]any

GetConnectionPoolStats returns current connection pool statistics for monitoring

func (*GravityClient) GetDeploymentMetadata

func (g *GravityClient) GetDeploymentMetadata(ctx context.Context, deploymentID, orgID string) (*pb.DeploymentMetadataResponse, error)

GetDeploymentMetadata makes a gRPC call to get deployment metadata This is used by HTTP API server for provision requests

func (*GravityClient) GetHealthScore

func (g *GravityClient) GetHealthScore() float64

GetHealthScore returns the overall health score (0-100)

func (*GravityClient) GetIPv6Address

func (g *GravityClient) GetIPv6Address() string

GetIPv6Address returns the IPv6 address for external use

func (*GravityClient) GetInboundPackets

func (g *GravityClient) GetInboundPackets() <-chan *PooledBuffer

func (*GravityClient) GetSecret

func (g *GravityClient) GetSecret() string

GetSecret returns the authentication secret for external use

func (*GravityClient) GetServerMetrics

func (g *GravityClient) GetServerMetrics(reset bool) *pb.ServerMetrics

GetServerMetrics returns current server metrics with performance data

func (*GravityClient) GetTLSConfig

func (g *GravityClient) GetTLSConfig() *tls.Config

GetTLSConfig returns the TLS configuration for external use (like HTTP server)

func (*GravityClient) GetTextMessages

func (g *GravityClient) GetTextMessages() <-chan *PooledBuffer

func (*GravityClient) IsConnected

func (g *GravityClient) IsConnected() bool

func (*GravityClient) Pause

func (g *GravityClient) Pause(reason string) error

Pause sends a pause event to the gravity server

func (*GravityClient) Resume

func (g *GravityClient) Resume(reason string) error

Resume sends a resume event to the gravity server

func (*GravityClient) SendPacket

func (g *GravityClient) SendPacket(data []byte) error

func (*GravityClient) SendRouteDeploymentRequest

func (g *GravityClient) SendRouteDeploymentRequest(deploymentID, hostname, virtualIP string, timeout time.Duration) (*pb.RouteDeploymentResponse, error)

SendRouteDeploymentRequest sends a route deployment request and waits for response (sync)

func (*GravityClient) Start

func (g *GravityClient) Start() error

Start establishes gRPC connections and starts the client

func (*GravityClient) Unprovision

func (g *GravityClient) Unprovision(deploymentID string) error

Unprovision sends an unprovision request to the gravity server

func (*GravityClient) WritePacket

func (g *GravityClient) WritePacket(payload []byte) error

WritePacket sends a tunnel packet via gRPC tunnel stream using load balancing

type GravityConfig

type GravityConfig struct {
	Context              context.Context
	Logger               logger.Logger
	Provider             provider.Provider
	URL                  string
	Cert                 string
	Key                  string
	CACert               string
	IP4Address           string
	IP6Address           string
	InstanceID           string
	AuthToken            string
	ClientVersion        string
	ClientName           string
	Capabilities         *pb.ClientCapabilities
	PingInterval         time.Duration
	ReportInterval       time.Duration
	WorkingDir           string
	TraceLogPackets      bool
	NetworkInterface     network.NetworkInterface
	ConnectionPoolConfig *ConnectionPoolConfig
	ReportStats          bool
}

GravityConfig contains configuration for the Gravity client

type HealthSample

type HealthSample = pb.HealthSample

Type aliases for protobuf types to maintain API compatibility

type HistoricalMetrics

type HistoricalMetrics = pb.HistoricalMetrics

Type aliases for protobuf types to maintain API compatibility

type LatencySample

type LatencySample = pb.LatencySample

Type aliases for protobuf types to maintain API compatibility

type MessageStatistics

type MessageStatistics = pb.MessageStatistics

Type aliases for protobuf types to maintain API compatibility

type PooledBuffer

type PooledBuffer struct {
	Buffer []byte
	Length int
}

PooledBuffer represents a buffer from the pool

type ProvisionRequest added in v1.0.96

type ProvisionRequest struct {
	Context          context.Context
	GravityURL       string
	InstanceID       string
	Region           string
	AvailabilityZone string
	Provider         string
	PrivateIP        string
	Token            string
	PublicKey        string
	Hostname         string
	ErrorMessage     string
	Ephemeral        bool
	Capabilities     *pb.ClientCapabilities
}

type RetryConfig

type RetryConfig struct {
	// MaxRetries is the maximum number of retry attempts
	MaxRetries int

	// InitialBackoff is the initial backoff duration
	InitialBackoff time.Duration

	// MaxBackoff is the maximum backoff duration
	MaxBackoff time.Duration

	// BackoffMultiplier is the multiplier for exponential backoff
	BackoffMultiplier float64

	// Jitter adds randomness to backoff to avoid thundering herd
	Jitter bool

	// RetryableErrors is a function that determines if an error is retryable
	RetryableErrors func(error) bool
}

RetryConfig defines configuration for retry logic

func DefaultRetryConfig

func DefaultRetryConfig() RetryConfig

DefaultRetryConfig returns a default retry configuration

type RetryStats

type RetryStats struct {
	TotalAttempts   int
	SuccessfulCalls int
	FailedCalls     int
	TotalRetries    int
	AverageBackoff  time.Duration
	LastError       error
}

RetryStats tracks retry statistics

func RetryWithStats

func RetryWithStats(ctx context.Context, config RetryConfig, fn RetryableFunc) (RetryStats, error)

RetryWithStats executes a function with retry logic and tracks statistics

type RetryableFunc

type RetryableFunc func() error

RetryableFunc is a function that can be retried

type ServerMetrics

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

ServerMetrics represents enhanced server performance metrics with gRPC-specific data This wraps the protobuf ServerMetrics with a mutex for thread safety

func NewServerMetrics

func NewServerMetrics() *ServerMetrics

NewServerMetrics creates a new ServerMetrics instance

func (*ServerMetrics) AddHistoricalSample

func (sm *ServerMetrics) AddHistoricalSample()

AddHistoricalSample adds a sample to historical data

func (*ServerMetrics) GetHealthScore

func (sm *ServerMetrics) GetHealthScore() float64

GetHealthScore calculates an overall health score (0-100)

func (*ServerMetrics) GetSnapshot

func (sm *ServerMetrics) GetSnapshot() *pb.ServerMetrics

GetSnapshot returns a read-only snapshot of current metrics

func (*ServerMetrics) RecordMessage

func (sm *ServerMetrics) RecordMessage(messageType string, bytes int64, sent bool)

RecordMessage records a message transmission

func (*ServerMetrics) Reset

func (sm *ServerMetrics) Reset()

Reset resets all metrics to initial state

func (*ServerMetrics) UpdateConnection

func (sm *ServerMetrics) UpdateConnection(connected bool)

UpdateConnection updates connection-related metrics

func (*ServerMetrics) UpdateGRPCMetrics

func (sm *ServerMetrics) UpdateGRPCMetrics(grpcMetrics *GRPCConnectionMetrics)

UpdateGRPCMetrics updates gRPC-specific metrics

func (*ServerMetrics) UpdatePerformanceMetrics

func (sm *ServerMetrics) UpdatePerformanceMetrics(perfMetrics *pb.PerformanceMetrics)

UpdatePerformanceMetrics updates performance metrics from the collector

func (*ServerMetrics) UpdateSystemMetrics

func (sm *ServerMetrics) UpdateSystemMetrics()

UpdateSystemMetrics updates system resource metrics

type ServerMetricsSnapshot

type ServerMetricsSnapshot = pb.ServerMetrics

Type aliases for protobuf types to maintain API compatibility

type StreamAllocationStrategy

type StreamAllocationStrategy int

StreamAllocationStrategy defines how streams are selected for load distribution

const (
	RoundRobin StreamAllocationStrategy = iota
	HashBased
	LeastConnections
	WeightedRoundRobin
)

func (StreamAllocationStrategy) String

func (s StreamAllocationStrategy) String() string

String method for StreamAllocationStrategy enum

type StreamInfo

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

StreamInfo tracks individual stream health and load

type StreamManager

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

StreamManager manages multiple gRPC streams for multiplexing with advanced load balancing

type StreamMetrics

type StreamMetrics struct {
	PacketsSent     int64
	PacketsReceived int64
	LastLatency     time.Duration
	ErrorCount      int64
	LastError       time.Time
}

StreamMetrics tracks performance metrics for individual streams

type SystemResourceMetrics

type SystemResourceMetrics = pb.SystemResourceMetrics

Type aliases for protobuf types to maintain API compatibility

type ThroughputSample

type ThroughputSample = pb.ThroughputSample

Type aliases for protobuf types to maintain API compatibility

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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