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
- type APIKeyValidator
- type BroadcastMessage
- type ClientMessage
- type Condition
- type Connection
- func (c *Connection) APIKeyID() string
- func (c *Connection) CanAccessEnv(envID string) bool
- func (c *Connection) Close()
- func (c *Connection) ConnectedAt() time.Time
- func (c *Connection) ID() string
- func (c *Connection) Ping()
- func (c *Connection) Run(ctx context.Context)
- func (c *Connection) Send(msg *ServerMessage)
- func (c *Connection) SendError(code, message string)
- func (c *Connection) Subscriptions() []string
- type ConnectionConfig
- type EvaluationContext
- type EvaluationResult
- type FlagChangeEvent
- type FlagConfig
- type Handler
- type HandlerConfig
- type HealthHandler
- type Hub
- func (h *Hub) Broadcast(msg *BroadcastMessage)
- func (h *Hub) Metrics() *HubMetrics
- func (h *Hub) Register(conn *Connection)
- func (h *Hub) Run(ctx context.Context) error
- func (h *Hub) Stats() HubStats
- func (h *Hub) Subscribe(conn *Connection, envID string) error
- func (h *Hub) Unregister(conn *Connection)
- func (h *Hub) Unsubscribe(conn *Connection, envID string)
- type HubConfig
- type HubMetrics
- type HubStats
- type Publisher
- func (p *Publisher) Channel(envID string) string
- func (p *Publisher) PublishBulkUpdate(ctx context.Context, envID string, flags []FlagConfig, changedBy string) error
- func (p *Publisher) PublishFlagCreated(ctx context.Context, envID string, flag *FlagConfig, changedBy string) error
- func (p *Publisher) PublishFlagDeleted(ctx context.Context, envID, flagKey, changedBy string) error
- func (p *Publisher) PublishFlagUpdated(ctx context.Context, envID string, flag *FlagConfig, changedBy string) error
- type PublisherConfig
- type ServeValue
- type ServerMessage
- type TargetingRule
- type Variant
- type WeightedVariant
Constants ¶
const ( ClientMessageTypeSubscribe = "subscribe" ClientMessageTypeUnsubscribe = "unsubscribe" ClientMessageTypePing = "ping" ClientMessageTypePong = "pong" )
Client message types (client -> server)
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)
const ( ErrCodeInvalidMessage = "invalid_message" ErrCodeUnknownMessageType = "unknown_message_type" ErrCodeMissingField = "missing_field" ErrCodeForbidden = "forbidden" ErrCodeInternal = "internal_error" ErrCodeConnectionLimit = "connection_limit" ErrCodeRateLimited = "rate_limited" )
Error codes
const ( ActionFlagCreated = "created" ActionFlagUpdated = "updated" ActionFlagDeleted = "deleted" ActionBulkUpdate = "bulk_update" )
Flag change actions
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) ConnectedAt ¶
func (c *Connection) ConnectedAt() time.Time
ConnectedAt returns when the connection was established.
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.
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 (*Hub) Broadcast ¶
func (h *Hub) Broadcast(msg *BroadcastMessage)
Broadcast sends a message to subscribers.
func (*Hub) Register ¶
func (h *Hub) Register(conn *Connection)
Register adds a connection to the hub.
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) 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 ¶
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.