subzero

package module
v0.0.0-...-2224170 Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2025 License: MIT Imports: 15 Imported by: 0

README

SubZero - GO Client

Go Reference Go Report Card

SubZero is a high-performance Go client for Subzero Server, a distributed disk-first cache system. It provides both gRPC and TCP protocols with comprehensive error handling, retry logic, and connection pooling.

Features

  • Dual Protocol Support: gRPC (recommended) and TCP text protocol
  • Connection Pooling: Configurable connection pools for optimal performance
  • Automatic Retries: Intelligent retry logic with exponential backoff
  • Comprehensive Error Handling: Structured error types with detailed context
  • Production Ready: Extensive configuration options and professional error handling
  • Type Safety: Full type safety with protobuf-generated types
  • Performance Optimized: Sub-millisecond latency for same-server deployment

Installation

go get github.com/mr-alejandroo/subzero-client

Quick Start

Basic gRPC Client
package main

import (
    "log"
    
    "github.com/mr-alejandroo/subzero-client"
)

func main() {
    // Create Client
    client, err := subzero.NewClient(subzero.DefaultConfig())
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()

    // Set Value
    err = client.Set("user:1001", []byte(`{"name":"Alice","age":30}`), nil)
    if err != nil {
        log.Fatal(err)
    }

    // Get Value
    value, err := client.Get("user:1001")
    if err != nil {
        log.Fatal(err)
    }

    if value != nil {
        log.Printf("Retrieved: %s", string(value))
    }
}
Delete Operation
found, err := client.Delete("key")
if found {
    log.Println("Key was deleted")
} else {
    log.Println("Key was not found")
}
Health and Metrics
// Health check
health, err := client.Health()
if err == nil {
    log.Printf("Status: %s, Uptime: %ds", health.Status, health.UptimeSeconds)
}

// Prometheus metrics
metrics, err := client.Metrics()
if err == nil {
    log.Printf("Metrics: %s", metrics)
}
TCP Client

For simple integrations, use the TCP text protocol:

// Create TCP client
tcpClient, err := subzero.NewTCPClient(subzero.DefaultTCPConfig())
if err != nil {
    log.Fatal(err)
}
defer tcpClient.Close()

// Test connectivity
err = tcpClient.Ping()

// Set and get
err = tcpClient.Set("key", "value")
value, err := tcpClient.Get("key")

// Delete
found, err := tcpClient.Delete("key")

Error Handling

SubZero provides comprehensive error handling with structured error types:

err := client.Set("", []byte("value"), nil)
if err != nil {
    if subzero.IsCacheError(err) {
        cacheErr := subzero.GetCacheError(err)
        log.Printf("Cache error: %s (code: %s, retryable: %t)", 
                  cacheErr.Message, cacheErr.Code, cacheErr.IsRetryable())
    }
    
    // Check specific error types
    if subzero.IsConnectionError(err) {
        log.Println("Connection error - check server availability")
    }
    
    if subzero.IsTimeoutError(err) {
        log.Println("Timeout error - consider increasing timeout")
    }
    
    if subzero.IsKeyNotFoundError(err) {
        log.Println("Key not found")
    }
}

Configuration Options

ClientConfig (gRPC)
Field Type Default Description
Address string "127.0.0.1:8080" Server address
MaxConnections int 4 Connection pool size
ConnectTimeout time.Duration 5s Connection timeout
RequestTimeout time.Duration 100ms Request timeout
KeepAliveTime time.Duration 10s Keep-alive interval
KeepAliveTimeout time.Duration 1s Keep-alive timeout
MaxRetries int 3 Maximum retry attempts
InitialBackoff time.Duration 10ms Initial retry delay
MaxBackoff time.Duration 1s Maximum retry delay
BackoffMultiplier float64 2.0 Backoff multiplier
EnablePooling bool true Enable connection pooling
PoolReuse bool true Enable context reuse
EnableTLS bool false Enable TLS
TCPClientConfig (TCP)
Field Type Default Description
Address string "127.0.0.1:8081" Server address
ConnectTimeout time.Duration 5s Connection timeout
ReadTimeout time.Duration 1s Read timeout
WriteTimeout time.Duration 1s Write timeout
MaxRetries int 3 Maximum retry attempts
RetryDelay time.Duration 100ms Retry delay
KeepAlive bool true Enable TCP keep-alive

