WebSocket Channels
Named channels over WebSocket connections, with delivery to every subscriber across the cluster rather than only the ones this process happens to hold.
A connection belongs to one node. A chat room, a live dashboard or a notification feed does not, so publishing to the sockets in this process delivers to whichever fraction of the subscribers landed here and silently misses the rest. The channels ride on b.pubsub, so a publish reaches every node and each one writes to its own sockets.
Detaching a connection removes it from every channel it had joined, so a dropped socket leaves no subscription behind to deliver into.
b.websocketChannels.create(opts?) #
{
backend: string, // "local", "cluster" or "redis"; passed through to b.pubsub
cluster: object, // cluster handle passed through to b.pubsub
topicPrefix: string, // prefix for the pub/sub topics these channels use
pollIntervalMs: number, // passed through to b.pubsub
retentionMs: number, // passed through to b.pubsub
pruneEveryMs: number, // passed through to b.pubsub
redisUrl: string, // passed through to b.pubsub
redisUsername: string, // passed through to b.pubsub
redisPassword: string, // passed through to b.pubsub
redisTls: boolean, // passed through to b.pubsub
redisCa: string, // passed through to b.pubsub
redisServername: string, // passed through to b.pubsub
audit: boolean, // default false
}
Open the channel registry and answer the handle to work it. The handle carries attach(conn) and detach(conn) for a connection's lifetime, subscribe(conn, channel) and unsubscribe(conn, channel), publish(channel, payload), the read-only localSubscribers(channel), localSubscriberCount(channel), channels(), connectionChannels(conn) and attachedCount(), close(), and backend, the pub/sub backend name in use.
publish goes through pub/sub, so it reaches subscribers on every node and not only the ones attached here. The local calls answer this process's view and are for its own metrics rather than for deciding who receives a message.
detach drops the connection from every channel it joined, so a socket that goes away leaves nothing behind.
backend and the redis options are handed to b.pubsub.create, so the transport is the one pub/sub is configured for.
var b = require("@blamejs/core");
var channels = b.websocketChannels.create({ backend: "local" });
channels.attach(conn);
channels.subscribe(conn, "room:42");
await channels.publish("room:42", { text: "hello" });