realtime

package
v0.0.0-...-5b201f8 Latest Latest
Warning

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

Go to latest
Published: Apr 7, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

README

realtime

WebSocket hub for real-time flag updates.

Architecture

┌──────────────┐     ┌───────────┐     ┌──────────────┐
│  Flag Write  │────▶│   Redis   │────▶│     Hub      │
│   (API)      │     │  pub/sub  │     │              │
└──────────────┘     └───────────┘     └──────┬───────┘
                                              │
                     ┌────────────────────────┼────────────────────────┐
                     ▼                        ▼                        ▼
              ┌────────────┐          ┌────────────┐          ┌────────────┐
              │ Connection │          │ Connection │          │ Connection │
              │   (SDK)    │          │   (SDK)    │          │   (SDK)    │
              └────────────┘          └────────────┘          └────────────┘

Usage

Server Setup
redisClient := redis.NewClient(&redis.Options{Addr: "localhost:6379"})

hub := realtime.NewHub(redisClient, realtime.DefaultHubConfig())

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

go hub.Run(ctx)

handler := realtime.NewHandler(hub, validator, realtime.HandlerConfig{
    RequireAuth: true,
})

http.Handle("/ws", handler)
Publishing Changes

When a flag is updated via your API, publish to Redis:

publisher := realtime.NewPublisher(redisClient, realtime.PublisherConfig{})

publisher.PublishFlagUpdated(ctx, "env-production", &realtime.FlagConfig{
    Key:     "dark-mode",
    Enabled: true,
    Version: 5,
}, "user-123")

WebSocket Protocol

Client → Server
{"type": "subscribe", "environmentId": "env-abc"}
{"type": "unsubscribe", "environmentId": "env-abc"}
{"type": "ping"}
Server → Client
{"type": "connected", "connectionId": "uuid"}
{"type": "subscribed", "environmentId": "env-abc"}
{"type": "flag_updated", "environmentId": "env-abc", "flag": {...}}
{"type": "flag_deleted", "environmentId": "env-abc", "flagKey": "my-flag"}
{"type": "error", "code": "forbidden", "message": "access denied"}

Configuration

realtime.HubConfig{
    RedisChannelPattern:  "hoist:flagchange:*",  // Redis pub/sub pattern
    PingInterval:         30 * time.Second,        // Ping frequency
    PongTimeout:          10 * time.Second,        // Dead connection threshold
    MaxConnectionsPerKey: 100,                     // Per-API-key limit
    BroadcastBufferSize:  256,                     // Message buffer size
}

Files

File Description
hub.go Connection management, Redis listener, broadcast
connection.go WebSocket read/write pumps, message handling
messages.go Message types, flag config structures
handler.go HTTP upgrade handler with auth
publisher.go Redis publish helper

Documentation

Overview

Package realtime provides a WebSocket-based real-time flag update system.

Architecture

The package implements a hub-and-spoke architecture where:

  • Hub: Central coordinator that manages connections and broadcasts
  • Connection: Individual WebSocket client connection
  • Publisher: Helper for publishing flag changes to Redis

Flow

┌─────────────┐     ┌─────────────┐     ┌─────────────┐
│  API Write  │────▶│  PostgreSQL │────▶│ pg_notify() │
└─────────────┘     └─────────────┘     └──────┬──────┘
                                               │
                    ┌──────────────────────────┘
                    ▼
              ┌───────────┐     ┌───────────────┐
              │  Listener │────▶│ Redis PUBLISH │
              └───────────┘     └───────┬───────┘
                                        │
         ┌──────────────────────────────┼───────────────┐
         ▼                              ▼               ▼
┌─────────────────┐          ┌─────────────────┐    ┌─────┐
│ Server Pod 1    │          │ Server Pod 2    │    │ ... │
│ - Delete cache  │          │ - Delete cache  │    │     │
│ - Push to WS    │          │ - Push to WS    │    │     │
└─────────────────┘          └─────────────────┘    └─────┘

Usage

Basic setup:

redisClient := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
hub := realtime.NewHub(redisClient, realtime.DefaultHubConfig())

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

go hub.Run(ctx)

handler := realtime.NewHandler(hub, validator, realtime.HandlerConfig{
    RequireAuth: true,
})
http.Handle("/ws", handler)

Publishing flag changes:

publisher := realtime.NewPublisher(redisClient, realtime.PublisherConfig{})
publisher.PublishFlagUpdated(ctx, "env-production", &realtime.FlagConfig{
    Key:     "my-flag",
    Enabled: true,
    Version: 5,
}, "user-123")

