services

package
v1.0.73 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2025 License: Apache-2.0 Imports: 25 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func HTTPClientMiddleware

func HTTPClientMiddleware(config SecureHTTPClientConfig) func(*http.Client) *http.Client

HTTPClientMiddleware provides HTTP client configuration middleware

func NewSecureHTTPClient

func NewSecureHTTPClient(config SecureHTTPClientConfig) *http.Client

NewSecureHTTPClient creates a secure HTTP client with comprehensive timeout configurations

func SecureHTTPClientExample

func SecureHTTPClientExample() *http.Client

SecureHTTPClientExample demonstrates secure HTTP client usage

func ServiceClientMiddleware

func ServiceClientMiddleware(client *ServiceClient) lift.Middleware

ServiceClientMiddleware creates middleware for service client integration

func ValidateHTTPClientSecurity

func ValidateHTTPClientSecurity(client *http.Client) []string

ValidateHTTPClientSecurity validates HTTP client security configuration

Types

type CacheStats

type CacheStats struct {
	Hits       int64   `json:"hits"`
	Misses     int64   `json:"misses"`
	Sets       int64   `json:"sets"`
	Deletes    int64   `json:"deletes"`
	Errors     int64   `json:"errors"`
	HitRate    float64 `json:"hit_rate"`
	AvgLatency int64   `json:"avg_latency_ns"`
	Size       int64   `json:"size"`
	Memory     int64   `json:"memory_bytes"`
}

CacheStats provides cache performance metrics (reusing from features package)

type CheckResult

type CheckResult struct {
	Status  string `json:"status"`
	Message string `json:"message"`
	Latency int64  `json:"latency_ms"`
}

CheckResult represents the result of a health check

type CircuitBreaker

type CircuitBreaker interface {
	Execute(fn func() (any, error)) (any, error)
	GetState() CircuitBreakerState
	GetStats() CircuitBreakerStats
}

CircuitBreaker defines the interface for circuit breaking

type CircuitBreakerState

type CircuitBreakerState string

CircuitBreakerState represents circuit breaker states

const (
	CircuitBreakerClosed   CircuitBreakerState = "closed"
	CircuitBreakerOpen     CircuitBreakerState = "open"
	CircuitBreakerHalfOpen CircuitBreakerState = "half_open"
)

type CircuitBreakerStats

type CircuitBreakerStats struct {
	LastStateChange    time.Time           `json:"last_state_change"`
	State              CircuitBreakerState `json:"state"`
	TotalRequests      int64               `json:"total_requests"`
	SuccessfulRequests int64               `json:"successful_requests"`
	FailedRequests     int64               `json:"failed_requests"`
}

CircuitBreakerStats provides circuit breaker metrics

type Counter

type Counter = lift.Counter

Counter is re-exported from lift package

type CreateUserRequest

type CreateUserRequest struct {
	Metadata map[string]string `json:"metadata"`
	Email    string            `json:"email"`
	Name     string            `json:"name"`
	TenantID string            `json:"tenant_id"`
}

CreateUserRequest represents a user creation request

type DefaultLoadBalancer

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

DefaultLoadBalancer implements multiple load balancing strategies Memory optimized: 56 → 32 bytes (24 bytes saved)

func NewDefaultLoadBalancer

func NewDefaultLoadBalancer() *DefaultLoadBalancer

NewDefaultLoadBalancer creates a new load balancer

func (*DefaultLoadBalancer) GetStats

func (lb *DefaultLoadBalancer) GetStats() LoadBalancerStats

GetStats returns load balancer statistics

func (*DefaultLoadBalancer) ReleaseConnection

func (lb *DefaultLoadBalancer) ReleaseConnection(instanceID string)

ReleaseConnection decrements the connection count for an instance

func (*DefaultLoadBalancer) Reset

func (lb *DefaultLoadBalancer) Reset()

Reset resets all counters and statistics

func (*DefaultLoadBalancer) Select

func (lb *DefaultLoadBalancer) Select(instances []*ServiceInstance, strategy LoadBalanceStrategy) *ServiceInstance

Select selects an instance using the specified strategy

func (*DefaultLoadBalancer) UpdateWeights

func (lb *DefaultLoadBalancer) UpdateWeights(_ []*ServiceInstance) error

UpdateWeights updates the weights of instances

type DiscoveryOptions

