Skip to main content
zerotal

Documentation


Documentation / @zerotal/broadcasting / RedisBroadcastDriver

Class: RedisBroadcastDriver

Defined in: broadcasting/src/RedisBroadcastDriver.ts:52

Redis-backed broadcast driver for horizontal scaling.

Extends BroadcastManager and overrides to() to publish through Redis Pub/Sub instead of writing directly to local WebSocket connections. Every server instance subscribes on __zerotal:broadcast and delivers incoming messages to its own local WS clients.

Result: a broadcast on Server A is received by subscribers on Server B, Server C, etc. — no direct server-to-server connection needed.

Architecture:

Server A Redis Server B ───────────────── ────────────── ───────────────── Broadcast.to(ch, ev) → pub.publish(TOPIC) ──► fan-out ───────────────► sub.subscribe cb ◄─────────────────────────── super.to() → ws

The publishing server also receives its own message via the subscriber, so all delivery — local or remote — flows through the same path.

Example

// config/broadcasting.ts
export default BroadcastConfig({
  driver: 'redis',
  redis:  { url: Bun.env.REDIS_URL ?? 'redis://localhost:6379' },
});

Extends

Constructors

Constructor

new RedisBroadcastDriver(_url): RedisBroadcastDriver

Defined in: broadcasting/src/RedisBroadcastDriver.ts:56

Parameters

_url

string

Returns

RedisBroadcastDriver

Overrides

BroadcastManager.constructor

Properties

_conns

protected _conns: Map<string, WS>

Defined in: broadcasting/src/BroadcastManager.ts:32

connectionId → live WebSocket

Inherited from

BroadcastManager._conns


_subs

protected _subs: Map<string, Set<string>>

Defined in: broadcasting/src/BroadcastManager.ts:34

channelName → Set

Inherited from

BroadcastManager._subs


_members

protected _members: Map<string, Map<string, PresenceMember>>

Defined in: broadcasting/src/BroadcastManager.ts:36

presence channelName → Map<connectionId, PresenceMember>

Inherited from

BroadcastManager._members


_authSecret

protected _authSecret: string | undefined = undefined

Defined in: broadcasting/src/BroadcastManager.ts:42