WebSocket Protocol

Client messages:

{"type": "subscribe", "environmentId": "env-123"}
{"type": "unsubscribe", "environmentId": "env-123"}
{"type": "ping"}
{"type": "pong"}

Server messages:

{"type": "connected", "connectionId": "uuid"}
{"type": "subscribed", "environmentId": "env-123"}
{"type": "flag_updated", "environmentId": "env-123", "flag": {...}}
{"type": "flag_deleted", "environmentId": "env-123", "flagKey": "my-flag"}
{"type": "error", "code": "forbidden", "message": "access denied"}

Redis Pub/Sub

The hub subscribes to Redis channels matching the pattern "hoist:flagchange:*". When a flag changes, publish a JSON message to "hoist:flagchange:{envID}":

{
    "action": "updated",
    "environmentId": "env-123",
    "flagKey": "my-flag",
    "flag": { ... },
    "timestamp": 1234567890,
    "changedBy": "user-123"
}

Configuration

Key configuration options:

  • RedisChannelPattern: Pattern for Redis pub/sub (default: "hoist:flagchange:*")
  • PingInterval: How often to ping connections (default: 30s)
  • PongTimeout: How long to wait for pong (default: 10s)
  • MaxConnectionsPerKey: Connection limit per API key (default: 100)

Metrics

The hub exposes metrics via hub.Metrics():

  • ConnectionsTotal: Total connections ever made
  • ConnectionsCurrent: Current active connections
  • SubscriptionsTotal: Total subscriptions ever made
  • MessagesReceived: Messages received from Redis
  • MessagesBroadcast: Messages broadcast to clients
  • Errors: Total errors

Package realtime provides WebSocket-based real-time flag update propagation.

Architecture:

┌─────────────────────────────────────────────────────────────┐
│                         Hub                                  │
│                                                              │
│  connections: map[connID]*Connection                        │
│  subscriptions: map[envID]map[connID]struct{}               │
│                                                              │
│  Goroutines:                                                 │
│  - Run(): main event loop (register/unregister/broadcast)   │
│  - listenRedis(): subscribes to Redis pub/sub               │
│  - pingLoop(): sends pings to detect dead connections       │
└─────────────────────────────────────────────────────────────┘

The Hub receives flag change notifications via Redis pub/sub and broadcasts them to all WebSocket clients subscribed to the affected environment.

Index

Constants

View Source
const (
	ClientMessageTypeSubscribe   = "subscribe"
	ClientMessageTypeUnsubscribe = "unsubscribe"
	ClientMessageTypePing        = "ping"
	ClientMessageTypePong        = "pong"
)

Client message types (client -> server)

View Source
const (
	MessageTypeConnected    = "connected"
	MessageTypeSubscribed   = "subscribed"
	MessageTypeUnsubscribed = "unsubscribed"
	MessageTypeFlagCreated  = "flag_created"
	MessageTypeFlagUpdated  = "flag_updated"
	MessageTypeFlagDeleted  = "flag_deleted"
	MessageTypeBulkUpdate   = "bulk_update"
	MessageTypePing         = "ping"
	MessageTypePong         = "pong"
	MessageTypeError        = "error"
)

Server message types (server -> client)

View Source
const (
	ErrCodeInvalidMessage     = "invalid_message"
	ErrCodeUnknownMessageType = "unknown_message_type"
	ErrCodeMissingField       = "missing_field"
	ErrCodeForbidden          = "forbidden"
	ErrCodeInternal           = "internal_error"
	ErrCodeConnectionLimit    = "connection_limit"
	ErrCodeRateLimited        = "rate_limited"
	ErrCodeUnauthorized       = "unauthorized"
)

Error codes

View Source
const (
	ActionFlagCreated = "created"
	ActionFlagUpdated = "updated"
	ActionFlagDeleted = "deleted"
	ActionBulkUpdate  = "bulk_update"
)

Flag change actions

View Source
const (
	ReasonDefault        = "DEFAULT"
	ReasonTargetingMatch = "TARGETING_MATCH"
	ReasonSegmentMatch   = "SEGMENT_MATCH"
	ReasonRollout        = "ROLLOUT"
	ReasonDisabled       = "DISABLED"
	ReasonError          = "ERROR"
	ReasonStatic         = "STATIC"
)

Evaluation reasons

Variables

This section is empty.

Functions

This section is empty.

Types

type APIKeyValidator