type DiscoveryOptions struct {
	TenantID         string              `json:"tenant_id,omitempty"`
	Strategy         LoadBalanceStrategy `json:"strategy"`
	Version          string              `json:"version,omitempty"`
	Region           string              `json:"region,omitempty"`
	Tags             []string            `json:"tags"`
	MaxInstances     int                 `json:"max_instances"`
	IncludeUnhealthy bool                `json:"include_unhealthy"`
	PreferLocal      bool                `json:"prefer_local"`
}

DiscoveryOptions configures service discovery behavior

type DynamoDBEventBus added in v1.0.71

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

DynamoDBEventBus implements EventBus using DynamoDB for durable storage This implementation is serverless-safe and survives Lambda container recycling

func NewDynamoDBEventBus added in v1.0.71

func NewDynamoDBEventBus(client *dynamodb.Client, config EventBusConfig) *DynamoDBEventBus

NewDynamoDBEventBus creates a new DynamoDB-backed event bus

func (*DynamoDBEventBus) BatchPublish added in v1.0.71

func (d *DynamoDBEventBus) BatchPublish(ctx context.Context, events []*Event) ([]string, error)

BatchPublish publishes multiple events in a batch operation This is more efficient than publishing events one at a time

func (*DynamoDBEventBus) DeleteEvent added in v1.0.71

func (d *DynamoDBEventBus) DeleteEvent(ctx context.Context, eventID string) error

DeleteEvent removes an event from DynamoDB

func (*DynamoDBEventBus) GetEvent added in v1.0.71

func (d *DynamoDBEventBus) GetEvent(ctx context.Context, eventID string) (*Event, error)

GetEvent retrieves a specific event by ID This uses a scan which can be slow - consider adding a GSI on ID if needed

func (*DynamoDBEventBus) ProcessStreamRecord added in v1.0.71

func (d *DynamoDBEventBus) ProcessStreamRecord(ctx context.Context, record map[string]dynamodbtypes.AttributeValue) error

ProcessStreamRecord processes a DynamoDB Stream record This is typically called from a Lambda function triggered by DynamoDB Streams

func (*DynamoDBEventBus) Publish added in v1.0.71

func (d *DynamoDBEventBus) Publish(ctx context.Context, event *Event) (string, error)

Publish publishes an event to DynamoDB with retry logic

func (*DynamoDBEventBus) Query added in v1.0.71

func (d *DynamoDBEventBus) Query(ctx context.Context, query *EventQuery) ([]*Event, error)

Query retrieves events based on filters using DynamoDB query

func (*DynamoDBEventBus) Subscribe added in v1.0.71

func (d *DynamoDBEventBus) Subscribe(_ context.Context, eventType string, handler EventHandler) error

Subscribe registers a handler (for DynamoDB Streams integration) Note: This stores handlers in memory and won't persist across Lambda restarts For production, use DynamoDB Streams + Lambda triggers instead

func (*DynamoDBEventBus) WithCloudWatch added in v1.0.71

func (d *DynamoDBEventBus) WithCloudWatch(client *cloudwatch.Client) *DynamoDBEventBus

WithCloudWatch adds CloudWatch client for metrics

type Event added in v1.0.71

type Event struct {
	// Primary identifiers and timestamps (8-byte aligned)
	PublishedAt time.Time `json:"published_at" dynamodbav:"published_at"`
	CreatedAt   time.Time `json:"created_at" dynamodbav:"created_at"`
	ExpiresAt   time.Time `json:"expires_at,omitempty" dynamodbav:"expires_at,omitempty"`

	// String fields (16 bytes each)
	ID            string `json:"id" dynamodbav:"id"`                 // ULID for ordering
	EventType     string `json:"event_type" dynamodbav:"event_type"` // e.g., "partner.created"
	TenantID      string `json:"tenant_id" dynamodbav:"tenant_id"`   // For multi-tenancy
	SourceID      string `json:"source_id" dynamodbav:"source_id"`   // Source entity ID
	PartitionKey  string `json:"partition_key" dynamodbav:"pk"`      // DynamoDB partition key
	SortKey       string `json:"sort_key" dynamodbav:"sk"`           // DynamoDB sort key
	CorrelationID string `json:"correlation_id,omitempty" dynamodbav:"correlation_id,omitempty"`

	// Complex types
	Payload  json.RawMessage   `json:"payload" dynamodbav:"payload"`                       // Event data
	Metadata map[string]string `json:"metadata,omitempty" dynamodbav:"metadata,omitempty"` // Additional context
	Tags     []string          `json:"tags,omitempty" dynamodbav:"tags,omitempty"`         // For filtering

	// Smaller numeric types
	Version    int `json:"version" dynamodbav:"version"`         // Schema version
	RetryCount int `json:"retry_count" dynamodbav:"retry_count"` // For failed processing
}

