Documentation
¶
Overview ¶
Package relay is the real-time room relay (SPEC.md "Real-time room relay (WebSocket)"): a generic per-room broadcast channel that fans one client's message out verbatim to every OTHER client in that room. No app-specific server logic lives here; clients hold the app logic and the relay is the live wire over the durable room KV.
Conn abstracts the socket so the hub logic (register, broadcast, drop-a-laggard, reap, teardown) is testable without real sockets.
Index ¶
- Constants
- Variables
- func MaxDurableFrameBytes(maxValueBytes int) int64
- type Conn
- type Frame
- type Hub
- type Limits
- type PeerPublisher
- type Peers
- type Registry
- type Relay
- func (rl *Relay) Admit(key RoomKey) (*Hub, uint64, error)
- func (rl *Relay) AnnounceDrain()
- func (rl *Relay) CommitAndMirror(key RoomKey, commit func() (Frame, error)) error
- func (rl *Relay) DeliverFromPeer(key RoomKey, f Frame)
- func (rl *Relay) Registry() *Registry
- func (rl *Relay) Release(key RoomKey, id uint64)
- func (rl *Relay) Serve(ctx context.Context, key RoomKey, id uint64, ws *websocket.Conn)
- func (rl *Relay) SetHeartbeat(interval, timeout time.Duration)
- func (rl *Relay) SetPeerPublisher(p PeerPublisher)
- type RoomKey
- type Snapshotter
Constants ¶
const ( // TypeSnapshot is the first frame a joining client receives: the full // current room state, so a late joiner is caught up before the live stream // begins. TypeSnapshot = "snapshot" // TypePut is the live mirror of a committed durable PUT. The client applies // it exactly as it applied that key in the snapshot (last-writer-wins per // key), so a stray re-delivery is idempotent. TypePut = "put" // TypeDelete is the live mirror of a committed durable DELETE. TypeDelete = "delete" // TypeReconnect is the drain hint (SPEC "Drain hint: // reconnect-before-shutdown"), broadcast to every local connection on the // termination signal and BEFORE the final close, so a client acting on it // re-homes while its old socket still works. It carries no seq, being no // room mutation, and is never load-bearing: a client that ignores it is // closed at shutdown and heals through reconnect + snapshot + splice. TypeReconnect = "reconnect" )
The only server-originated frames, which the client distinguishes by their "type" field. A relayed PEER frame is never stamped: those stay payload-opaque and fan out verbatim.
const ( DefaultMaxConnsPerRoom = 64 DefaultMaxConnsPerApp = 1024 DefaultMaxRooms = 4096 DefaultMaxMessageBytes = 32 << 10 // 32 KiB DefaultSendBuffer = 16 DefaultMaxMsgsPerSec = 120 )
SPEC defaults (SPEC.md "Limits and abuse posture").
const ( PingInterval = 20 * time.Second PingTimeout = 10 * time.Second )
Heartbeat timing: the server pings each connection on PingInterval and reaps it if the pong misses PingTimeout. PingInterval must stay UNDER the proxy idle defaults (traefik / nginx 60-120 s) so the heartbeat also keeps a legitimately-quiet connection alive through the proxy.
Variables ¶
var ( // ErrRoomFull: the per-room connection cap is hit. HTTP 429. ErrRoomFull = errors.New("relay: room connection cap reached") // ErrAppFull: the per-app aggregate connection cap is hit. HTTP 429. ErrAppFull = errors.New("relay: app connection cap reached") // ErrTooManyRooms: the live-room cap is hit and this upgrade would create // a NEW hub. HTTP 503; joins to already-live rooms still succeed. ErrTooManyRooms = errors.New("relay: too many active relay rooms") )
Admission errors the upgrade handler maps to HTTP status codes. Relay-layer sentinels, so the HTTP handler never reaches into the registry's internals.
Functions ¶
func MaxDurableFrameBytes ¶ added in v0.65.0
MaxDurableFrameBytes bounds the largest frame EncodePut can produce for a value of at most maxValueBytes, and is what the peer receiver's cap must admit. RoomWireValue encodes a non-JSON value as a JSON string, and worst-case escaping (\u00XX per control byte) inflates it up to 6x, plus quotes and the envelope.
The client-socket cap (Limits.MaxMessageBytes) deliberately does NOT apply: it bounds ephemeral frames from untrusted client sockets, while durable mirrors come from the HTTP PUT path, whose value cap is several times larger.
Types ¶
type Conn ¶
Conn is the per-client connection the Hub broadcasts to. Implementations must honour:
- Send enqueues on a bounded buffer and NEVER blocks the broadcast path. False means the buffer is full, and the hub drops that laggard rather than head-of-line-blocking the whole room.
- Close is idempotent and safe to call from the hub while the connection's own writer is draining.
- ID is unique per connection, not per client: two tabs are two members.
type Frame ¶
type Frame struct {
// Binary is carried through uninterpreted so the receiving socket
// re-emits the message type the sender used.
Binary bool
// Data is the app's payload, fanned out verbatim.
Data []byte
}
Frame is one relay message: opaque bytes plus the WebSocket message type, so a frame round-trips with the flavor the sender chose. The server never parses or stamps Data. Server-originated control envelopes (the late-join snapshot, the live mirror of a durable PUT) are JSON text frames the client distinguishes by their own structure.
func EncodeDelete ¶
EncodeDelete builds the live-mirror frame for a committed durable DELETE of key whose commit assigned the per-room sequence seq.
func EncodePut ¶
EncodePut builds the live-mirror frame for a durable PUT of (key, val) whose commit assigned the per-room sequence seq. The commit closure passed to Relay.CommitAndMirror builds the frame only AFTER the durable write returns that seq, so it carries the exact position the write landed at in the room's order.
type Hub ¶
type Hub struct {
// contains filtered or unexported fields
}
Hub is the in-memory registry for ONE room's live connections. The Registry creates a hub lazily on the first connection to a room and tears it down when the last connection leaves, so no idle empty hub lingers.
Every method takes the hub's mutex, so concurrent register / broadcast / unregister is serialized. The broadcast is still wait-free per client: it calls Conn.Send, which enqueues on a bounded buffer and returns immediately, so one laggard cannot stall the fan-out to the rest of the room while the lock is held.
type Limits ¶
type Limits struct {
// MaxConnsPerRoom bounds one hub's client set and one room's fan-out cost
// (a broadcast is O(connections)). Past it, a new upgrade to that room is
// refused 429.
MaxConnsPerRoom int
// MaxConnsPerApp bounds the live connections one app's rooms hold open in
// aggregate. Past it, a new upgrade under that app is refused 429.
MaxConnsPerApp int
// MaxRooms bounds the count of distinct live rooms. Past it, an upgrade
// that would create a NEW hub is refused 503; joins to already-live rooms
// still succeed.
MaxRooms int
// MaxMessageBytes bounds a single inbound frame; over it the connection
// closes (StatusMessageTooBig). Distinct from the per-room DURABLE byte
// cap: a relay frame is never persisted, so this bounds memory, not
// storage.
MaxMessageBytes int64
// SendBuffer is the bounded per-client send-buffer depth in frames. A
// client whose buffer is full when a broadcast tries to enqueue is dropped:
// that is the backpressure mechanism. A small handful is correct, since a
// client that cannot keep up with a few buffered frames is better off
// reconnecting than holding a live slot.
SendBuffer int
// MaxMsgsPerSec is the per-connection inbound rate ceiling; a client past
// it is dropped. Without it one hostile connection saturates a room's
// fan-out, since every inbound frame is multiplied by the room's connection
// count on the way out.
MaxMsgsPerSec int
}
Limits is the relay's abuse posture (SPEC.md "Limits and abuse posture"). Every in-memory structure is bounded; the room-UUID capability plus these caps are the whole posture, with no additional auth. A zero field means "unlimited" on that axis (used by tests isolating one limit); NewLimits sets the SPEC defaults.
type PeerPublisher ¶ added in v0.65.0
PeerPublisher publishes a frame to every OTHER pod of the deployment, which delivers it to its own local subscribers of the same room (via Relay.DeliverFromPeer). The relay is the ONLY caller; implementations own transport, discovery, and queueing.
The contract (SPEC "Delivery semantics"):
- Publish MUST NOT block and MUST NOT fail the caller: delivery is best-effort per peer, isolated per peer, and never on the commit path. A production implementation enqueues on a bounded per-peer queue and drops when it is full. A dropped durable frame is detectable at every affected subscriber via the dense seq (the client re-snapshots); a dropped ephemeral frame is harmless by definition.
- The recipient list is the implementation's concern, so interest-based fan-out can replace "all peers" later with no contract change.
- Publish carries BOTH flavors, durable mirror and ephemeral client frame. The frame is opaque to the transport: a durable mirror's seq rides inside f.Data, an ephemeral frame has none.
type Peers ¶ added in v0.65.0
type Peers interface {
Addresses() []string
}
Peers is the peer-discovery port: the CURRENT peer pods' gRPC addresses, self excluded (SPEC "Peer discovery: the ring membership the cluster already gossips"). Addresses is called per publish, so the peer set follows membership with no subscription machinery; implementations must be safe for concurrent use.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry maps a RoomKey to its live Hub and owns the per-app aggregate connection cap and the service-wide live-room cap. It is the only in-memory structure the upgrade handler touches directly, and everything it holds is bounded.
Concurrency: r.mu guards the hub map and the per-app counters. Admission's map-only accounting runs under it so the caps are checked atomically against the lazy create, and an empty hub is removed under it so the room count stays exact.
func NewRegistry ¶
NewRegistry builds an empty registry with the given limits.
func (*Registry) CloseAll ¶
func (r *Registry) CloseAll()
CloseAll closes every connection in every hub at shutdown. It sets the closing flag so no new admit succeeds, then closes each hub's connections with a normal-closure status so clients reconnect on their backoff schedule rather than hammering instantly.
type Relay ¶
type Relay struct {
// contains filtered or unexported fields
}
Relay is the real-time room relay service: it owns the Registry, reads the late-join snapshot via the Snapshotter, and runs each connection's reader / writer / heartbeat lifecycle. The HTTP upgrade handler authenticates the room and hands the accepted websocket to Serve.
func NewRelay ¶
func NewRelay(snap Snapshotter, limits Limits) *Relay
NewRelay builds a relay over snap with the given limits.
func (*Relay) Admit ¶
Admit reserves a connection slot for the room under the per-room / per-app / total-rooms caps and returns the hub + a fresh connection id, or an admission error (ErrRoomFull / ErrAppFull / ErrTooManyRooms) the HTTP layer maps to a status. Must be called BEFORE completing the websocket handshake, so an over-limit upgrade is refused with a normal HTTP status and no socket is ever accepted for it.
func (*Relay) AnnounceDrain ¶ added in v0.65.0
func (rl *Relay) AnnounceDrain()
AnnounceDrain broadcasts the {"type":"reconnect"} drain hint once to every live connection (SPEC "Drain hint: reconnect-before-shutdown"). Must be called on the termination signal BEFORE the HTTP server stops accepting and before CloseAll, with serving continuing through the drain grace window, so a client acting on the hint can reconnect onto a surviving pod while its old socket still works. The hint is an optimization, never load-bearing: clients that ignore it heal through the normal reconnect + snapshot + splice path.
func (*Relay) CommitAndMirror ¶
CommitAndMirror runs a durable write's KV commit, broadcasts its LOCAL live mirror, then publishes the mirror to the peer pods (best-effort, never on the commit path). A failed commit mirrors nothing, publishes nothing, and returns the error.
commit returns the mirror frame to fan out, built AFTER the write because it carries the per-room sequence the commit assigned: the seq is durable room state only the commit knows. NOTHING here runs under the room's hub lock - the commit is a storage round trip, and holding the hub lock across storage I/O would let a slow commit stall the room's fan-out and joins. The mirror broadcasts server-originated (from == 0), so every local connection receives it.
Correctness, locally AND across pods, rides the sequence: subscribers order by seq, de-duplicate by the discard rule (seq <= their snapshot's S), and detect loss by the hole a dense seq leaves (SPEC "Multi-pod relay"). The local broadcast is the zero-hop case of the same contract.
func (*Relay) DeliverFromPeer ¶ added in v0.65.0
DeliverFromPeer is the receive path of the peer transport: the transport adapter calls it for every frame published by a peer pod. The frame is broadcast to THIS pod's local subscribers as server-originated (from == 0, so every local connection receives it; the originating socket lives on the origin pod, which already excluded it from its own fan-out). No local hub means no local subscribers and the frame is dropped, which is correct because the live path never carries correctness (the durable KV + the dense seq do). A received frame is delivered locally ONLY, never re-published, so the origin pod is the single fan-out point (full mesh, TTL 1) and no routing loop can exist by construction.
func (*Relay) Registry ¶
Registry exposes the registry so the HTTP layer can mirror a durable PUT to a live hub and shutdown can close every connection.
func (*Relay) Release ¶
Release frees a slot reserved by Admit that was never handed to Serve: the websocket Accept failed AFTER admission, so Serve's deferred teardown never ran. Without it a failed Accept leaks a connection count and an empty hub.
func (*Relay) Serve ¶
Serve runs a single accepted connection's full lifecycle: the late-join snapshot, the live stream, and the heartbeat, tearing everything down on any exit. The caller has already Admitted the connection and accepted the websocket. Serve blocks until the connection ends, so the handler's request goroutine owns the connection for its lifetime - correct, since the websocket was hijacked out from under the http.Server's timeouts.
Late-join is gap-free and dup-free only under the register-FIRST sequence (SPEC "Persistence and late-join"):
- Register the connection into the hub FIRST, so every mirror frame broadcast from that instant on is queued for it (the frames wait in the send buffer behind the reserved first-frame slot).
- Read the room KV snapshot OUTSIDE the hub lock and write it as the FIRST frame on the wire, stamped with the exact seq S it reflects.
- Start the writer (draining any buffered live frames), reader, and heartbeat; live frames flow.
A frame broadcast BEFORE the register came from a commit that completed before the snapshot read started, so its effect is in the snapshot (seq <= S): no gap. A frame delivered after the register whose effect the snapshot also caught is discarded by the client's seq <= S rule: no dup. Correctness rides the sequence, so it holds identically for frames arriving from peer pods.
func (*Relay) SetHeartbeat ¶
SetHeartbeat overrides the ping interval + timeout so tests can drive the reap path quickly.
func (*Relay) SetPeerPublisher ¶ added in v0.65.0
func (rl *Relay) SetPeerPublisher(p PeerPublisher)
SetPeerPublisher wires the outbound peer port. Called once at the composition root, before the HTTP server accepts connections; nil (the default) is the zero-peer deploy. A setter rather than a constructor argument because the relay and the transport are constructed in an order the composition root owns.
type RoomKey ¶
RoomKey identifies one relay hub. Including the app slug makes cross-app isolation structural: the same room UUID under a different app resolves to a different hub, with no filter a handler could forget. Mirrors the (app-slug, room-uuid, key) shape the durable KV tier namespaces by.
type Snapshotter ¶
Snapshotter is the relay's ONLY dependency on the durable tier: it reads the current room KV so a joining client is caught up before it joins the live stream. internal/service.Rooms satisfies it via Scan.
The relay never writes durable state. Every durable mutation is the app's HTTP KV PUT/DELETE, which the server mirrors to the room's hub, so the relay inherits the durable tier's caps and never opens a second persistence path.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package relaygrpc is the relay's peer-transport adapter (docs/SPEC.md "Multi-pod relay: the peer transport"): the Receiver, a gRPC service every pod registers on the cluster-internal server shale forwarding already runs, and the Publisher, which fans a frame out to every peer over bounded per-peer queues.
|
Package relaygrpc is the relay's peer-transport adapter (docs/SPEC.md "Multi-pod relay: the peer transport"): the Receiver, a gRPC service every pod registers on the cluster-internal server shale forwarding already runs, and the Publisher, which fans a frame out to every peer over bounded per-peer queues. |