webchannel

package module
v0.0.0-...-9158755 Latest Latest
Warning

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

Go to latest
Published: Aug 22, 2026 License: MIT Imports: 13 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

WebChannel

A high-performance WebSocket engine for Go, wire-compatible with Phoenix Channels V2. WebChannel is built for two patterns: state synchronization (clients receive the full current state on every join or reconnect) and push-only event streaming (server-to-client fan-out with no state). It uses the battle-tested phoenix.js client on the frontend — no custom client library required.

Design Philosophy

Most real-time frameworks try to recover missed messages during network blips. WebChannel doesn't. Instead:

  • Full state on connect. When a client joins a topic, the server sends the entire current state as JSON. On reconnect, same thing. No deltas, no catchup, no message ordering bugs.
  • Drop slow clients. If a client's outbound buffer fills up, the server drops the connection immediately. This protects server memory and keeps latency predictable for everyone else. The client reconnects and gets fresh state.
  • Authorize every join. Auth runs on every join attempt, even if the state is already cached. Cached state is shared across subscribers — authorization is not.

Install

go get github.com/greyhoundhq/webchannel

Quick Start

package main
import (
	"context"
	"log"
	"net/http"
	"github.com/greyhoundhq/webchannel"
)
func main() {
	hub := webchannel.NewHub(webchannel.DefaultHubOptions())
	// Register a state topic — clients get full state on join.
		hub.RegisterStateTopic(
			"user:*",
			func(ctx context.Context, topic string, claims webchannel.Claims) error {
				return nil // authorize the join
			},
			func(ctx context.Context, topic string) (any, error) {
				return map[string]string{"name": "Alice", "status": "online"}, nil // build shared state
			},
			nil, // optional leave handler
			nil, // optional custom event handler
		)
	// HTTP handler upgrades connections and binds them to the hub.
	http.Handle("/socket", webchannel.Handler(hub, func(r *http.Request) webchannel.Claims {
		return r.Header.Get("X-User-ID")
	}, nil))
	// Broadcast to subscribers from anywhere in your application.
	go func() {
		_ = hub.BroadcastRaw("user:123", "status_changed", map[string]string{
			"status": "away",
		})
	}()
	log.Fatal(http.ListenAndServe(":8080", nil))
}

On the frontend, connect with the standard Phoenix client:

import { Socket } from "phoenix";
const socket = new Socket("/socket");
socket.connect();
const channel = socket.channel("user:123", {});
channel.join()
  .receive("ok", (state) => console.log("Current state:", state));
channel.on("status_changed", (payload) => {
  console.log("Status update:", payload);
});

Topic Types

State Topics

State topics deliver the full current state to every client on join. The state is built by a HydrateHandler and cached in RAM — concurrent joins hit the cache, not your database.

hub.RegisterStateTopic("project:*", authFn, hydrateFn, leaveFn, eventFn)
  • Payloads are capped at 100 KB (configurable) to keep joins fast.
  • Cache is protected against thundering herds: if 50 clients reconnect simultaneously, the hydrate function runs exactly once.
  • Use hub.SetState(topic, newState) to push cache updates proactively.
  • Use hub.InvalidateState(topic) to force re-hydration on the next join.
Stream Topics

Stream topics are push-only channels with no initial state. Use them for logs, notifications, or any append-only event feed.

hub.RegisterStreamTopic("project:*:logs", authFn, leaveFn, eventFn)

No payload size limit on individual broadcast messages.

Broadcasting

// Untyped broadcast.
hub.BroadcastRaw("project:123", "build_progress", map[string]any{"pct": 75})
// Typed broadcast — implement the Event interface.
type BuildFinished struct {
	Artifact string `json:"artifact"`
}
func (b BuildFinished) EventName() string { return "build_finished" }
hub.Broadcast("project:123", BuildFinished{Artifact: "v1.2.0.tar.gz"})

Messages are marshaled once and the resulting bytes are shared across all subscribers — O(1) serialization regardless of subscriber count.

Configuration

