websocket

package
v0.0.0-...-d105bfc Latest Latest
Warning

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

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

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

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 NewClient

func NewClient(hub *Hub, conn *websocket.Conn, log *logger.Logger) *Client

NewClient creates a new Client.

func (*Client) Close

func (c *Client) Close() error

Close signals the client to stop and closes the connection. Safe to call multiple times.

func (*Client) IDs

func (c *Client) IDs() []string

IDs returns a copy of the client's registered IDs. Thread-safe.

func (*Client) ReadPump

func (c *Client) ReadPump(ctx context.Context)

ReadPump pumps messages from the WebSocket connection. Blocks until the connection is closed.

func (*Client) Send

func (c *Client) Send(ctx context.Context, message []byte)

Send queues a message for sending to the client. Non-blocking; drops message if buffer is full.

func (*Client) SetIDs

func (c *Client) SetIDs(ids []string)

SetIDs updates the client's registered IDs. Thread-safe.

func (*Client) WritePump

func (c *Client) WritePump(ctx context.Context)

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 NewHub

func NewHub(log *logger.Logger) *Hub

NewHub creates a new Hub instance.

func (*Hub) BroadcastAll

func (h *Hub) BroadcastAll(message []byte) int

BroadcastAll sends a message to all connected clients.

func (*Hub) BroadcastToID

func (h *Hub) BroadcastToID(id string, message []byte) int

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

func (h *Hub) ClientsForID(id string) int

ClientsForID returns the number of clients registered under the given ID.

func (*Hub) CloseAll

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

CloseAll closes all connected clients. Used for graceful shutdown.

func (*Hub) ConnectedIDs

func (h *Hub) ConnectedIDs() []string

ConnectedIDs returns all unique IDs currently registered in the hub.

func (*Hub) ConnectionCount

func (h *Hub) ConnectionCount() int

ConnectionCount returns the total number of active connections.

func (*Hub) Register

func (h *Hub) Register(ctx context.Context, client *Client, ids []string)

Register adds a client to the hub under the given IDs.

func (*Hub) Run

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

Run starts the hub and blocks until context is cancelled. Periodically logs connection metrics for monitoring.

func (*Hub) Unregister

func (h *Hub) Unregister(ctx context.Context, client *Client)

Unregister removes a client from the hub.

func (*Hub) UpdateClientIDs

func (h *Hub) UpdateClientIDs(ctx context.Context, client *Client, newIDs []string)

UpdateClientIDs updates the IDs for a specific client.

func (*Hub) UpdateClientIDsForID

func (h *Hub) UpdateClientIDsForID(ctx context.Context, id string, newIDs []string)

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"
)

Jump to

Keyboard shortcuts

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