Documentation
¶
Overview ¶
Package websocket provides a generic WebSocket connection registry (Hub) and client wrapper for real-time communication.
This is a foundation-layer package that uses string-based IDs for maximum flexibility. Application-specific semantics (e.g., "user:{uuid}", "role:{uuid}") are defined by higher layers.
Architecture:
Hub manages all WebSocket connections and provides broadcast methods. Client wraps individual WebSocket connections with read/write pumps. Message defines the envelope format for WebSocket messages.
Usage:
// Create hub
hub := websocket.NewHub(log)
go hub.Run(ctx)
// On connection, create client and register
client := websocket.NewClient(hub, conn, log)
hub.Register(ctx, client, []string{"user:uuid", "role:admin"})
// Broadcast to specific ID
hub.BroadcastToID("user:uuid", messageBytes)
// Broadcast to all
hub.BroadcastAll(messageBytes)
Index ¶
- type Client
- type HandlerRegistry
- type Hub
- func (h *Hub) BroadcastAll(message []byte) int
- func (h *Hub) BroadcastToID(id string, message []byte) int
- func (h *Hub) ClientsForID(id string) int
- func (h *Hub) CloseAll(ctx context.Context) error
- func (h *Hub) ConnectedIDs() []string
- func (h *Hub) ConnectionCount() int
- func (h *Hub) Register(ctx context.Context, client *Client, ids []string)
- func (h *Hub) Run(ctx context.Context) error
- func (h *Hub) Unregister(ctx context.Context, client *Client)
- func (h *Hub) UpdateClientIDs(ctx context.Context, client *Client, newIDs []string)
- func (h *Hub) UpdateClientIDsForID(ctx context.Context, id string, newIDs []string)
- type Message
- type MessageHandler
- type MessageType
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client represents a WebSocket connection. It is generic and has no business logic - application-specific semantics are added by higher layers (e.g., AlertHub).
func (*Client) Close ¶
Close signals the client to stop and closes the connection. Safe to call multiple times.
func (*Client) ReadPump ¶
ReadPump pumps messages from the WebSocket connection. Blocks until the connection is closed.
func (*Client) Send ¶
Send queues a message for sending to the client. Non-blocking; drops message if buffer is full.
func (*Client) WritePump ¶
WritePump pumps messages from the hub to the WebSocket connection. Owns the connection lifecycle - responsible for closing the underlying connection. Note: coder/websocket's Close() is safe to call multiple times and will return an error if already closed, which we ignore in the defer.
type HandlerRegistry ¶
type HandlerRegistry struct {
// contains filtered or unexported fields
}
HandlerRegistry manages WebSocket message handlers by type. It provides thread-safe registration and lookup of handlers.
func NewHandlerRegistry ¶
func NewHandlerRegistry() *HandlerRegistry
NewHandlerRegistry creates a new handler registry.
func (*HandlerRegistry) Get ¶
func (r *HandlerRegistry) Get(msgType string) (MessageHandler, bool)
Get retrieves a handler by message type. Returns the handler and true if found, nil and false otherwise.
func (*HandlerRegistry) Register ¶
func (r *HandlerRegistry) Register(h MessageHandler)
Register adds a handler to the registry. The handler's MessageType() is used as the key. If a handler for that type already exists, it is replaced.
func (*HandlerRegistry) Types ¶
func (r *HandlerRegistry) Types() []string
Types returns all registered message types.
type Hub ¶
type Hub struct {
// contains filtered or unexported fields
}
Hub manages WebSocket connections and message broadcasting. Uses string-based IDs for maximum flexibility - the calling application defines the semantics (e.g., "user:{uuid}", "role:{uuid}").
func (*Hub) BroadcastAll ¶
BroadcastAll sends a message to all connected clients.
func (*Hub) BroadcastToID ¶
BroadcastToID sends a message to all connections registered under the given ID. Uses context.Background() intentionally - broadcasts should not be cancelled by the caller's context since they're fire-and-forget operations. Individual client Send() calls handle their own timeouts via the write pump.
func (*Hub) ClientsForID ¶
ClientsForID returns the number of clients registered under the given ID.
func (*Hub) ConnectedIDs ¶
ConnectedIDs returns all unique IDs currently registered in the hub.
func (*Hub) ConnectionCount ¶
ConnectionCount returns the total number of active connections.
func (*Hub) Run ¶
Run starts the hub and blocks until context is cancelled. Periodically logs connection metrics for monitoring.
func (*Hub) Unregister ¶
Unregister removes a client from the hub.
func (*Hub) UpdateClientIDs ¶
UpdateClientIDs updates the IDs for a specific client.
func (*Hub) UpdateClientIDsForID ¶
UpdateClientIDsForID updates IDs for all clients registered under the given ID. Used for bulk updates (e.g., update all clients for a user when roles change). Note: This matches the exact ID, not a prefix pattern. For user role updates, pass the full user ID string (e.g., "user:uuid") to update all that user's connections.
type Message ¶
type Message struct {
Type MessageType `json:"type"`
Payload json.RawMessage `json:"payload"`
Timestamp time.Time `json:"timestamp"`
}
Message is the envelope format for WebSocket messages. All messages sent through the WebSocket are wrapped in this format.
type MessageHandler ¶
type MessageHandler interface {
// MessageType returns the type string this handler processes (e.g., "alert").
MessageType() string
// HandleMessage processes a single message for WebSocket delivery.
HandleMessage(ctx context.Context, msg *rabbitmq.Message) error
}
MessageHandler processes messages from the queue for real-time delivery via WebSocket. Implementations handle specific message types (alerts, inventory updates, etc.)
type MessageType ¶
type MessageType string
MessageType identifies the type of WebSocket message.
const ( // MessageTypeAlert is a new alert notification message. MessageTypeAlert MessageType = "alert" // MessageTypeAlertUpdated signals that an existing alert's status changed. MessageTypeAlertUpdated MessageType = "alert_updated" // MessageTypeApprovalResolved signals that an approval request was resolved (approved or rejected). MessageTypeApprovalResolved MessageType = "approval_resolved" // MessageTypeApprovalRequest signals that a new approval request was created and is pending. MessageTypeApprovalRequest MessageType = "approval_request" // MessageTypePing is a heartbeat ping message. MessageTypePing MessageType = "ping" // MessageTypePong is a heartbeat pong response message. MessageTypePong MessageType = "pong" )