type APIKeyValidator interface {
	// ValidateAPIKey validates an API key and returns the key ID and allowed environment IDs.
	// Returns an error if the key is invalid.
	ValidateAPIKey(ctx context.Context, apiKey string) (keyID string, allowedEnvs []string, err error)
}

APIKeyValidator validates API keys and returns the allowed environments.

type BroadcastMessage

type BroadcastMessage struct {
	// Target environment ID (empty for global broadcast)
	EnvironmentID string

	// The message to send
	Message *ServerMessage

	// Optional: only send to specific connection IDs
	TargetConnIDs []string
}

BroadcastMessage represents a message to broadcast to subscribers.

type ClientMessage

type ClientMessage struct {
	// Type of message (subscribe, unsubscribe, ping, pong)
	Type string `json:"type"`

	// EnvironmentID for subscribe/unsubscribe
	EnvironmentID string `json:"environmentId,omitempty"`
}

ClientMessage represents a message from the client.

type Condition

type Condition struct {
	// Attribute path (e.g., "user.plan", "context.region")
	Attribute string `json:"attribute"`

	// Operator (eq, neq, in, notIn, contains, startsWith, endsWith, gt, gte, lt, lte, regex, semver)
	Operator string `json:"operator"`

	// Single value for binary operators
	Value json.RawMessage `json:"value,omitempty"`

	// Multiple values for set operators (in, notIn)
	Values []json.RawMessage `json:"values,omitempty"`

	// Negate the condition
	Negate bool `json:"negate,omitempty"`
}

Condition represents a single condition in a targeting rule.

type Connection

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

Connection represents a WebSocket connection to the hub.

func NewConnection

func NewConnection(cfg ConnectionConfig) *Connection

NewConnection creates a new Connection.

func (*Connection) APIKeyID

func (c *Connection) APIKeyID() string

APIKeyID returns the API key ID used for authentication.

func (*Connection) CanAccessEnv

func (c *Connection) CanAccessEnv(envID string) bool

CanAccessEnv checks if the connection can access a given environment.

func (*Connection) Close

func (c *Connection) Close()

Close closes the connection.

func (*Connection) ConnectedAt

func (c *Connection) ConnectedAt() time.Time

ConnectedAt returns when the connection was established.

func (*Connection) ID

func (c *Connection) ID() string

ID returns the connection's unique ID.

func (*Connection) Ping

func (c *Connection) Ping()

Ping sends a ping to the client.

func (*Connection) Run

func (c *Connection) Run(ctx context.Context)

Run starts the read and write pumps for the connection. This should be called in a goroutine after the connection is registered.

func (*Connection) Send

func (c *Connection) Send(msg *ServerMessage)

Send queues a message to be sent to the client.

func (*Connection) SendError

func (c *Connection) SendError(code, message string)

SendError sends an error message to the client.

func (*Connection) Subscriptions

func (c *Connection) Subscriptions() []string

Subscriptions returns the current environment subscriptions.

type ConnectionConfig

type ConnectionConfig struct {
	ID          string
	WebSocket   *websocket.Conn
	APIKeyID    string
	AllowedEnvs []string
	RemoteAddr  string
	Hub         *Hub
	Logger      *zerolog.Logger
}

ConnectionConfig holds configuration for a new connection.

type EvaluationContext

type EvaluationContext struct {
	// Unique identifier for the target (user, device, etc.)
	TargetingKey string `json:"targetingKey"`

	// Custom attributes for targeting
	Attributes map[string]interface{} `json:"attributes,omitempty"`
}

EvaluationContext represents the context for flag evaluation.

type EvaluationResult

type EvaluationResult struct {
	// The flag key that was evaluated
	FlagKey string `json:"flagKey"`

	// The evaluated value
	Value json.RawMessage `json:"value"`

	// Variant key if applicable
	VariantKey string `json:"variantKey,omitempty"`

	// Reason for the evaluation result
	Reason string `json:"reason"`

	// Rule ID that matched (if any)
	RuleID string `json:"ruleId,omitempty"`

	// Segment key that matched (if any)
	SegmentKey string `json:"segmentKey,omitempty"`

	// Flag version at evaluation time
	Version int `json:"version"`
}

EvaluationResult represents the result of a flag evaluation.

type FlagChangeEvent