Performance Comparisons

COMING SOON...

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrClientClosed     = errors.New("client is closed")
	ErrInvalidKey       = errors.New("key cannot be empty")
	ErrInvalidValue     = errors.New("value cannot be nil")
	ErrConnectionFailed = errors.New("connection failed")
	ErrTimeout          = errors.New("operation timed out")
	ErrServerError      = errors.New("server error")
	ErrInvalidConfig    = errors.New("invalid configuration")
	ErrKeyNotFound      = errors.New("key not found")
	ErrOperationFailed  = errors.New("operation failed")
)

Error types

Functions

func IsCacheError

func IsCacheError(err error) bool

Checks if an error is a CacheError

func IsConnectionError

func IsConnectionError(err error) bool

Checks if an error is related to connection issues

func IsKeyNotFoundError

func IsKeyNotFoundError(err error) bool

Checks if an error indicates a key was not found

func IsRetryableError

func IsRetryableError(err error) bool

Checks if an error should trigger a retry

func IsTimeoutError

func IsTimeoutError(err error) bool

Checks if an error is related to timeouts

func WrapGRPCError

func WrapGRPCError(err error, operation string) error

Converts a gRPC error to a CacheError

func WrapTCPError

func WrapTCPError(err error, operation string) error

Converts a TCP error to a CacheError

Types

type CacheError

type CacheError struct {
	Code      ErrorCode `json:"code"`
	Message   string    `json:"message"`
	Operation string    `json:"operation"`
	Key       string    `json:"key,omitempty"`
	Cause     error     `json:"cause,omitempty"`
	Retryable bool      `json:"retryable"`
}

func GetCacheError

func GetCacheError(err error) *CacheError

Extracts a CacheError from an error chain

func NewCacheError

func NewCacheError(code ErrorCode, message, operation string) *CacheError

Creates a new CacheError

func NewCacheErrorWithCause

func NewCacheErrorWithCause(code ErrorCode, message, operation string, cause error) *CacheError

Creates a new CacheError with an underlying cause

func NewCacheErrorWithKey

func NewCacheErrorWithKey(code ErrorCode, message, operation, key string) *CacheError

Creates a new CacheError with a key

func (*CacheError) Error

func (e *CacheError) Error() string

Error Interface

func (*CacheError) IsRetryable

func (e *CacheError) IsRetryable() bool

Returns whether this error should trigger a retry

func (*CacheError) IsTemporary

func (e *CacheError) IsTemporary() bool

Returns whether this is a temporary error

func (*CacheError) Unwrap

func (e *CacheError) Unwrap() error

type Client

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

Subzero Client

func NewClient

func NewClient(config *ClientConfig) (*Client, error)

func (*Client) BatchGet

func (c *Client) BatchGet(keys []string) (map[string][]byte, error)

BatchGet retrieves multiple keys in a single operation

func (*Client) BatchSet

func (c *Client) BatchSet(items map[string][]byte, ttlSeconds *uint64) error

BatchSet stores multiple key-value pairs in a single operation

func (*Client) Close

func (c *Client) Close() error

Close closes all connections and cleans up resources

func (*Client) Delete

func (c *Client) Delete(key string) (bool, error)

Delete removes a key from the cache

func (*Client) Get

func (c *Client) Get(key string) ([]byte, error)

Get retrieves a value by key from the cache

func (*Client) GetConfig

func (c *Client) GetConfig() ClientConfig

GetConfig returns a copy of the client configuration

func (*Client) GetWithMetadata

func (c *Client) GetWithMetadata(key string) ([]byte, *pb.EntryMetadata, error)

GetWithMetadata retrieves a value and its metadata by key