Event represents a single event in the system

func NewEvent added in v1.0.71

func NewEvent(eventType, tenantID, sourceID string, payload interface{}) (*Event, error)

NewEvent creates a new event with generated ID and timestamps

func (*Event) UnmarshalPayload added in v1.0.71

func (e *Event) UnmarshalPayload(v interface{}) error

UnmarshalPayload unmarshals the event payload into the provided struct

func (*Event) WithCorrelationID added in v1.0.71

func (e *Event) WithCorrelationID(correlationID string) *Event

WithCorrelationID sets a correlation ID for tracing related events

func (*Event) WithMetadata added in v1.0.71

func (e *Event) WithMetadata(key, value string) *Event

WithMetadata adds metadata to the event

func (*Event) WithTTL added in v1.0.71

func (e *Event) WithTTL(ttl time.Duration) *Event

WithTTL sets an expiration time for the event

func (*Event) WithTags added in v1.0.71

func (e *Event) WithTags(tags ...string) *Event

WithTags adds tags to the event

type EventBus added in v1.0.71

type EventBus interface {
	// Publish publishes an event to the bus and returns the event ID
	Publish(ctx context.Context, event *Event) (string, error)

	// Query retrieves events based on filters
	Query(ctx context.Context, query *EventQuery) ([]*Event, error)

	// Subscribe registers a handler for specific event types (for stream processing)
	Subscribe(ctx context.Context, eventType string, handler EventHandler) error

	// GetEvent retrieves a specific event by ID
	GetEvent(ctx context.Context, eventID string) (*Event, error)

	// DeleteEvent removes an event (for cleanup/GDPR)
	DeleteEvent(ctx context.Context, eventID string) error
}

EventBus defines the interface for publishing and consuming events This interface is designed to work in serverless environments with DynamoDB backing

type EventBusConfig added in v1.0.71

type EventBusConfig struct {
	TableName        string
	MetricsNamespace string
	TTL              time.Duration
	RetryBaseDelay   time.Duration
	RetryAttempts    int
	MaxBatchSize     int
	EnableMetrics    bool
}

EventBusConfig configures the event bus behavior

func DefaultEventBusConfig added in v1.0.71

func DefaultEventBusConfig() EventBusConfig

DefaultEventBusConfig returns sensible defaults

type EventHandler added in v1.0.71

type EventHandler func(ctx context.Context, event *Event) error

EventHandler is a function that processes events

type EventQuery added in v1.0.71

type EventQuery struct {
	LastEvaluatedKey map[string]interface{}
	NextKey          map[string]interface{} // Returned pagination token for next query
	StartTime        *time.Time
	EndTime          *time.Time
	TenantID         string
	EventType        string
	Tags             []string
	Limit            int
}

EventQuery defines parameters for querying events

type Gauge

type Gauge = lift.Gauge

Gauge is re-exported from lift package

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient defines the interface for HTTP operations

type HealthAwareLoadBalancer

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

HealthAwareLoadBalancer wraps a load balancer with health awareness

func NewHealthAwareLoadBalancer

func NewHealthAwareLoadBalancer(delegate LoadBalancer, healthThreshold time.Duration) *HealthAwareLoadBalancer

NewHealthAwareLoadBalancer creates a health-aware load balancer

func (*HealthAwareLoadBalancer) GetStats

GetStats delegates to the underlying load balancer

func (*HealthAwareLoadBalancer) Select

Select selects an instance with health awareness

func (*HealthAwareLoadBalancer) UpdateWeights

func (h *HealthAwareLoadBalancer) UpdateWeights(instances []*ServiceInstance) error

UpdateWeights delegates to the underlying load balancer

type HealthCheckConfig