type FlagChangeEvent struct {
	// Action: created, updated, deleted, bulk_update
	Action string `json:"action"`

	// Environment ID
	EnvironmentID string `json:"environmentId"`

	// Flag key (for single flag operations)
	FlagKey string `json:"flagKey,omitempty"`

	// Flag configuration (for created/updated)
	Flag *FlagConfig `json:"flag,omitempty"`

	// Multiple flags (for bulk_update)
	Flags []FlagConfig `json:"flags,omitempty"`

	// Timestamp of the change
	Timestamp int64 `json:"timestamp"`

	// User who made the change
	ChangedBy string `json:"changedBy,omitempty"`
}

FlagChangeEvent represents a flag change event from Redis pub/sub.

type FlagConfig

type FlagConfig struct {
	// Unique key for the flag
	Key string `json:"key"`

	// Flag type: boolean, string, number, json
	Type string `json:"type"`

	// Whether the flag is enabled
	Enabled bool `json:"enabled"`

	// Default value when no rules match
	DefaultValue json.RawMessage `json:"defaultValue"`

	// Targeting rules
	Rules []TargetingRule `json:"rules,omitempty"`

	// Percentage rollout (0-100)
	RolloutPercentage int `json:"rolloutPercentage,omitempty"`

	// Version for optimistic concurrency
	Version int `json:"version"`

	// Variants for multivariate flags
	Variants []Variant `json:"variants,omitempty"`
}

FlagConfig represents a flag's configuration for SDK consumption.

type Handler

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

Handler handles WebSocket upgrade requests.

func NewHandler

func NewHandler(hub *Hub, validator APIKeyValidator, config HandlerConfig) *Handler

NewHandler creates a new WebSocket handler.

func (*Handler) ServeHTTP

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP handles WebSocket upgrade requests.

type HandlerConfig

type HandlerConfig struct {
	// AllowedOrigins for CORS. Empty allows all.
	AllowedOrigins []string

	// RequireAuth whether authentication is required.
	RequireAuth bool

	// Logger for the handler.
	Logger *zerolog.Logger
}

HandlerConfig configures the WebSocket handler.

type HealthHandler

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

HealthHandler returns the hub's health status.

func NewHealthHandler

func NewHealthHandler(hub *Hub) *HealthHandler

NewHealthHandler creates a new health handler.

func (*HealthHandler) ServeHTTP