func (*Client) Health

func (c *Client) Health() (*pb.HealthResponse, error)

Health checks the health of the cache server

func (*Client) IsConnected

func (c *Client) IsConnected() bool

IsConnected checks if the client has active connections

func (*Client) Metrics

func (c *Client) Metrics() (string, error)

Retrive server metrics (Prometheus format)

func (*Client) Set

func (c *Client) Set(key string, value []byte, ttlSeconds *uint64) error

Set stores a key-value pair in the cache

type ClientConfig

type ClientConfig struct {
	// Connection settings
	Address          string        `json:"address"`
	MaxConnections   int           `json:"max_connections"`
	ConnectTimeout   time.Duration `json:"connect_timeout"`
	RequestTimeout   time.Duration `json:"request_timeout"`
	KeepAliveTime    time.Duration `json:"keep_alive_time"`
	KeepAliveTimeout time.Duration `json:"keep_alive_timeout"`

	// Retry settings
	MaxRetries        int           `json:"max_retries"`
	InitialBackoff    time.Duration `json:"initial_backoff"`
	MaxBackoff        time.Duration `json:"max_backoff"`
	BackoffMultiplier float64       `json:"backoff_multiplier"`

	// Connection pool settings
	EnablePooling bool `json:"enable_pooling"`
	PoolReuse     bool `json:"pool_reuse"`

	// TLS settings
	EnableTLS     bool   `json:"enable_tls"`
	TLSServerName string `json:"tls_server_name"`
}

func DefaultConfig

func DefaultConfig() *ClientConfig

func ProductionConfig

func ProductionConfig(address string) *ClientConfig

type ErrorCode

type ErrorCode int
const (
	ErrorCodeUnknown ErrorCode = iota
	ErrorCodeInvalidKey
	ErrorCodeInvalidValue
	ErrorCodeInvalidConfig
	ErrorCodeConnectionFailed
	ErrorCodeTimeout
	ErrorCodeServerError
	ErrorCodeKeyNotFound
	ErrorCodeOperationFailed
	ErrorCodeClientClosed
	ErrorCodeTooManyRetries
	ErrorCodeResourceExhausted
	ErrorCodePermissionDenied
)

func (ErrorCode) String

func (e ErrorCode) String() string

type ErrorReporter

type ErrorReporter struct {
	OnError func(err *CacheError)
}

Provides structured error reporting capabilities

func NewErrorReporter

func NewErrorReporter(onError func(err *CacheError)) *ErrorReporter

Creates a new error reporter

func (*ErrorReporter) ReportError

func (r *ErrorReporter) ReportError(err error)

Reports an error if it's a CacheError

type TCPClient

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

TCP Protocol Client

func NewTCPClient

func NewTCPClient(config *TCPClientConfig) (*TCPClient, error)

Create new TCP client with given config

func (*TCPClient) Close

func (c *TCPClient) Close() error

Close closes the TCP connection

func (*TCPClient) Delete

func (c *TCPClient) Delete(key string) (bool, error)

func (*TCPClient) Get

func (c *TCPClient) Get(key string) (string, error)

func (*TCPClient) GetConfig

func (c *TCPClient) GetConfig() TCPClientConfig

func (*TCPClient) IsConnected

func (c *TCPClient) IsConnected() bool

func (*TCPClient) Ping

func (c *TCPClient) Ping() error

func (*TCPClient) Set

func (c *TCPClient) Set(key, value string) error

type TCPClientConfig

type TCPClientConfig struct {
	Address        string        `json:"address"`
	ConnectTimeout time.Duration `json:"connect_timeout"`
	ReadTimeout    time.Duration `json:"read_timeout"`
	WriteTimeout   time.Duration `json:"write_timeout"`
	MaxRetries     int           `json:"max_retries"`
	RetryDelay     time.Duration `json:"retry_delay"`
	KeepAlive      bool          `json:"keep_alive"`
}

func DefaultTCPConfig

func DefaultTCPConfig() *TCPClientConfig

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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