type HealthCheckConfig struct {
	Path             string        `json:"path"`
	Interval         time.Duration `json:"interval"`
	Timeout          time.Duration `json:"timeout"`
	Retries          int           `json:"retries"`
	FailureThreshold int           `json:"failure_threshold"`
	SuccessThreshold int           `json:"success_threshold"`
	Enabled          bool          `json:"enabled"`
}

HealthCheckConfig configures health checking for a service

type HealthStatus

type HealthStatus struct {
	Timestamp time.Time              `json:"timestamp"`
	Checks    map[string]CheckResult `json:"checks"`
	Status    string                 `json:"status"`
	Message   string                 `json:"message"`
}

HealthStatus represents the health status of a service

type Histogram

type Histogram = lift.Histogram

Histogram is re-exported from lift package

type LoadBalanceStrategy

type LoadBalanceStrategy string

LoadBalanceStrategy defines load balancing strategies

const (
	RoundRobin       LoadBalanceStrategy = "round_robin"
	WeightedRandom   LoadBalanceStrategy = "weighted_random"
	LeastConnections LoadBalanceStrategy = "least_connections"
	HealthyFirst     LoadBalanceStrategy = "healthy_first"
	LocalFirst       LoadBalanceStrategy = "local_first"
)

type LoadBalancer

type LoadBalancer interface {
	Select(instances []*ServiceInstance, strategy LoadBalanceStrategy) *ServiceInstance
	UpdateWeights(instances []*ServiceInstance) error
	GetStats() LoadBalancerStats
}

LoadBalancer defines the interface for load balancing

func NewHealthyFirstLoadBalancer

func NewHealthyFirstLoadBalancer(healthThreshold time.Duration) LoadBalancer

NewHealthyFirstLoadBalancer creates a health-first load balancer

func NewLeastConnectionsLoadBalancer

func NewLeastConnectionsLoadBalancer() LoadBalancer

NewLeastConnectionsLoadBalancer creates a least connections load balancer

func NewRoundRobinLoadBalancer

func NewRoundRobinLoadBalancer() LoadBalancer

NewRoundRobinLoadBalancer creates a round-robin load balancer

func NewWeightedRandomLoadBalancer

func NewWeightedRandomLoadBalancer() LoadBalancer

NewWeightedRandomLoadBalancer creates a weighted random load balancer

type LoadBalancerMetrics

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

LoadBalancerMetrics tracks load balancer performance

type LoadBalancerStats

type LoadBalancerStats struct {
	TotalRequests        int64 `json:"total_requests"`
	SuccessfulSelections int64 `json:"successful_selections"`
	FailedSelections     int64 `json:"failed_selections"`
	AverageLatency       int64 `json:"average_latency_ns"`
}

LoadBalancerStats provides load balancer metrics

type MemoryEventBus added in v1.0.71

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

MemoryEventBus provides an in-memory implementation for testing and development WARNING: This is NOT suitable for production Lambda environments as events are lost when the Lambda container scales down or is recycled

func NewMemoryEventBus added in v1.0.71

func NewMemoryEventBus() *MemoryEventBus

NewMemoryEventBus creates a new in-memory event bus This should only be used for testing or local development

func (*MemoryEventBus) Clear added in v1.0.71

func (m *MemoryEventBus) Clear()

Clear removes all events (useful for testing)

func (*MemoryEventBus) Count added in v1.0.71

func (m *MemoryEventBus) Count() int

Count returns the total number of events

func (*MemoryEventBus) DeleteEvent added in v1.0.71

func (m *MemoryEventBus) DeleteEvent(_ context.Context, eventID string) error

DeleteEvent removes an event from the bus

func (*MemoryEventBus) GetEvent added in v1.0.71

func (m *MemoryEventBus) GetEvent(_ context.Context, eventID string) (*Event, error)

GetEvent retrieves a specific event by ID

func (*MemoryEventBus) Publish added in v1.0.71

func (m *MemoryEventBus) Publish(ctx context.Context, event *Event) (string, error)

Publish stores an event in memory and triggers handlers

func (*MemoryEventBus) Query added in v1.0.71

func (m *MemoryEventBus) Query(_ context.Context, query *EventQuery) ([]*Event, error)

Query retrieves events based on filters

func (*MemoryEventBus) Subscribe added in v1.0.71

func (m *MemoryEventBus) Subscribe(_ context.Context, eventType string, handler EventHandler) error

Subscribe registers a handler for specific event types

type MemoryServiceCache

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