func (h *HealthHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP returns the hub's health status.

type Hub

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

Hub manages WebSocket connections and broadcasts flag updates.

func NewHub

func NewHub(redisClient *redis.Client, config HubConfig) *Hub

NewHub creates a new WebSocket hub.

func (*Hub) Broadcast

func (h *Hub) Broadcast(msg *BroadcastMessage)

Broadcast sends a message to subscribers.

func (*Hub) Metrics

func (h *Hub) Metrics() *HubMetrics

Metrics returns the hub's metrics.

func (*Hub) Register

func (h *Hub) Register(conn *Connection)

Register adds a connection to the hub.

func (*Hub) Run

func (h *Hub) Run(ctx context.Context) error

Run starts the hub's main event loop. Blocks until ctx is cancelled.

func (*Hub) Stats

func (h *Hub) Stats() HubStats

Stats returns current hub statistics.

func (*Hub) Subscribe

func (h *Hub) Subscribe(conn *Connection, envID string) error

Subscribe adds a connection to an environment's subscription list.

func (*Hub) Unregister

func (h *Hub) Unregister(conn *Connection)

Unregister removes a connection from the hub.

func (*Hub) Unsubscribe

func (h *Hub) Unsubscribe(conn *Connection, envID string)

Unsubscribe removes a connection from an environment's subscription list.

type HubConfig

type HubConfig struct {
	// Redis channel pattern for flag changes (default: "hoist:flagchange:*")
	RedisChannelPattern string

	// How often to ping connections (default: 30s)
	PingInterval time.Duration

	// How long to wait for pong before considering connection dead (default: 10s)
	PongTimeout time.Duration

	// Maximum connections per API key (default: 100)
	MaxConnectionsPerKey int

	// Buffer size for broadcast channel (default: 256)
	BroadcastBufferSize int
}

HubConfig configures the WebSocket hub.

func DefaultHubConfig

func DefaultHubConfig() HubConfig

DefaultHubConfig returns a HubConfig with sensible defaults.

type HubMetrics

type HubMetrics struct {
	ConnectionsTotal   atomic.Int64 // Total connections ever made
	ConnectionsCurrent atomic.Int64 // Current active connections
	SubscriptionsTotal atomic.Int64 // Total subscriptions ever made
	MessagesReceived   atomic.Int64 // Messages received from Redis
	MessagesBroadcast  atomic.Int64 // Messages broadcast to clients
	Errors             atomic.Int64 // Total errors
}

HubMetrics tracks hub statistics.

type HubStats

type HubStats struct {
	TotalConnections  int
	EnvironmentCounts map[string]int
	MessagesReceived  int64
	MessagesBroadcast int64
}

HubStats contains current hub statistics.

type Publisher

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

Publisher publishes flag change events to Redis for distribution to WebSocket clients.

func NewPublisher

func NewPublisher(redisClient *redis.Client, config PublisherConfig) *Publisher

NewPublisher creates a new Publisher.

func (*Publisher) Channel

func (p *Publisher) Channel(envID string) string

Channel returns the Redis channel name for an environment.

func (*Publisher) PublishBulkUpdate

func (p *Publisher) PublishBulkUpdate(ctx context.Context, envID string, flags []FlagConfig, changedBy string) error

PublishBulkUpdate publishes a bulk update event.

func (*Publisher) PublishFlagCreated

func (p *Publisher) PublishFlagCreated(ctx context.Context, envID string, flag *FlagConfig, changedBy string) error

PublishFlagCreated publishes a flag created event.

func (*Publisher) PublishFlagDeleted

func (p *Publisher) PublishFlagDeleted(ctx context.Context, envID, flagKey, changedBy string) error

PublishFlagDeleted publishes a flag deleted event.

func (*Publisher) PublishFlagUpdated

func (p *Publisher) PublishFlagUpdated(ctx context.Context, envID string, flag *FlagConfig, changedBy string) error

PublishFlagUpdated publishes a flag updated event.

type PublisherConfig

type PublisherConfig struct {
	// ChannelPrefix for Redis channels (default: "hoist:flagchange:")
	ChannelPrefix string
}

PublisherConfig configures the publisher.

type ServeValue

type ServeValue struct {
	// Type: "variant" or "rollout"
	Type string `json:"type"`

	// Direct value (for variant type)
	Value json.RawMessage `json:"value,omitempty"`

	// Variant key (for variant type with named variants)
	VariantKey string `json:"variantKey,omitempty"`

	// Weighted variants (for rollout type)
	Distribution []WeightedVariant `json:"distribution,omitempty"`
}

ServeValue represents the value to serve when a rule matches.

type ServerMessage

type ServerMessage struct {
	// Type of message
	Type string `json:"type"`

	// ConnectionID (for connected message)
	ConnectionID string `json:"connectionId,omitempty"`

	// AllowedEnvironments (for connected message) - environments the API key has access to
	AllowedEnvironments []string `json:"allowedEnvironments,omitempty"`

	// EnvironmentID (for subscribed/flag events)
	EnvironmentID string `json:"environmentId,omitempty"`

	// Flag data (for flag_created/flag_updated)
	Flag *FlagConfig `json:"flag,omitempty"`

	// FlagKey (for flag_deleted)
	FlagKey string `json:"flagKey,omitempty"`

	// Flags (for bulk_update)
	Flags []FlagConfig `json:"flags,omitempty"`

	// Error fields
	Code    string `json:"code,omitempty"`
	Message string `json:"message,omitempty"`
}

ServerMessage represents a message from the server.

type TargetingRule

type TargetingRule struct {
	// Unique ID for the rule
	ID string `json:"id"`

	// Human-readable description
	Description string `json:"description,omitempty"`

	// Conditions that must match
	Conditions []Condition `json:"conditions,omitempty"`

	// Logic for combining conditions (and/or)
	ConditionLogic string `json:"conditionLogic,omitempty"`

	// Segment key to match instead of conditions
	SegmentKey string `json:"segmentKey,omitempty"`

	// Value to serve when rule matches
	Serve ServeValue `json:"serve"`

	// Percentage of matching users to apply rule to
	Rollout int `json:"rollout,omitempty"`

	// Priority (lower = higher priority)
	Priority int `json:"priority,omitempty"`
}

TargetingRule represents a targeting rule for flag evaluation.

type Variant

type Variant struct {
	// Unique key for the variant
	Key string `json:"key"`

	// Human-readable name
	Name string `json:"name,omitempty"`

	// The variant value
	Value json.RawMessage `json:"value"`

	// Description
	Description string `json:"description,omitempty"`
}

Variant represents a named variant for multivariate flags.

type WeightedVariant

type WeightedVariant struct {
	// Variant key
	VariantKey string `json:"variantKey"`

	// Weight (0-100, should sum to 100 across all variants in a distribution)
	Weight int `json:"weight"`
}

WeightedVariant represents a variant with a weight for percentage-based distribution.

Jump to

Keyboard shortcuts

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