Documentation
¶
Index ¶
- Constants
- Variables
- func Handler(hub *Hub, extractor ClaimsExtractor, opts *websocket.AcceptOptions) http.HandlerFunc
- type AuthHandler
- type Claims
- type ClaimsExtractor
- type Client
- type Event
- type EventHandler
- type Hub
- func (h *Hub) Broadcast(topicName string, event Event) error
- func (h *Hub) BroadcastRaw(topicName string, eventName string, payload any) error
- func (h *Hub) InvalidateState(topicName string)
- func (h *Hub) MatchTopic(topic string) (*topicRegistration, bool)
- func (h *Hub) RegisterStateTopic(pattern string, auth AuthHandler, hydrate HydrateHandler, leave LeaveHandler, ...)
- func (h *Hub) RegisterStreamTopic(pattern string, auth AuthHandler, leave LeaveHandler, event EventHandler)
- func (h *Hub) RouteMessage(c *Client, msg Message)
- func (h *Hub) SetState(topicName string, state any) error
- func (h *Hub) Shutdown()
- func (h *Hub) Stats() HubStats
- func (h *Hub) UnregisterClient(c *Client)
- type HubOptions
- type HubStats
- type HydrateHandler
- type LeaveHandler
- type Message
- type Router
- type TopicType
Constants ¶
const ( // MaxTeleportPayloadSize strictly bounds StateTopic payloads to ~100KB. MaxTeleportPayloadSize = 100 * 1024 // JoinTimeout is the maximum time an auth/hydration flow is allowed to take. JoinTimeout = 5 * time.Second )
Variables ¶
var ErrInvalidMessage = errors.New("invalid phoenix v2 message format")
ErrInvalidMessage is returned when the incoming JSON does not match the required Phoenix V2 5-element array format.
Functions ¶
func Handler ¶
func Handler(hub *Hub, extractor ClaimsExtractor, opts *websocket.AcceptOptions) http.HandlerFunc
Handler returns a standard HTTP handler that upgrades incoming connections to WebSockets and binds them to the provided Hub.
Types ¶
type AuthHandler ¶
AuthHandler is invoked for every client join attempt. It validates whether the specific client (claims) may join the topic.
type Claims ¶
type Claims any
Claims represents the authenticated identity of a user (e.g., from a JWT or session).
type ClaimsExtractor ¶
ClaimsExtractor is a callback that extracts user identity from an HTTP request before upgrading it to a WebSocket. The returned Claims are attached to the Client.
type Client ¶
type Client struct {
// ID is a unique identifier for this connection, used in structured logs.
ID string
// Claims holds the authenticated user identity (e.g., from JWT or session).
// This is set by the application layer after NewClient is called.
Claims Claims
// contains filtered or unexported fields
}
Client represents a single connected WebSocket user.
func (*Client) Close ¶
func (c *Client) Close()
Close safely tears down the connection and cancels the client context.
type Event ¶
type Event interface {
EventName() string
}
Event defines a typed event envelope for server-to-client broadcasts. By implementing this interface, complex applications avoid stringly-typed bugs.
type EventHandler ¶
type EventHandler func(ctx context.Context, topic string, event string, payload json.RawMessage, claims Claims)
EventHandler is invoked for custom client-to-server events on a topic. It receives the sender's claims, topic, event name, and raw payload.
type Hub ¶
type Hub struct {
// contains filtered or unexported fields
}
Hub is the central concurrent router for the WebChannel engine.
func (*Hub) BroadcastRaw ¶
BroadcastRaw sends an untyped payload to all connected clients on a specific topic. It implements the "Marshal Once" optimization for O(1) serialization performance.
func (*Hub) InvalidateState ¶
InvalidateState clears the RAM cache for a topic. The next client to join will trigger a fresh call to the topic's HydrateHandler.
func (*Hub) MatchTopic ¶
MatchTopic maps an exact topic (e.g., "room:lobby") to a registered pattern (e.g., "room:*").
func (*Hub) RegisterStateTopic ¶
func (h *Hub) RegisterStateTopic(pattern string, auth AuthHandler, hydrate HydrateHandler, leave LeaveHandler, event EventHandler)
RegisterStateTopic maps a state-topic pattern to auth/hydration/leave/event handlers.
func (*Hub) RegisterStreamTopic ¶
func (h *Hub) RegisterStreamTopic(pattern string, auth AuthHandler, leave LeaveHandler, event EventHandler)
RegisterStreamTopic maps a stream-topic pattern to auth/leave/event handlers.
func (*Hub) RouteMessage ¶
RouteMessage implements the Router interface. It intercepts join/leave events and routes custom events to the application.
func (*Hub) SetState ¶
SetState updates the RAM cache for a StateTopic. If the topic is not currently active (no subscribers), this is a memory-saving no-op, because the next client to join will automatically hydrate it fresh from the application.
func (*Hub) Shutdown ¶
func (h *Hub) Shutdown()
Shutdown gracefully cancels all client connections and waits for them to drain.
func (*Hub) Stats ¶
Stats aggregates current connections and topics across all shards. It acquires read locks briefly per shard, making it safe to call periodically.
func (*Hub) UnregisterClient ¶
UnregisterClient implements the Router interface. When a client drops, we must aggressively purge them from all shards.
type HubOptions ¶
type HubOptions struct {
SendBufferSize int
WriteTimeout time.Duration
ReadIdleTimeout time.Duration
MaxMessageSize int64
MaxTeleportPayloadSize int
StateTTL time.Duration // 0 means no expiration
}
func DefaultHubOptions ¶
func DefaultHubOptions() HubOptions
type HydrateHandler ¶
HydrateHandler is invoked at most once per topic cache generation. It builds shared state for all authorized subscribers and intentionally does not take claims.
type LeaveHandler ¶
LeaveHandler is invoked for cleanups (e.g., removing a user from a presence list).
type Message ¶
type Message struct {
// JoinRef is the unique ID for the topic subscription. It can be null.
JoinRef *string `json:"join_ref"`
// Ref is the unique ID for a specific message/request. It can be null.
Ref *string `json:"ref"`
// Topic is the channel name (e.g., "project:123" or "phoenix").
Topic string `json:"topic"`
// Event is the action name (e.g., "phx_join", "heartbeat", or custom).
Event string `json:"event"`
// Payload is the actual data. We use json.RawMessage to defer parsing.
// This prevents allocating memory for large payloads until we authorize the request.
Payload json.RawMessage `json:"payload"`
}
Message represents a single Phoenix V2 protocol message. Wire format: [join_ref, ref, topic, event, payload]
func (*Message) MarshalJSON ¶
MarshalJSON implements the json.Marshaler interface to convert the Message back into the 5-element array format for outbound broadcasting.
func (*Message) UnmarshalJSON ¶
UnmarshalJSON implements the json.Unmarshaler interface to handle the 5-element array format required by Phoenix Channels V2.