MemoryServiceCache implements an in-memory service discovery cache Memory optimized: 32 → 24 bytes (8 bytes saved)

func (*MemoryServiceCache) Clear

func (c *MemoryServiceCache) Clear()

Clear removes all entries from cache

func (*MemoryServiceCache) Delete

func (c *MemoryServiceCache) Delete(key string)

Delete removes an entry from cache

func (*MemoryServiceCache) Get

func (c *MemoryServiceCache) Get(key string) ([]*ServiceInstance, bool)

Get retrieves service instances from cache

func (*MemoryServiceCache) Set

func (c *MemoryServiceCache) Set(key string, instances []*ServiceInstance, ttl time.Duration)

Set stores service instances in cache

func (*MemoryServiceCache) Stats

func (c *MemoryServiceCache) Stats() CacheStats

Stats returns cache statistics

type MetricsCollector

type MetricsCollector = lift.MetricsCollector

MetricsCollector is re-exported from lift package

type MultiTierServiceCache

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

MultiTierServiceCache implements a multi-tier caching strategy

func NewMultiTierServiceCache

func NewMultiTierServiceCache(l1Cache, l2Cache ServiceCache) *MultiTierServiceCache

NewMultiTierServiceCache creates a multi-tier cache

func (*MultiTierServiceCache) Clear

func (m *MultiTierServiceCache) Clear()

Clear clears both caches

func (*MultiTierServiceCache) Delete

func (m *MultiTierServiceCache) Delete(key string)

Delete removes from both caches

func (*MultiTierServiceCache) Get

Get retrieves from L1 cache first, then L2 cache

func (*MultiTierServiceCache) Set

func (m *MultiTierServiceCache) Set(key string, instances []*ServiceInstance, ttl time.Duration)

Set stores in both L1 and L2 caches

func (*MultiTierServiceCache) Stats

func (m *MultiTierServiceCache) Stats() CacheStats

Stats returns combined statistics

type RegistryConfig

type RegistryConfig struct {
	CacheTTL            time.Duration `json:"cache_ttl"`
	HealthCheckInterval time.Duration `json:"health_check_interval"`
	MaxRetries          int           `json:"max_retries"`
	RetryBackoff        time.Duration `json:"retry_backoff"`
	EnableCaching       bool          `json:"enable_caching"`
	EnableMetrics       bool          `json:"enable_metrics"`
	TenantIsolation     bool          `json:"tenant_isolation"`
}

RegistryConfig configures the service registry

type RegistryStats

type RegistryStats struct {
	Timestamp          time.Time         `json:"timestamp"`
	CacheStats         CacheStats        `json:"cache_stats"`
	LoadBalancerStats  LoadBalancerStats `json:"load_balancer_stats"`
	RegisteredServices int               `json:"registered_services"`
}

RegistryStats provides registry performance metrics

type RetryPolicy

type RetryPolicy struct {
	RetryableStatusCodes []int         `json:"retryable_status_codes"`
	RetryableErrors      []string      `json:"retryable_errors"`
	MaxRetries           int           `json:"max_retries"`
	InitialBackoff       time.Duration `json:"initial_backoff"`
	MaxBackoff           time.Duration `json:"max_backoff"`
	BackoffMultiplier    float64       `json:"backoff_multiplier"`
}

RetryPolicy defines retry behavior

type SecureHTTPClientConfig

type SecureHTTPClientConfig struct {
	UserAgent              string        `json:"user_agent"`
	MaxIdleConns           int           `json:"max_idle_conns"`
	ResponseTimeout        time.Duration `json:"response_timeout"`
	KeepAliveTimeout       time.Duration `json:"keepalive_timeout"`
	TLSHandshakeTimeout    time.Duration `json:"tls_handshake_timeout"`
	ConnectTimeout         time.Duration `json:"connect_timeout"`
	MaxIdleConnsPerHost    int           `json:"max_idle_conns_per_host"`
	MaxConnsPerHost        int           `json:"max_conns_per_host"`
	IdleConnTimeout        time.Duration `json:"idle_conn_timeout"`
	MaxResponseHeaderBytes int64         `json:"max_response_header_bytes"`
	RequestTimeout         time.Duration `json:"request_timeout"`
	InsecureSkipVerify     bool          `json:"insecure_skip_verify"`
	DisableCompression     bool          `json:"disable_compression"`
	DisableKeepAlives      bool          `json:"disable_keep_alives"`
}