opts := webchannel.HubOptions{
	SendBufferSize:         64,            // outbound queue per client
	WriteTimeout:           10 * time.Second,
	ReadIdleTimeout:        60 * time.Second,
	MaxMessageSize:         4 * 1024 * 1024, // 4 MB inbound limit
	MaxTeleportPayloadSize: 100 * 1024,      // 100 KB state payload limit
	StateTTL:               30 * time.Second, // 0 = no expiry
}
hub := webchannel.NewHub(opts)

Observability

stats := hub.Stats()
fmt.Printf("topics=%d clients=%d\n", stats.ActiveTopics, stats.ActiveClients)

Internals

  • 32-shard concurrent hub. Topics are partitioned across 32 independent shards using FNV-1a hashing, minimizing lock contention under high connection counts.
  • Data locality. Topics are hashed by their first two segments (project:123), so project:123 and project:123:logs always land on the same shard. No cross-shard coordination required.
  • Marshal-once fan-out. Outbound messages are serialized exactly once and the same byte slice is sent to every subscriber.
  • Phoenix V2 wire format. Messages use the standard 5-element JSON array: [join_ref, ref, topic, event, payload].

Lifecycle

Client connects
    │
    ▼
websocket.Accept → NewClient → read/write pumps start
    │
    ▼
Client sends phx_join
    │
    ├─ topic registered? ─── no ──→ error reply
    │
    ├─ auth handler ──────── fail ─→ error reply
    │
    ├─ state topic? ─── yes ──→ hydrate (or serve from cache)
    │                            │
    │                            ▼
    │                       state > 100KB? ─→ error reply
    │
    ▼
Subscribe to shard + reply with state (or {} for streams)
    │
    ▼
Client receives broadcasts until disconnect or drop

License

MIT — see LICENSE.

Documentation

Index

Constants

View Source
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

View Source
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

type AuthHandler func(ctx context.Context, topic string, claims Claims) error

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

type ClaimsExtractor func(r *http.Request) Claims

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 NewClient

func NewClient(ctx context.Context, conn *websocket.Conn, router Router, opts HubOptions) *Client

NewClient creates a new Client and starts its read and write pumps.

func (*Client) Close

func (c *Client) Close()

Close safely tears down the connection and cancels the client context.

func (*Client) Send

func (c *Client) Send(message []byte)

Send places a pre-marshaled JSON message into the client's outbound queue. DROP POLICY: If the buffer is full, the client is dropped instantly. NOTE: Messages remaining in the queue when a client drops are intentionally discarded; reconnect performs a fresh Teleport sync.

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 NewHub

func NewHub(opts HubOptions) *Hub

NewHub initializes a new sharded Hub.

func (*Hub) Broadcast

func (h *Hub) Broadcast(topicName string, event Event) error

Broadcast sends a typed Event to all connected clients on a specific topic.

func (*Hub) BroadcastRaw

func (h *Hub) BroadcastRaw(topicName string, eventName string, payload any) error

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

func (h *Hub) InvalidateState(topicName string)

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

func (h *Hub) MatchTopic(topic string) (*topicRegistration, bool)

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

func (h *Hub) RouteMessage(c *Client, msg Message)

RouteMessage implements the Router interface. It intercepts join/leave events and routes custom events to the application.

func (*Hub) SetState

func (h *Hub) SetState(topicName string, state any) error

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

func (h *Hub) Stats() HubStats

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

func (h *Hub) UnregisterClient(c *Client)

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 HubStats

type HubStats struct {
	ActiveTopics  int
	ActiveClients int
}

type HydrateHandler

type HydrateHandler func(ctx context.Context, topic string) (initialState any, err error)

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

type LeaveHandler func(topic string, claims Claims)

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

func (m *Message) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface to convert the Message back into the 5-element array format for outbound broadcasting.

func (*Message) UnmarshalJSON

func (m *Message) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface to handle the 5-element array format required by Phoenix Channels V2.

type Router

type Router interface {
	RouteMessage(c *Client, msg Message)
	UnregisterClient(c *Client)
}

Router defines the interface for passing messages from a Client up to the Hub.

type TopicType

type TopicType int

TopicType explicitly differentiates between Teleport state and Push-only streams.

const (
	StateTopic TopicType = iota
	StreamTopic
)

Jump to

Keyboard shortcuts

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