Secret for per-subscription HMAC signatures (the app's APP_KEY).

Inherited from

BroadcastManager._authSecret

Accessors

wsHandlers

Get Signature

get wsHandlers(): object

Defined in: broadcasting/src/BroadcastManager.ts:246

Returns

object

open

open: (ws) => void

Parameters
ws

WS

Returns

void

message

message: (ws, msg) => undefined

Parameters
ws

WS

msg

string | Uint8Array<ArrayBufferLike>

Returns

undefined

close

close: (ws) => void

Parameters
ws

WS

Returns

void

Inherited from

BroadcastManager.wsHandlers

Methods

setAuthSecret()

setAuthSecret(secret): void

Defined in: broadcasting/src/BroadcastManager.ts:51

Set the secret used to sign/verify per-subscription auth tokens. Wired from the app's APP_KEY by BroadcastProvider. Without it the signed-auth path is disabled and the server falls back to the connection-level authorize callbacks.

Parameters

secret

string

Returns

void

Inherited from

BroadcastManager.setAuthSecret


signAuth()

signAuth(socketId, channel, channelData?): string

Defined in: broadcasting/src/BroadcastManager.ts:59

Sign a socket_id / channel pair (and, for presence, its channelData) — the token POST /broadcasting/auth hands back to the client, which echoes it in subscribe.

Parameters

socketId

string

channel

string

channelData?

string

Returns

string

Inherited from

BroadcastManager.signAuth


verifyAuth()

verifyAuth(socketId, channel, auth, channelData?): boolean

Defined in: broadcasting/src/BroadcastManager.ts:74

Constant-time check that auth is a valid signature for this socket/channel(/data).

Parameters

socketId

string

channel

string

auth

string

channelData?

string

Returns

boolean

Inherited from

BroadcastManager.verifyAuth


authorizeWith()

authorizeWith(fn): void

Defined in: broadcasting/src/BroadcastManager.ts:95

Register an authorization callback for private/presence channels. Return true to allow subscription, false to deny.

Parameters

fn

ChannelAuthFn

Returns

void

Example

broadcast.authorizeWith(async (channel, ws) => {
  if (!ws.data.userId) return false;
  if (channel.startsWith('private-orders.')) {
    const id = channel.split('.')[1];
    return await Order.findOwner(id) === ws.data.userId;
  }
  return true;
});

Inherited from

BroadcastManager.authorizeWith


authorizePresenceWith()

authorizePresenceWith(fn): void

Defined in: broadcasting/src/BroadcastManager.ts:111

Register a presence channel auth callback. Return a PresenceMember object to grant access and track the member, or false to deny.

Parameters

fn

PresenceAuthFn

Returns

void

Example

manager.authorizePresenceWith(async (channel, ws) => {
  const user = await User.find(ws.data.userId);
  if (!user) return false;
  return { id: user.id, info: { name: user.name, avatar: user.avatar } };
});

Inherited from

BroadcastManager.authorizePresenceWith


getMembers()

getMembers(channel): PresenceMember[]

Defined in: broadcasting/src/BroadcastManager.ts:122

Return all members currently subscribed to a presence channel.

Parameters

channel

string

Returns

PresenceMember[]

Example

const members = manager.getMembers('presence-chat.room');
// [{ id: 1, info: { name: 'Alice' } }, ...]

Inherited from

BroadcastManager.getMembers


handleOpen()

handleOpen(ws): void

Defined in: broadcasting/src/BroadcastManager.ts:128

Parameters

ws

WS

Returns

void

Inherited from

BroadcastManager.handleOpen


handleMessage()

handleMessage(ws, raw): Promise<void>

Defined in: broadcasting/src/BroadcastManager.ts:133

Parameters

ws

WS

raw

string | Uint8Array<ArrayBufferLike>

Returns

Promise<void>

Inherited from

BroadcastManager.handleMessage


handleClose()

handleClose(ws): void

Defined in: broadcasting/src/BroadcastManager.ts:166

Parameters

ws

WS

Returns

void

Inherited from

BroadcastManager.handleClose


send()

send(event, opts?): void

Defined in: broadcasting/src/BroadcastManager.ts:214

Dispatch a BroadcastEvent to all its declared channels.

Parameters

event

BroadcastEvent

opts?
exceptSocketId?

string

Returns

void

Example

broadcast.send(new PostUpdated(post));

Inherited from

BroadcastManager.send


subscriptionsFor()

subscriptionsFor(connectionId): string[]

Defined in: broadcasting/src/BroadcastManager.ts:226

Returns the list of channels a connection is subscribed to.

Parameters

connectionId

string

Returns

string[]

Inherited from

BroadcastManager.subscriptionsFor


subscriberCount()

subscriberCount(channel): number

Defined in: broadcasting/src/BroadcastManager.ts:235

Returns the number of subscribers on a channel.

Parameters

channel

string

Returns

number

Inherited from

BroadcastManager.subscriberCount


connectionCount()

connectionCount(): number

Defined in: broadcasting/src/BroadcastManager.ts:240

Total open connections.

Returns

number

Inherited from

BroadcastManager.connectionCount


_onHandlerError()

protected _onHandlerError(ws, error): void

Defined in: broadcasting/src/BroadcastManager.ts:267

Last-resort handler for a rejection escaping handleMessage.

Logs and, where possible, tells the offending client. Never rethrows: the whole point is that one client's bad frame must not terminate the process serving everyone else.

Parameters

ws

WS

error

unknown

Returns

void

Inherited from

BroadcastManager._onHandlerError


upgradeData()

upgradeData(req): Record<string, unknown>

Defined in: broadcasting/src/BroadcastManager.ts:278

Factory for upgradeData passed to app.withWebSocket().

Parameters

req

Request

Returns

Record<string, unknown>

Inherited from

BroadcastManager.upgradeData


boot()

boot(): Promise<void>

Defined in: broadcasting/src/RedisBroadcastDriver.ts:67

Open the pub + sub connections and start listening for cross-server broadcasts. Call once during application boot.

If _pub/_sub are already set (e.g. injected in tests), this method skips creating new clients and only registers the subscriber callback.

Returns

Promise<void>


stop()

stop(): Promise<void>

Defined in: broadcasting/src/RedisBroadcastDriver.ts:96

Unsubscribe the Redis listener. Called when the application stops.

Returns

Promise<void>


to()

to(channel, event, data?, opts?): void

Defined in: broadcasting/src/RedisBroadcastDriver.ts:105

Publish the event to Redis instead of delivering locally. All server instances — including this one — receive it through the subscriber and deliver it to their own local WS clients.

Parameters

channel

string

event

string

data?

unknown = {}

opts?
exceptSocketId?

string

Returns

void

Overrides

BroadcastManager.to