SecureHTTPClientConfig provides comprehensive HTTP client security configuration

func DefaultSecureHTTPClientConfig

func DefaultSecureHTTPClientConfig() SecureHTTPClientConfig

DefaultSecureHTTPClientConfig returns secure default configuration

func DevelopmentHTTPClientConfig

func DevelopmentHTTPClientConfig() SecureHTTPClientConfig

DevelopmentHTTPClientConfig returns development-friendly configuration

func ProductionHTTPClientConfig

func ProductionHTTPClientConfig() SecureHTTPClientConfig

ProductionHTTPClientConfig returns production-ready configuration

type ServiceCache

type ServiceCache interface {
	Get(key string) ([]*ServiceInstance, bool)
	Set(key string, instances []*ServiceInstance, ttl time.Duration)
	Delete(key string)
	Clear()
	Stats() CacheStats
}

ServiceCache defines the interface for service discovery caching

func NewMemoryServiceCache

func NewMemoryServiceCache() ServiceCache

NewMemoryServiceCache creates a new in-memory service cache

func NewMemoryServiceCacheWithSize

func NewMemoryServiceCacheWithSize(maxSize int) ServiceCache

NewMemoryServiceCacheWithSize creates a cache with specified max size

type ServiceClient

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

ServiceClient provides type-safe inter-service communication Memory optimized: 24 → 8 bytes (16 bytes saved)

func GetServiceClient

func GetServiceClient(ctx *lift.Context) *ServiceClient

GetServiceClient retrieves the service client from context

func NewServiceClient

func NewServiceClient(registry *ServiceRegistry, config ServiceClientConfig) *ServiceClient

NewServiceClient creates a new service client

func (*ServiceClient) Call

func (c *ServiceClient) Call(ctx context.Context, request *ServiceRequest) (*ServiceResponse, error)

Call makes a type-safe service call with automatic discovery

type ServiceClientConfig

type ServiceClientConfig struct {
	// Strings (16 bytes) - largest first
	UserAgent string `json:"user_agent"`

	// 8-byte types
	DefaultTimeout time.Duration `json:"default_timeout"`
	RetryBackoff   time.Duration `json:"retry_backoff"`

	// 4-byte types
	MaxRetries int `json:"max_retries"`

	// Booleans (1 byte each) - smallest last
	EnableTracing        bool `json:"enable_tracing"`
	EnableMetrics        bool `json:"enable_metrics"`
	EnableCircuitBreaker bool `json:"enable_circuit_breaker"`
	TenantIsolation      bool `json:"tenant_isolation"`
}

ServiceClientConfig configures the service client Memory optimized: 24 → 8 bytes (16 bytes saved)

type ServiceConfig

type ServiceConfig struct {
	Created     time.Time         `json:"created"`
	LastSeen    time.Time         `json:"last_seen"`
	Metadata    map[string]string `json:"metadata"`
	Name        string            `json:"name"`
	Version     string            `json:"version"`
	TenantID    string            `json:"tenant_id,omitempty"`
	Region      string            `json:"region"`
	Environment string            `json:"environment"`
	Endpoints   []ServiceEndpoint `json:"endpoints"`
	Tags        []string          `json:"tags"`
	HealthCheck HealthCheckConfig `json:"health_check"`
	Weight      int               `json:"weight"`
}

ServiceConfig represents a service configuration

type ServiceDiscovery

type ServiceDiscovery interface {
	Register(ctx context.Context, config *ServiceConfig) error
	Deregister(ctx context.Context, serviceID string) error
	Discover(ctx context.Context, serviceName string) ([]*ServiceInstance, error)
	Watch(ctx context.Context, serviceName string) (<-chan []*ServiceInstance, error)
	HealthCheck(ctx context.Context, instance *ServiceInstance) (*HealthStatus, error)
}

ServiceDiscovery defines the interface for service discovery backends

type ServiceEndpoint

type ServiceEndpoint struct {
	Metadata map[string]string `json:"metadata"`
	Protocol string            `json:"protocol"`
	Host     string            `json:"host"`
	Path     string            `json:"path"`
	Port     int               `json:"port"`
}

ServiceEndpoint represents a service endpoint

type ServiceInstance

type ServiceInstance struct {
	LastSeen    time.Time         `json:"last_seen"`
	Metadata    map[string]string `json:"metadata"`
	Health      HealthStatus      `json:"health"`
	ID          string            `json:"id"`
	ServiceName string            `json:"service_name"`
	Version     string            `json:"version"`
	TenantID    string            `json:"tenant_id,omitempty"`
	Endpoint    ServiceEndpoint   `json:"endpoint"`
	Weight      int               `json:"weight"`
}

ServiceInstance represents a discovered service instance

type ServiceRegistry

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

ServiceRegistry manages service registration and discovery

func NewServiceRegistry

func NewServiceRegistry(config RegistryConfig, discovery ServiceDiscovery, loadBalancer LoadBalancer) *ServiceRegistry

NewServiceRegistry creates a new service registry

func (*ServiceRegistry) Deregister

func (r *ServiceRegistry) Deregister(ctx context.Context, serviceID string) error

Deregister removes a service from the registry

func (*ServiceRegistry) Discover

func (r *ServiceRegistry) Discover(ctx context.Context, serviceName string, opts DiscoveryOptions) (*ServiceInstance, error)

Discover discovers service instances

func (*ServiceRegistry) DiscoverAll

func (r *ServiceRegistry) DiscoverAll(ctx context.Context, serviceName string, opts DiscoveryOptions) ([]*ServiceInstance, error)

DiscoverAll discovers all instances of a service

func (*ServiceRegistry) GetService

func (r *ServiceRegistry) GetService(serviceName string) (*ServiceConfig, bool)

GetService returns a service configuration

func (*ServiceRegistry) GetStats

func (r *ServiceRegistry) GetStats() RegistryStats

GetStats returns registry statistics

func (*ServiceRegistry) ListServices

func (r *ServiceRegistry) ListServices() []*ServiceConfig

ListServices returns all registered services

func (*ServiceRegistry) Register

func (r *ServiceRegistry) Register(ctx context.Context, config *ServiceConfig) error

Register registers a service with the registry

func (*ServiceRegistry) Watch

func (r *ServiceRegistry) Watch(ctx context.Context, serviceName string) (<-chan []*ServiceInstance, error)

Watch watches for changes to a service

type ServiceRequest

type ServiceRequest struct {
	Body                any                 `json:"body"`
	Headers             map[string]string   `json:"headers"`
	Metadata            map[string]any      `json:"metadata"`
	LoadBalanceStrategy LoadBalanceStrategy `json:"load_balance_strategy"`
	ServiceName         string              `json:"service_name"`
	Method              string              `json:"method"`
	Path                string              `json:"path"`
	TenantID            string              `json:"tenant_id,omitempty"`
	UserID              string              `json:"user_id,omitempty"`
	RequestID           string              `json:"request_id,omitempty"`
	Timeout             time.Duration       `json:"timeout"`
}

ServiceRequest represents a service call request Memory optimized: 144 → 136 bytes (8 bytes saved)

type ServiceResponse

type ServiceResponse struct {
	Headers    map[string]string `json:"headers"`
	Metadata   map[string]any    `json:"metadata"`
	Instance   *ServiceInstance  `json:"instance"`
	Body       []byte            `json:"body"`
	Duration   time.Duration     `json:"duration"`
	StatusCode int               `json:"status_code"`
}

ServiceResponse represents a service call response

type TTLServiceCache

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

TTLServiceCache wraps a cache with automatic TTL cleanup Memory optimized: 32 → 24 bytes (8 bytes saved)

func NewTTLServiceCache

func NewTTLServiceCache(delegate ServiceCache, cleanupInterval time.Duration) *TTLServiceCache

NewTTLServiceCache creates a cache with automatic TTL cleanup

func (*TTLServiceCache) Clear

func (t *TTLServiceCache) Clear()

Clear delegates to the underlying cache

func (*TTLServiceCache) Close

func (t *TTLServiceCache) Close()

Close stops the cleanup goroutine

func (*TTLServiceCache) Delete

func (t *TTLServiceCache) Delete(key string)

Delete delegates to the underlying cache

func (*TTLServiceCache) Get

func (t *TTLServiceCache) Get(key string) ([]*ServiceInstance, bool)

Get delegates to the underlying cache

func (*TTLServiceCache) Set

func (t *TTLServiceCache) Set(key string, instances []*ServiceInstance, ttl time.Duration)

Set delegates to the underlying cache

func (*TTLServiceCache) Stats

func (t *TTLServiceCache) Stats() CacheStats

Stats delegates to the underlying cache

type UpdateUserRequest

type UpdateUserRequest struct {
	Email    *string           `json:"email,omitempty"`
	Name     *string           `json:"name,omitempty"`
	Metadata map[string]string `json:"metadata,omitempty"`
}

UpdateUserRequest represents a user update request

type User

type User struct {
	CreatedAt time.Time         `json:"created_at"`
	UpdatedAt time.Time         `json:"updated_at"`
	Metadata  map[string]string `json:"metadata"`
	ID        string            `json:"id"`
	Email     string            `json:"email"`
	Name      string            `json:"name"`
	TenantID  string            `json:"tenant_id"`
}

User represents a user entity

type UserFilters

type UserFilters struct {
	TenantID string `json:"tenant_id,omitempty"`
	Email    string `json:"email,omitempty"`
	Limit    int    `json:"limit,omitempty"`
	Offset   int    `json:"offset,omitempty"`
}

UserFilters represents user listing filters

type UserList

type UserList struct {
	Users  []*User `json:"users"`
	Total  int     `json:"total"`
	Limit  int     `json:"limit"`
	Offset int     `json:"offset"`
}

UserList represents a list of users

type UserService

type UserService interface {
	GetUser(ctx context.Context, userID string) (*User, error)
	CreateUser(ctx context.Context, user *CreateUserRequest) (*User, error)
	UpdateUser(ctx context.Context, userID string, updates *UpdateUserRequest) (*User, error)
	DeleteUser(ctx context.Context, userID string) error
	ListUsers(ctx context.Context, filters *UserFilters) (*UserList, error)
}

UserService defines the interface for user service operations

func NewUserServiceClient

func NewUserServiceClient(client *ServiceClient, tenantID string) UserService

NewUserServiceClient creates a new user service client

type UserServiceClient

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

UserServiceClient implements the UserService interface

func (*UserServiceClient) CreateUser

func (u *UserServiceClient) CreateUser(ctx context.Context, user *CreateUserRequest) (*User, error)

CreateUser creates a new user

func (*UserServiceClient) DeleteUser

func (u *UserServiceClient) DeleteUser(ctx context.Context, userID string) error

DeleteUser deletes a user

func (*UserServiceClient) GetUser

func (u *UserServiceClient) GetUser(ctx context.Context, userID string) (*User, error)

GetUser retrieves a user by ID

func (*UserServiceClient) ListUsers

func (u *UserServiceClient) ListUsers(ctx context.Context, filters *UserFilters) (*UserList, error)

ListUsers lists users with optional filters

func (*UserServiceClient) UpdateUser

func (u *UserServiceClient) UpdateUser(ctx context.Context, userID string, updates *UpdateUserRequest) (*User, error)

UpdateUser updates an existing user

type WeightedLoadBalancer

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

WeightedLoadBalancer implements weighted load balancing with dynamic weight adjustment Memory optimized: 48 → 24 bytes (24 bytes saved)

func NewWeightedLoadBalancer

func NewWeightedLoadBalancer(delegate LoadBalancer) *WeightedLoadBalancer

NewWeightedLoadBalancer creates a weighted load balancer

func (*WeightedLoadBalancer) GetStats

GetStats delegates to the underlying load balancer

func (*WeightedLoadBalancer) GetWeight

func (w *WeightedLoadBalancer) GetWeight(instanceID string) int

GetWeight gets the weight for a specific instance

func (*WeightedLoadBalancer) Select

func (w *WeightedLoadBalancer) Select(instances []*ServiceInstance, strategy LoadBalanceStrategy) *ServiceInstance

Select selects an instance using weighted selection

func (*WeightedLoadBalancer) SetWeight

func (w *WeightedLoadBalancer) SetWeight(instanceID string, weight int)

SetWeight sets the weight for a specific instance

func (*WeightedLoadBalancer) UpdateWeights

func (w *WeightedLoadBalancer) UpdateWeights(_ []*ServiceInstance) error

UpdateWeights updates weights based on performance metrics

Directories

Path Synopsis
Package kernel provides authenticated cross-account calls to kernel services.
Package kernel provides authenticated cross-account calls to kernel services.

Jump to

Keyboard shortcuts

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