@bymax-one/nest-realtime 1.0.2 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +38 -1
- package/README.md +2 -0
- package/dist/internal/index.cjs +1621 -0
- package/dist/internal/index.d.cts +1407 -0
- package/dist/internal/index.d.ts +1407 -0
- package/dist/internal/index.mjs +1601 -0
- package/dist/server/index.cjs +76 -1616
- package/dist/server/index.d.cts +1 -846
- package/dist/server/index.d.ts +1 -846
- package/dist/server/index.mjs +1 -1603
- package/dist/websocket/index.cjs +33 -1376
- package/dist/websocket/index.d.cts +4 -685
- package/dist/websocket/index.d.ts +4 -685
- package/dist/websocket/index.mjs +3 -1346
- package/package.json +17 -2
|
@@ -0,0 +1,1407 @@
|
|
|
1
|
+
import { ModuleMetadata, Type, Provider, Logger, DynamicModule, MessageEvent, OnModuleInit, OnApplicationShutdown } from '@nestjs/common';
|
|
2
|
+
import { Subject, Observable } from 'rxjs';
|
|
3
|
+
import { Request, Response } from 'express';
|
|
4
|
+
import { Redis } from 'ioredis';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* @fileoverview Config-level transport mode selection.
|
|
8
|
+
* @layer shared
|
|
9
|
+
*/
|
|
10
|
+
/**
|
|
11
|
+
* Transport mode chosen by the consumer at module configuration time.
|
|
12
|
+
*
|
|
13
|
+
* - `sse` — Server-Sent Events only. HTTP-based, server → client push.
|
|
14
|
+
* - `websocket` — Socket.IO only. Full duplex.
|
|
15
|
+
* - `both` — Compose SSE and WebSocket. Useful during migrations or when
|
|
16
|
+
* different product surfaces need different transports.
|
|
17
|
+
*
|
|
18
|
+
* Distinct from `ITransport.kind` (`'sse' | 'websocket'`), which identifies a
|
|
19
|
+
* single concrete transport implementation. See
|
|
20
|
+
* `docs/technical_specification.md` §1.3 for selection criteria.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* ```ts
|
|
24
|
+
* const mode: TransportMode = 'sse'
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
type TransportMode = 'sse' | 'websocket' | 'both';
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* @fileoverview The single auth contract the library owns (auth inversion).
|
|
31
|
+
* @layer contracts
|
|
32
|
+
*/
|
|
33
|
+
/**
|
|
34
|
+
* Transport-agnostic context passed to `IConnectionAuthenticator.authenticate`.
|
|
35
|
+
*
|
|
36
|
+
* Built from the HTTP request (SSE) or the Socket.IO handshake (WebSocket).
|
|
37
|
+
* Cookies are parsed; header names are normalized to lowercase.
|
|
38
|
+
*/
|
|
39
|
+
interface ConnectionAuthContext {
|
|
40
|
+
/** Cookies parsed from the request/handshake headers. */
|
|
41
|
+
readonly cookies: Record<string, string>;
|
|
42
|
+
/**
|
|
43
|
+
* Selected headers (lowercase keys). `authorization` is always stripped for SSE:
|
|
44
|
+
* an `EventSource` cannot send custom headers, so it is never a valid SSE auth
|
|
45
|
+
* channel (use a cookie or the ticket pattern). It is available for WebSocket.
|
|
46
|
+
*/
|
|
47
|
+
readonly headers: Record<string, string | undefined>;
|
|
48
|
+
/**
|
|
49
|
+
* Query string parameters — useful for the ticket pattern.
|
|
50
|
+
*
|
|
51
|
+
* Values follow the Node `ParsedUrlQuery` shape: a repeated key (`?a=1&a=2`)
|
|
52
|
+
* arrives as a `string[]`. Authenticators that expect a single value should
|
|
53
|
+
* normalize accordingly; the WebSocket gateway already collapses the `ticket`
|
|
54
|
+
* parameter to a single string before delegating.
|
|
55
|
+
*/
|
|
56
|
+
readonly query: Record<string, string | string[] | undefined>;
|
|
57
|
+
/**
|
|
58
|
+
* Client IP — best-effort. Derived from `X-Forwarded-For` when present, which is
|
|
59
|
+
* spoofable unless set by a trusted proxy; do not use it for security decisions
|
|
60
|
+
* without validating the proxy chain.
|
|
61
|
+
*/
|
|
62
|
+
readonly ip: string;
|
|
63
|
+
/** Raw User-Agent. */
|
|
64
|
+
readonly userAgent: string | undefined;
|
|
65
|
+
/** Transport kind initiating the connection. */
|
|
66
|
+
readonly transport: 'sse' | 'websocket';
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Authenticated traits returned by a successful `authenticate()` call. Consumers
|
|
70
|
+
* may carry extra fields through the `metadata` bag.
|
|
71
|
+
*/
|
|
72
|
+
interface AuthenticationResult {
|
|
73
|
+
readonly userId: string;
|
|
74
|
+
readonly tenantId?: string;
|
|
75
|
+
readonly roles?: readonly string[];
|
|
76
|
+
/** Free-form extras for downstream code (e.g. feature flags, plan tier). */
|
|
77
|
+
readonly metadata?: Record<string, unknown>;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Connection authenticator contract — the only auth surface the library owns.
|
|
81
|
+
*
|
|
82
|
+
* Implementations bridge the library to whatever auth strategy the consumer uses
|
|
83
|
+
* (cookie JWT, the ticket pattern, a bearer header in WS, etc.). The library
|
|
84
|
+
* NEVER imports a concrete auth library; see `docs/technical_specification.md`
|
|
85
|
+
* §1.6 ("auth inversion").
|
|
86
|
+
*
|
|
87
|
+
* @example
|
|
88
|
+
* ```ts
|
|
89
|
+
* class CookieAuthenticator implements IConnectionAuthenticator {
|
|
90
|
+
* async authenticate(ctx: ConnectionAuthContext): Promise<AuthenticationResult | null> {
|
|
91
|
+
* const token = ctx.cookies['access_token']
|
|
92
|
+
* if (!token) return null
|
|
93
|
+
* const claims = await verify(token)
|
|
94
|
+
* return { userId: claims.sub, tenantId: claims.tid, roles: claims.roles }
|
|
95
|
+
* }
|
|
96
|
+
* }
|
|
97
|
+
* ```
|
|
98
|
+
*/
|
|
99
|
+
interface IConnectionAuthenticator {
|
|
100
|
+
/**
|
|
101
|
+
* Authenticate a new connection request.
|
|
102
|
+
*
|
|
103
|
+
* @returns the authenticated result, or `null` to reject the connection (the
|
|
104
|
+
* transport replies 401 / disconnects accordingly).
|
|
105
|
+
*/
|
|
106
|
+
authenticate(context: ConnectionAuthContext): Promise<AuthenticationResult | null>;
|
|
107
|
+
/**
|
|
108
|
+
* Optionally re-validate during long sessions. Called periodically based on
|
|
109
|
+
* `reauthenticationPolicy.intervalSeconds`.
|
|
110
|
+
*
|
|
111
|
+
* @returns `true` to keep the connection alive, `false` to disconnect.
|
|
112
|
+
*/
|
|
113
|
+
revalidate?(connectionId: string, originalAuth: AuthenticationResult): Promise<boolean>;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* @fileoverview Optional connection lifecycle hooks the consumer can provide.
|
|
118
|
+
* @layer contracts
|
|
119
|
+
*/
|
|
120
|
+
/** Metadata describing a connection at a lifecycle transition. */
|
|
121
|
+
interface ConnectionEventMeta {
|
|
122
|
+
readonly connectionId: string;
|
|
123
|
+
readonly userId: string;
|
|
124
|
+
readonly tenantId: string | undefined;
|
|
125
|
+
readonly transport: 'sse' | 'websocket';
|
|
126
|
+
readonly ip: string;
|
|
127
|
+
readonly userAgent: string | undefined;
|
|
128
|
+
readonly connectedAt: Date;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Optional lifecycle hooks invoked by the active transport. Every hook may be
|
|
132
|
+
* synchronous or asynchronous; rejected promises are isolated so one failing hook
|
|
133
|
+
* never blocks delivery to other connections.
|
|
134
|
+
*/
|
|
135
|
+
interface IConnectionLifecycleHooks {
|
|
136
|
+
/** Called after authentication succeeds and the connection is registered. */
|
|
137
|
+
onConnect?(meta: ConnectionEventMeta): void | Promise<void>;
|
|
138
|
+
/** Called when the connection closes for any reason. */
|
|
139
|
+
onDisconnect?(meta: ConnectionEventMeta & {
|
|
140
|
+
reason?: string;
|
|
141
|
+
durationMs: number;
|
|
142
|
+
}): void | Promise<void>;
|
|
143
|
+
/** Called on a transport error. */
|
|
144
|
+
onError?(meta: {
|
|
145
|
+
connectionId?: string;
|
|
146
|
+
error: Error;
|
|
147
|
+
transport: 'sse' | 'websocket';
|
|
148
|
+
}): void | Promise<void>;
|
|
149
|
+
/** Called on re-authentication failure, before disconnect. */
|
|
150
|
+
onReauthenticationFailed?(meta: ConnectionEventMeta): void | Promise<void>;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* @fileoverview Cross-instance message bus contract for SSE horizontal scaling.
|
|
155
|
+
* @layer contracts
|
|
156
|
+
*/
|
|
157
|
+
/** A single cross-instance fan-out message. */
|
|
158
|
+
interface RealtimePubSubMessage {
|
|
159
|
+
/** Operation type. */
|
|
160
|
+
readonly op: 'emitToUser' | 'emitToTenant' | 'emitToRoom' | 'broadcast' | 'disconnect';
|
|
161
|
+
/** Operation arguments — the concrete shape is narrowed per `op` at the call site. */
|
|
162
|
+
readonly args: unknown;
|
|
163
|
+
/** Instance id that originated the message (used to avoid echo). */
|
|
164
|
+
readonly origin: string;
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Cross-instance message bus.
|
|
168
|
+
*
|
|
169
|
+
* The library provides `InMemoryPubSub` (the single-instance default) and ships a
|
|
170
|
+
* reference Redis-backed implementation (`RedisRealtimePubSub`) for multi-instance
|
|
171
|
+
* deployments. For WebSocket-only deployments, `@socket.io/redis-adapter` is the
|
|
172
|
+
* recommended scaling primitive and `IRealtimePubSub` is not required.
|
|
173
|
+
*/
|
|
174
|
+
interface IRealtimePubSub {
|
|
175
|
+
/** Publish a message to all subscribers (the other instances). */
|
|
176
|
+
publish(message: RealtimePubSubMessage): Promise<void>;
|
|
177
|
+
/** Subscribe to messages. Resolves to an async unsubscribe handle. */
|
|
178
|
+
subscribe(handler: (message: RealtimePubSubMessage) => void): Promise<() => Promise<void>>;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* @fileoverview Optional durable offline-queue storage for Last-Event-ID replay.
|
|
183
|
+
* @layer contracts
|
|
184
|
+
*/
|
|
185
|
+
/** A single event persisted in a user's offline queue. */
|
|
186
|
+
interface OfflineQueuedEvent {
|
|
187
|
+
/** Monotonic id — used as `Last-Event-ID` across reconnections. */
|
|
188
|
+
readonly id: string;
|
|
189
|
+
readonly event: string;
|
|
190
|
+
readonly data: unknown;
|
|
191
|
+
readonly emittedAt: Date;
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Optional durable per-user offline queue.
|
|
195
|
+
*
|
|
196
|
+
* Consulted as a fallback when a reconnect's gap exceeds the in-memory replay
|
|
197
|
+
* buffer. Implementations should enforce per-user retention (size + TTL).
|
|
198
|
+
*/
|
|
199
|
+
interface IOfflineQueueStorage {
|
|
200
|
+
/** Append an event to a user's offline queue. */
|
|
201
|
+
append(userId: string, event: OfflineQueuedEvent): Promise<void>;
|
|
202
|
+
/** Retrieve events with `id > sinceId`, up to `limit`. */
|
|
203
|
+
retrieveSince(userId: string, sinceId: string, limit: number): Promise<OfflineQueuedEvent[]>;
|
|
204
|
+
/** Mark events delivered up to `upToId`. Implementations may purge or retain. */
|
|
205
|
+
acknowledge(userId: string, upToId: string): Promise<void>;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* @fileoverview Optional presence-tracking contract ("who is online?").
|
|
210
|
+
* @layer contracts
|
|
211
|
+
*/
|
|
212
|
+
/**
|
|
213
|
+
* Optional presence tracking — answers "who is online?" across instances. When it
|
|
214
|
+
* is not provided, presence-dependent features (e.g. the `usePresence` hook) are
|
|
215
|
+
* disabled.
|
|
216
|
+
*/
|
|
217
|
+
interface IPresenceStorage {
|
|
218
|
+
setOnline(userId: string, connectionId: string, tenantId?: string): Promise<void>;
|
|
219
|
+
setOffline(userId: string, connectionId: string): Promise<void>;
|
|
220
|
+
isOnline(userId: string): Promise<boolean>;
|
|
221
|
+
listOnlineByTenant(tenantId: string): Promise<string[]>;
|
|
222
|
+
countOnline(): Promise<number>;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* @fileoverview Module configuration contracts (sync + async dynamic module).
|
|
227
|
+
* @layer contracts
|
|
228
|
+
*/
|
|
229
|
+
|
|
230
|
+
/** CORS configuration shared by the SSE and WebSocket transports. */
|
|
231
|
+
interface CorsConfig {
|
|
232
|
+
origin?: string | readonly string[] | boolean;
|
|
233
|
+
credentials?: boolean;
|
|
234
|
+
methods?: readonly string[];
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* SSE-transport-specific options.
|
|
238
|
+
*
|
|
239
|
+
* CORS for the SSE endpoint is intentionally not configured here: the endpoint is a
|
|
240
|
+
* standard HTTP GET, so cross-origin access is controlled at the NestJS application
|
|
241
|
+
* level (`app.enableCors(...)`). `CorsConfig` applies to the WebSocket transport.
|
|
242
|
+
*/
|
|
243
|
+
interface SseOptions {
|
|
244
|
+
endpoint?: string;
|
|
245
|
+
heartbeatMs?: number;
|
|
246
|
+
replayBufferSize?: number;
|
|
247
|
+
maxConnectionsPerUser?: number;
|
|
248
|
+
emitConnectionEvent?: boolean;
|
|
249
|
+
}
|
|
250
|
+
/** WebSocket-transport-specific options. */
|
|
251
|
+
interface WebSocketOptions {
|
|
252
|
+
namespace?: string;
|
|
253
|
+
cors?: CorsConfig;
|
|
254
|
+
maxHttpBufferSize?: number;
|
|
255
|
+
pingIntervalMs?: number;
|
|
256
|
+
pingTimeoutMs?: number;
|
|
257
|
+
maxConnectionsPerUser?: number;
|
|
258
|
+
/**
|
|
259
|
+
* Emit a `connection:established` event to the client immediately after a
|
|
260
|
+
* successful WebSocket handshake. Defaults to `true`.
|
|
261
|
+
*
|
|
262
|
+
* Transport-neutral for WebSocket and independent of `sse.emitConnectionEvent`,
|
|
263
|
+
* so toggling the SSE flag never changes WebSocket behavior.
|
|
264
|
+
*/
|
|
265
|
+
emitConnectionEvent?: boolean;
|
|
266
|
+
redisAdapter?: {
|
|
267
|
+
/**
|
|
268
|
+
* The ioredis client used by `@socket.io/redis-adapter`. Typed `unknown` so
|
|
269
|
+
* the library never imports `ioredis`; the consumer passes a concrete client
|
|
270
|
+
* and the WebSocket transport calls `.duplicate()` for the subscriber.
|
|
271
|
+
*/
|
|
272
|
+
pubClient: unknown;
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
/** Periodic re-authentication policy for long-lived connections. */
|
|
276
|
+
interface ReauthenticationPolicy {
|
|
277
|
+
intervalSeconds?: number;
|
|
278
|
+
onFailure?: 'disconnect' | 'event';
|
|
279
|
+
cacheTtlMs?: number;
|
|
280
|
+
}
|
|
281
|
+
/** Synchronous module configuration. */
|
|
282
|
+
interface BymaxRealtimeModuleOptions {
|
|
283
|
+
transport: TransportMode;
|
|
284
|
+
service?: {
|
|
285
|
+
name: string;
|
|
286
|
+
version: string;
|
|
287
|
+
};
|
|
288
|
+
authenticator: IConnectionAuthenticator;
|
|
289
|
+
tenantResolver?: (auth: AuthenticationResult) => string | undefined;
|
|
290
|
+
hooks?: IConnectionLifecycleHooks;
|
|
291
|
+
pubsub?: IRealtimePubSub;
|
|
292
|
+
offlineQueue?: IOfflineQueueStorage;
|
|
293
|
+
presence?: IPresenceStorage;
|
|
294
|
+
sse?: SseOptions;
|
|
295
|
+
websocket?: WebSocketOptions;
|
|
296
|
+
reauthenticationPolicy?: ReauthenticationPolicy;
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* Synchronous configuration for `BymaxRealtimeModule`, which serves SSE only.
|
|
300
|
+
*
|
|
301
|
+
* `transport` is narrowed rather than validated at runtime: WebSocket lives
|
|
302
|
+
* behind `@bymax-one/nest-realtime/websocket`, so asking this module for it is
|
|
303
|
+
* a mistake the compiler can catch.
|
|
304
|
+
*/
|
|
305
|
+
type SseRealtimeModuleOptions = Omit<BymaxRealtimeModuleOptions, 'transport'> & {
|
|
306
|
+
transport: 'sse';
|
|
307
|
+
};
|
|
308
|
+
/**
|
|
309
|
+
* Synchronous configuration for `BymaxRealtimeWebSocketModule`, which serves
|
|
310
|
+
* `'websocket'` and `'both'`. An SSE-only application wants the root module.
|
|
311
|
+
*/
|
|
312
|
+
type WebSocketRealtimeModuleOptions = Omit<BymaxRealtimeModuleOptions, 'transport'> & {
|
|
313
|
+
transport: 'websocket' | 'both';
|
|
314
|
+
};
|
|
315
|
+
/** A factory that builds module options (async dynamic-module pattern). */
|
|
316
|
+
interface BymaxRealtimeModuleOptionsFactory {
|
|
317
|
+
createRealtimeOptions(): BymaxRealtimeModuleOptions | Promise<BymaxRealtimeModuleOptions>;
|
|
318
|
+
}
|
|
319
|
+
/** Asynchronous module configuration — the standard NestJS dynamic-module pattern. */
|
|
320
|
+
interface BymaxRealtimeModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'> {
|
|
321
|
+
/**
|
|
322
|
+
* The transport this registration wires. Required, not a hint: providers and
|
|
323
|
+
* controllers are fixed at decoration time, long before a factory runs, so the
|
|
324
|
+
* module cannot discover its own transport later. It MUST equal the
|
|
325
|
+
* `transport` the factory resolves; a mismatch fails fast at bootstrap.
|
|
326
|
+
*/
|
|
327
|
+
transport: TransportMode;
|
|
328
|
+
useFactory?: (...args: unknown[]) => BymaxRealtimeModuleOptions | Promise<BymaxRealtimeModuleOptions>;
|
|
329
|
+
inject?: readonly (string | symbol | Type<unknown>)[];
|
|
330
|
+
useExisting?: Type<BymaxRealtimeModuleOptionsFactory>;
|
|
331
|
+
useClass?: Type<BymaxRealtimeModuleOptionsFactory>;
|
|
332
|
+
/**
|
|
333
|
+
* Additional providers to register alongside the module (e.g. the authenticator
|
|
334
|
+
* class when it is a NestJS-managed injectable).
|
|
335
|
+
*/
|
|
336
|
+
extraProviders?: Provider[];
|
|
337
|
+
}
|
|
338
|
+
/** Asynchronous configuration for `BymaxRealtimeModule` (SSE only). */
|
|
339
|
+
type SseRealtimeModuleAsyncOptions = Omit<BymaxRealtimeModuleAsyncOptions, 'transport'> & {
|
|
340
|
+
transport: 'sse';
|
|
341
|
+
};
|
|
342
|
+
/** Asynchronous configuration for `BymaxRealtimeWebSocketModule`. */
|
|
343
|
+
type WebSocketRealtimeModuleAsyncOptions = Omit<BymaxRealtimeModuleAsyncOptions, 'transport'> & {
|
|
344
|
+
transport: 'websocket' | 'both';
|
|
345
|
+
};
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* @fileoverview Merge consumer options with library defaults (SSE transport).
|
|
349
|
+
* @layer composition
|
|
350
|
+
*/
|
|
351
|
+
|
|
352
|
+
/** Module options with every SSE field resolved to a concrete value. */
|
|
353
|
+
type ResolvedRealtimeOptions = Readonly<BymaxRealtimeModuleOptions & {
|
|
354
|
+
sse: Required<SseOptions>;
|
|
355
|
+
}>;
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* @fileoverview The seam between module composition and transport selection.
|
|
359
|
+
* @layer composition
|
|
360
|
+
*/
|
|
361
|
+
|
|
362
|
+
/** Providers and controllers a transport contributes to the dynamic module. */
|
|
363
|
+
interface TransportRegistration {
|
|
364
|
+
/** Injectable providers, including the `REALTIME_TRANSPORT_TOKEN` binding. */
|
|
365
|
+
readonly providers: Provider[];
|
|
366
|
+
/** SSE controller endpoints to register. Empty for WebSocket-only wiring. */
|
|
367
|
+
readonly endpoints: string[];
|
|
368
|
+
/** Gateway providers. Registered separately so the intent stays readable. */
|
|
369
|
+
readonly gateways: Provider[];
|
|
370
|
+
}
|
|
371
|
+
/**
|
|
372
|
+
* How a given entry point wires transports.
|
|
373
|
+
*
|
|
374
|
+
* This is what keeps `@nestjs/websockets` out of the root bundle. The
|
|
375
|
+
* composition code never names a transport class; each entry point supplies its
|
|
376
|
+
* own wiring, and only the `./websocket` entry imports the Socket.IO stack. A
|
|
377
|
+
* consumer on SSE therefore never loads it — the reason the transports are
|
|
378
|
+
* split across entry points at all.
|
|
379
|
+
*/
|
|
380
|
+
interface TransportWiring {
|
|
381
|
+
/** Transport modes this wiring accepts, for validating configuration. */
|
|
382
|
+
readonly modes: readonly BymaxRealtimeModuleOptions['transport'][];
|
|
383
|
+
/** Wire the transports for a fully resolved, synchronous configuration. */
|
|
384
|
+
build(resolved: ResolvedRealtimeOptions): TransportRegistration;
|
|
385
|
+
/**
|
|
386
|
+
* Wire the transports for the asynchronous path, where options are not known
|
|
387
|
+
* at decoration time. Controllers must be registered then, so the endpoint is
|
|
388
|
+
* fixed rather than read from the resolved options.
|
|
389
|
+
*/
|
|
390
|
+
buildAsync(mode: BymaxRealtimeModuleOptions['transport']): {
|
|
391
|
+
readonly providers: Provider[];
|
|
392
|
+
readonly controllers: Type<unknown>[];
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* Compose the synchronous dynamic module for an entry point.
|
|
398
|
+
*
|
|
399
|
+
* @throws when the options are invalid or name a transport this entry point
|
|
400
|
+
* does not serve.
|
|
401
|
+
*/
|
|
402
|
+
declare function composeForRoot(moduleClass: Type<unknown>, wiring: TransportWiring, logger: Logger, options: BymaxRealtimeModuleOptions): DynamicModule;
|
|
403
|
+
/**
|
|
404
|
+
* Compose the asynchronous dynamic module for an entry point.
|
|
405
|
+
*
|
|
406
|
+
* `transport` is required here, unlike a hint that could be omitted: providers
|
|
407
|
+
* and controllers are fixed at decoration time, long before a factory runs, so
|
|
408
|
+
* the module cannot discover its own transport later. Declaring it is what lets
|
|
409
|
+
* an SSE application register no gateway at all.
|
|
410
|
+
*
|
|
411
|
+
* @throws when the registration names no factory pattern, names more than one,
|
|
412
|
+
* or names a transport this entry point does not serve.
|
|
413
|
+
*/
|
|
414
|
+
declare function composeForRootAsync(moduleClass: Type<unknown>, wiring: TransportWiring, logger: Logger, asyncOptions: BymaxRealtimeModuleAsyncOptions): DynamicModule;
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* Wiring for Server-Sent Events, and the reason the root entry point carries no
|
|
418
|
+
* Socket.IO. Nothing reachable from here imports `@nestjs/websockets`, so an SSE
|
|
419
|
+
* application installs neither it nor `socket.io`.
|
|
420
|
+
*/
|
|
421
|
+
declare const sseWiring: TransportWiring;
|
|
422
|
+
|
|
423
|
+
/**
|
|
424
|
+
* Realtime module for Server-Sent Events. Registered globally so a single
|
|
425
|
+
* configuration serves the whole application.
|
|
426
|
+
*
|
|
427
|
+
* WebSocket lives behind `@bymax-one/nest-realtime/websocket`, and that split is
|
|
428
|
+
* what this module buys: nothing reachable from here imports
|
|
429
|
+
* `@nestjs/websockets` or `socket.io`, so an SSE application never installs the
|
|
430
|
+
* Socket.IO stack. Reach for `BymaxRealtimeWebSocketModule` when the transport
|
|
431
|
+
* is `'websocket'` or `'both'`.
|
|
432
|
+
*/
|
|
433
|
+
declare class BymaxRealtimeModule {
|
|
434
|
+
private static readonly logger;
|
|
435
|
+
/**
|
|
436
|
+
* Configure the module synchronously.
|
|
437
|
+
*
|
|
438
|
+
* @throws when the options are invalid.
|
|
439
|
+
* @example
|
|
440
|
+
* ```ts
|
|
441
|
+
* BymaxRealtimeModule.forRoot({
|
|
442
|
+
* transport: 'sse',
|
|
443
|
+
* authenticator: new MyAuthenticator(),
|
|
444
|
+
* })
|
|
445
|
+
* ```
|
|
446
|
+
*/
|
|
447
|
+
static forRoot(options: SseRealtimeModuleOptions): DynamicModule;
|
|
448
|
+
/**
|
|
449
|
+
* Configure the module asynchronously so options — and the authenticator —
|
|
450
|
+
* can be resolved through DI: `ConfigService`, a Redis client, and so on.
|
|
451
|
+
*
|
|
452
|
+
* Options are validated inside the resolving factory, so a malformed
|
|
453
|
+
* configuration rejects at bootstrap and the application fails to start with
|
|
454
|
+
* a clear error.
|
|
455
|
+
*
|
|
456
|
+
* Controllers are registered at decoration time, so this path binds the SSE
|
|
457
|
+
* controller to the default endpoint `/events`. A non-default endpoint needs
|
|
458
|
+
* `forRoot` with pre-resolved options.
|
|
459
|
+
*
|
|
460
|
+
* @throws when no factory pattern is given, more than one is, or the factory
|
|
461
|
+
* resolves a transport other than `'sse'`.
|
|
462
|
+
* @example
|
|
463
|
+
* ```ts
|
|
464
|
+
* BymaxRealtimeModule.forRootAsync({
|
|
465
|
+
* transport: 'sse',
|
|
466
|
+
* imports: [ConfigModule],
|
|
467
|
+
* inject: [ConfigService],
|
|
468
|
+
* useFactory: (cfg: ConfigService) => ({
|
|
469
|
+
* transport: 'sse' as const,
|
|
470
|
+
* authenticator: new CookieJwtAuthenticator(cfg.getOrThrow('JWT_SECRET')),
|
|
471
|
+
* }),
|
|
472
|
+
* })
|
|
473
|
+
* ```
|
|
474
|
+
*/
|
|
475
|
+
static forRootAsync(asyncOptions: SseRealtimeModuleAsyncOptions): DynamicModule;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/**
|
|
479
|
+
* @fileoverview Dependency-injection tokens (unique Symbols) and shared module-level constants.
|
|
480
|
+
* @layer composition
|
|
481
|
+
*/
|
|
482
|
+
/**
|
|
483
|
+
* Dependency-injection tokens.
|
|
484
|
+
*
|
|
485
|
+
* Symbols are used instead of strings so tokens are guaranteed unique at runtime
|
|
486
|
+
* and cannot collide with tokens from other libraries.
|
|
487
|
+
*/
|
|
488
|
+
declare const REALTIME_OPTIONS_TOKEN: unique symbol;
|
|
489
|
+
declare const REALTIME_TRANSPORT_TOKEN: unique symbol;
|
|
490
|
+
declare const REALTIME_AUTHENTICATOR_TOKEN: unique symbol;
|
|
491
|
+
declare const REALTIME_PUBSUB_TOKEN: unique symbol;
|
|
492
|
+
declare const REALTIME_OFFLINE_QUEUE_TOKEN: unique symbol;
|
|
493
|
+
declare const REALTIME_PRESENCE_TOKEN: unique symbol;
|
|
494
|
+
declare const REALTIME_HOOKS_TOKEN: unique symbol;
|
|
495
|
+
declare const REALTIME_INSTANCE_ID_TOKEN: unique symbol;
|
|
496
|
+
|
|
497
|
+
/** Transport kind a connection belongs to. */
|
|
498
|
+
type ConnectionTransport = 'sse' | 'websocket';
|
|
499
|
+
/**
|
|
500
|
+
* Internal record kept per active connection.
|
|
501
|
+
*
|
|
502
|
+
* `subject` and `close$` are populated only for SSE connections (the per-connection
|
|
503
|
+
* RxJS stream and its server-initiated teardown signal). WebSocket connections set
|
|
504
|
+
* both to `null` and rely on the Socket.IO server's own emit/disconnect mechanism.
|
|
505
|
+
*/
|
|
506
|
+
interface ConnectionRecord {
|
|
507
|
+
connectionId: string;
|
|
508
|
+
userId: string;
|
|
509
|
+
tenantId: string | undefined;
|
|
510
|
+
transport: ConnectionTransport;
|
|
511
|
+
ip: string;
|
|
512
|
+
userAgent: string | undefined;
|
|
513
|
+
connectedAt: Date;
|
|
514
|
+
/** Per-connection event stream (SSE only); `null` for WebSocket. */
|
|
515
|
+
subject: Subject<MessageEvent> | null;
|
|
516
|
+
/** Server-initiated teardown signal (SSE only); `null` for WebSocket. */
|
|
517
|
+
close$: Subject<void> | null;
|
|
518
|
+
/** Snapshot of the original authentication result — used by the re-auth policy. */
|
|
519
|
+
originalAuth: {
|
|
520
|
+
userId: string;
|
|
521
|
+
tenantId: string | undefined;
|
|
522
|
+
roles: readonly string[] | undefined;
|
|
523
|
+
};
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* Indexed registry of active connections.
|
|
527
|
+
*
|
|
528
|
+
* Maintains three maps — `byId` (connectionId → record), `byUserId` (userId →
|
|
529
|
+
* Set<connectionId>) and `byTenantId` (tenantId → Set<connectionId>) — kept
|
|
530
|
+
* consistent on every `register`/`unregister`. Operations are amortized O(1);
|
|
531
|
+
* mutation is single-threaded (the Node.js event loop), so no locking is needed.
|
|
532
|
+
*/
|
|
533
|
+
declare class ConnectionRegistry {
|
|
534
|
+
private readonly byId;
|
|
535
|
+
private readonly byUserId;
|
|
536
|
+
private readonly byTenantId;
|
|
537
|
+
/** Register a connection and index it by user and tenant. */
|
|
538
|
+
register(record: ConnectionRecord): void;
|
|
539
|
+
/** Remove a connection from every index. Returns the removed record, if any. */
|
|
540
|
+
unregister(connectionId: string): ConnectionRecord | undefined;
|
|
541
|
+
/** Look up a single connection by id. */
|
|
542
|
+
get(connectionId: string): ConnectionRecord | undefined;
|
|
543
|
+
/** All connections of a user, optionally filtered by transport. */
|
|
544
|
+
byUser(userId: string, transport?: ConnectionTransport): ConnectionRecord[];
|
|
545
|
+
/** All connections of a tenant, optionally filtered by transport. */
|
|
546
|
+
byTenant(tenantId: string, transport?: ConnectionTransport): ConnectionRecord[];
|
|
547
|
+
/** All connections of a given transport. */
|
|
548
|
+
allByTransport(transport: ConnectionTransport): ConnectionRecord[];
|
|
549
|
+
/** Total number of active connections. */
|
|
550
|
+
count(): number;
|
|
551
|
+
/** Number of distinct users currently connected. */
|
|
552
|
+
countUsers(): number;
|
|
553
|
+
private resolve;
|
|
554
|
+
private addToSetMap;
|
|
555
|
+
private removeFromSetMap;
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
/**
|
|
559
|
+
* Generates monotonically increasing event ids of the form
|
|
560
|
+
* `{epochMillis}-{counter}`, where the counter resets every millisecond.
|
|
561
|
+
*
|
|
562
|
+
* Guarantees:
|
|
563
|
+
* - Lexicographically sortable (the counter is zero-padded to a fixed width), so
|
|
564
|
+
* `Last-Event-ID` replay can string-compare ids.
|
|
565
|
+
* - Monotonic within a single instance even when called repeatedly at the same
|
|
566
|
+
* epoch millisecond.
|
|
567
|
+
*
|
|
568
|
+
* @example
|
|
569
|
+
* ```ts
|
|
570
|
+
* gen.next() // → '1717000000000-000001'
|
|
571
|
+
* gen.next() // → '1717000000000-000002'
|
|
572
|
+
* ```
|
|
573
|
+
*/
|
|
574
|
+
declare class EventIdGenerator {
|
|
575
|
+
private lastMs;
|
|
576
|
+
private counter;
|
|
577
|
+
/** Produce the next monotonic event id. */
|
|
578
|
+
next(): string;
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
/**
|
|
582
|
+
* @fileoverview Unified transport abstraction implemented by every transport.
|
|
583
|
+
* @layer contracts
|
|
584
|
+
*/
|
|
585
|
+
/**
|
|
586
|
+
* Unified transport abstraction.
|
|
587
|
+
*
|
|
588
|
+
* The library ships concrete implementations (`SseTransport`, the WebSocket
|
|
589
|
+
* transport, and a composite that fans out to both). Consumers normally interact
|
|
590
|
+
* with `RealtimeService`, which delegates to the active transport; implementing a
|
|
591
|
+
* custom `ITransport` is an advanced use case (e.g. bridging an external bus).
|
|
592
|
+
*
|
|
593
|
+
* @example
|
|
594
|
+
* ```ts
|
|
595
|
+
* class NoopTransport implements ITransport {
|
|
596
|
+
* readonly kind = 'sse' as const
|
|
597
|
+
* async emitToUser() {}
|
|
598
|
+
* async emitToTenant() {}
|
|
599
|
+
* async emitToRoom() {}
|
|
600
|
+
* async broadcast() {}
|
|
601
|
+
* async joinRoom() {}
|
|
602
|
+
* async leaveRoom() {}
|
|
603
|
+
* async disconnect() {}
|
|
604
|
+
* }
|
|
605
|
+
* ```
|
|
606
|
+
*/
|
|
607
|
+
interface ITransport {
|
|
608
|
+
/** Transport identifier. A composite reports its dominant kind (`'sse'`). */
|
|
609
|
+
readonly kind: 'sse' | 'websocket';
|
|
610
|
+
/** Send to every connection of a single user. */
|
|
611
|
+
emitToUser(userId: string, event: string, data: unknown): Promise<void>;
|
|
612
|
+
/** Send to every connection of every user in a tenant. */
|
|
613
|
+
emitToTenant(tenantId: string, event: string, data: unknown): Promise<void>;
|
|
614
|
+
/** Send to every connection in a logical room. */
|
|
615
|
+
emitToRoom(roomId: string, event: string, data: unknown): Promise<void>;
|
|
616
|
+
/** Send to all connected clients. Use sparingly. */
|
|
617
|
+
broadcast(event: string, data: unknown): Promise<void>;
|
|
618
|
+
/** Join a connection to a room (idempotent). */
|
|
619
|
+
joinRoom(connectionId: string, roomId: string): Promise<void>;
|
|
620
|
+
/** Leave a connection from a room (idempotent). */
|
|
621
|
+
leaveRoom(connectionId: string, roomId: string): Promise<void>;
|
|
622
|
+
/** Disconnect a specific connection (e.g. on auth revocation). */
|
|
623
|
+
disconnect(connectionId: string, reason?: string): Promise<void>;
|
|
624
|
+
/** Lifecycle hook — called on NestJS bootstrap. */
|
|
625
|
+
onModuleInit?(): Promise<void>;
|
|
626
|
+
/** Lifecycle hook — called on NestJS shutdown. */
|
|
627
|
+
onApplicationShutdown?(): Promise<void>;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/**
|
|
631
|
+
* Transport-agnostic realtime API.
|
|
632
|
+
*
|
|
633
|
+
* Every method delegates to the active transport, so switching transport (for
|
|
634
|
+
* example `'sse'` → `'websocket'`) requires no change in the application services
|
|
635
|
+
* that call this API.
|
|
636
|
+
*/
|
|
637
|
+
declare class RealtimeService {
|
|
638
|
+
private readonly transport;
|
|
639
|
+
constructor(transport: ITransport);
|
|
640
|
+
/**
|
|
641
|
+
* Send to all of a user's connections (across devices/tabs).
|
|
642
|
+
*
|
|
643
|
+
* @example
|
|
644
|
+
* ```ts
|
|
645
|
+
* await realtime.emitToUser('u_abc', 'invoice.paid', { id: 'inv_123' })
|
|
646
|
+
* ```
|
|
647
|
+
*/
|
|
648
|
+
emitToUser(userId: string, event: string, data: unknown): Promise<void>;
|
|
649
|
+
/** Send to every connection in a tenant. */
|
|
650
|
+
emitToTenant(tenantId: string, event: string, data: unknown): Promise<void>;
|
|
651
|
+
/**
|
|
652
|
+
* Send to a logical room. Use the prefix convention (`user:{id}`,
|
|
653
|
+
* `tenant:{id}`, `resource:{type}:{id}`) or a custom non-colliding id.
|
|
654
|
+
*/
|
|
655
|
+
emitToRoom(roomId: string, event: string, data: unknown): Promise<void>;
|
|
656
|
+
/** Send to every connected client. Use sparingly. */
|
|
657
|
+
broadcast(event: string, data: unknown): Promise<void>;
|
|
658
|
+
/** Add a specific connection to a room. */
|
|
659
|
+
joinRoom(connectionId: string, roomId: string): Promise<void>;
|
|
660
|
+
/** Remove a specific connection from a room. */
|
|
661
|
+
leaveRoom(connectionId: string, roomId: string): Promise<void>;
|
|
662
|
+
/** Force-disconnect a specific connection (e.g. on auth revocation). */
|
|
663
|
+
disconnect(connectionId: string, reason?: string): Promise<void>;
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
/**
|
|
667
|
+
* @fileoverview Periodic re-authentication service with positive-result cache.
|
|
668
|
+
* @layer application
|
|
669
|
+
*/
|
|
670
|
+
|
|
671
|
+
/**
|
|
672
|
+
* Periodically revalidates active SSE connections through the consumer-provided
|
|
673
|
+
* `IConnectionAuthenticator.revalidate` contract.
|
|
674
|
+
*
|
|
675
|
+
* A short positive cache (default 60 s) avoids hammering the auth backend on every
|
|
676
|
+
* interval tick. On failure the service either disconnects immediately or first emits
|
|
677
|
+
* `connection:reauthentication-failed` then disconnects, depending on the configured
|
|
678
|
+
* `reauthenticationPolicy.onFailure` value.
|
|
679
|
+
*
|
|
680
|
+
* The `revalidate` method is optional on the authenticator interface. When absent,
|
|
681
|
+
* the service logs an informative message and stays idle.
|
|
682
|
+
*/
|
|
683
|
+
declare class ReauthenticationService implements OnModuleInit, OnApplicationShutdown {
|
|
684
|
+
private readonly connections;
|
|
685
|
+
private readonly realtime;
|
|
686
|
+
private readonly auth;
|
|
687
|
+
private readonly hooks?;
|
|
688
|
+
private readonly logger;
|
|
689
|
+
private timer;
|
|
690
|
+
/** connectionId → epoch-ms timestamp of last successful revalidation. */
|
|
691
|
+
private readonly positiveCache;
|
|
692
|
+
private readonly policy;
|
|
693
|
+
constructor(connections: ConnectionRegistry, realtime: RealtimeService, auth: IConnectionAuthenticator, options: BymaxRealtimeModuleOptions, hooks?: IConnectionLifecycleHooks | undefined);
|
|
694
|
+
/**
|
|
695
|
+
* Schedule the periodic revalidation cycle.
|
|
696
|
+
*
|
|
697
|
+
* The timer is unref'd so it never keeps the process alive on its own.
|
|
698
|
+
* When the authenticator does not implement `revalidate`, the service stays
|
|
699
|
+
* idle and emits an informative log.
|
|
700
|
+
*/
|
|
701
|
+
onModuleInit(): void;
|
|
702
|
+
/**
|
|
703
|
+
* Clear the timer and the positive cache.
|
|
704
|
+
*
|
|
705
|
+
* Called by NestJS on graceful shutdown to prevent leaks.
|
|
706
|
+
*/
|
|
707
|
+
onApplicationShutdown(): void;
|
|
708
|
+
/**
|
|
709
|
+
* Run one revalidation cycle over all active SSE connections.
|
|
710
|
+
*
|
|
711
|
+
* A cache hit within `cacheTtlMs` skips the `revalidate` call. A positive result
|
|
712
|
+
* refreshes the cache. A negative result (or a thrown error) invokes the configured
|
|
713
|
+
* `onFailure` policy and fires the `onReauthenticationFailed` hook best-effort.
|
|
714
|
+
*
|
|
715
|
+
* Exposed as public for test access.
|
|
716
|
+
*/
|
|
717
|
+
runCycle(): Promise<void>;
|
|
718
|
+
/** Evict the positive-cache entry, optionally emit the failure event, then disconnect. */
|
|
719
|
+
private handleFailure;
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/**
|
|
723
|
+
* Indexed registry of room membership.
|
|
724
|
+
*
|
|
725
|
+
* Maintains two maps — `rooms` (roomId → Set<connectionId>) and `connectionRooms`
|
|
726
|
+
* (connectionId → Set<roomId>). The reverse index makes `leaveAll()` on disconnect
|
|
727
|
+
* O(rooms-per-connection) instead of O(total rooms).
|
|
728
|
+
*/
|
|
729
|
+
declare class RoomRegistry {
|
|
730
|
+
private readonly rooms;
|
|
731
|
+
private readonly connectionRooms;
|
|
732
|
+
/** Join a connection to a room (idempotent). */
|
|
733
|
+
join(connectionId: string, roomId: string): void;
|
|
734
|
+
/** Remove a connection from a room (idempotent); prunes empty entries. */
|
|
735
|
+
leave(connectionId: string, roomId: string): void;
|
|
736
|
+
/** Snapshot of a room's members — safe to iterate while membership mutates. */
|
|
737
|
+
members(roomId: string): readonly string[];
|
|
738
|
+
/** Snapshot of the rooms a connection currently belongs to. */
|
|
739
|
+
roomsOf(connectionId: string): readonly string[];
|
|
740
|
+
/** Remove a connection from every room (called on disconnect). */
|
|
741
|
+
leaveAll(connectionId: string): void;
|
|
742
|
+
/** Total number of distinct rooms. */
|
|
743
|
+
countRooms(): number;
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
/**
|
|
747
|
+
* Fetches events from the offline queue that the client missed since `lastEventId`
|
|
748
|
+
* and de-duplicates them against the in-memory replay buffer.
|
|
749
|
+
*
|
|
750
|
+
* Retrieval and acknowledgment are split to preserve at-least-once delivery:
|
|
751
|
+
* `retrieve` never prunes the durable queue, and `acknowledge` is called only after
|
|
752
|
+
* the events have been emitted to a live subscriber. A client that disconnects before
|
|
753
|
+
* emission therefore keeps its gap events durable for redelivery on the next reconnect.
|
|
754
|
+
*
|
|
755
|
+
* Injected `@Optional()` so consumers that do not configure an offline queue still
|
|
756
|
+
* get a no-op service (returns `[]`).
|
|
757
|
+
*/
|
|
758
|
+
declare class OfflineQueueDeliveryService {
|
|
759
|
+
private readonly storage?;
|
|
760
|
+
private readonly logger;
|
|
761
|
+
constructor(storage?: IOfflineQueueStorage | undefined);
|
|
762
|
+
/**
|
|
763
|
+
* Return events for `userId` that arrived after `lastEventId` and are NOT
|
|
764
|
+
* already covered by `ringBufferIds` (already replayed from in-memory buffer).
|
|
765
|
+
*
|
|
766
|
+
* Retrieval does NOT acknowledge: the durable queue is pruned only after the events
|
|
767
|
+
* have been emitted to a live subscriber via {@link acknowledge}. This guarantees
|
|
768
|
+
* at-least-once delivery — events that never reach the client are never lost.
|
|
769
|
+
*
|
|
770
|
+
* @param userId - The reconnecting user.
|
|
771
|
+
* @param lastEventId - The `Last-Event-ID` header value.
|
|
772
|
+
* @param ringBufferIds - Set of event ids already replayed from the ring buffer.
|
|
773
|
+
* @returns Gap events, or an empty array when no offline queue is configured.
|
|
774
|
+
*/
|
|
775
|
+
retrieve(userId: string, lastEventId: string, ringBufferIds: Set<string>): Promise<OfflineQueuedEvent[]>;
|
|
776
|
+
/**
|
|
777
|
+
* Acknowledge delivered offline events so the storage backend can prune them.
|
|
778
|
+
*
|
|
779
|
+
* At-least-once contract: call this ONLY after the events have been emitted to a
|
|
780
|
+
* still-open subscriber. Acknowledging before emission would permanently drop events
|
|
781
|
+
* that never reached the client. A failure is swallowed (logged) so a transient
|
|
782
|
+
* storage error never disrupts delivery; the events simply redeliver on reconnect.
|
|
783
|
+
*
|
|
784
|
+
* @param userId - The user whose queue is acknowledged.
|
|
785
|
+
* @param events - The delivered gap events; the last id is the prune watermark.
|
|
786
|
+
*/
|
|
787
|
+
acknowledge(userId: string, events: readonly OfflineQueuedEvent[]): Promise<void>;
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
/**
|
|
791
|
+
* Per-user ring buffer of recent events for `Last-Event-ID` replay.
|
|
792
|
+
*
|
|
793
|
+
* In-memory by design — it survives only as long as the process. Per-user buffers
|
|
794
|
+
* prevent one user from poisoning another's replay state. For durable replay
|
|
795
|
+
* (instance restart, or a gap larger than the buffer), a consumer can plug
|
|
796
|
+
* `IOfflineQueueStorage` as a fallback.
|
|
797
|
+
*
|
|
798
|
+
* @example
|
|
799
|
+
* ```ts
|
|
800
|
+
* // On reconnect with `Last-Event-ID: <id>`, replay what was missed:
|
|
801
|
+
* const missed = replayBuffer.since(userId, lastEventId)
|
|
802
|
+
* ```
|
|
803
|
+
*/
|
|
804
|
+
declare class EventReplayBuffer {
|
|
805
|
+
private readonly opts;
|
|
806
|
+
private readonly buffers;
|
|
807
|
+
constructor(opts: BymaxRealtimeModuleOptions);
|
|
808
|
+
/** Append an event to a user's ring buffer, evicting the oldest beyond the cap. */
|
|
809
|
+
append(userId: string, event: MessageEvent): void;
|
|
810
|
+
/**
|
|
811
|
+
* Return the events emitted after `lastEventId`.
|
|
812
|
+
*
|
|
813
|
+
* Returns an empty array when the user has no buffer, or when `lastEventId` is
|
|
814
|
+
* not present (a gap — the caller should fall back to `IOfflineQueueStorage`).
|
|
815
|
+
*/
|
|
816
|
+
since(userId: string, lastEventId: string): MessageEvent[];
|
|
817
|
+
/** Number of events currently buffered for a user (diagnostics). */
|
|
818
|
+
size(userId: string): number;
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
/** Minimal response surface the heartbeat needs — a writable text stream. */
|
|
822
|
+
interface HeartbeatWritable {
|
|
823
|
+
write(chunk: string): unknown;
|
|
824
|
+
}
|
|
825
|
+
/**
|
|
826
|
+
* Emits the SSE keepalive on an interval, per connection.
|
|
827
|
+
*
|
|
828
|
+
* The keepalive is a raw `: keepalive\n\n` comment written DIRECTLY to the response
|
|
829
|
+
* stream — not a `MessageEvent`, not a named event, and outside the `Last-Event-ID`
|
|
830
|
+
* id-space — so it never corrupts replay. Comments keep proxies and load balancers
|
|
831
|
+
* from idling out the connection. Timers are tracked per connection and cleared on
|
|
832
|
+
* `stop`.
|
|
833
|
+
*
|
|
834
|
+
* The configured interval must be within `[5_000, 90_000]` ms; values outside this
|
|
835
|
+
* range throw a `REALTIME_INVALID_OPTIONS` error.
|
|
836
|
+
*
|
|
837
|
+
* See `docs/proxies-cheat-sheet.md` for nginx, Cloudflare, and AWS ALB configuration.
|
|
838
|
+
*/
|
|
839
|
+
declare class HeartbeatService {
|
|
840
|
+
private readonly timers;
|
|
841
|
+
/**
|
|
842
|
+
* Start writing keepalives for a connection every `intervalMs`.
|
|
843
|
+
*
|
|
844
|
+
* @param connectionId - Unique connection identifier used to track the timer.
|
|
845
|
+
* @param res - The writable response stream (or any object with a `write` method).
|
|
846
|
+
* @param intervalMs - Keepalive interval in milliseconds; must be within
|
|
847
|
+
* `[5_000, 90_000]`.
|
|
848
|
+
* @throws {Error} When `intervalMs` is outside the valid range.
|
|
849
|
+
*/
|
|
850
|
+
start(connectionId: string, res: HeartbeatWritable, intervalMs: number): void;
|
|
851
|
+
/** Stop and clear the keepalive timer for a connection (idempotent). */
|
|
852
|
+
stop(connectionId: string): void;
|
|
853
|
+
/** Stop every keepalive timer (used on shutdown). */
|
|
854
|
+
stopAll(): void;
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
/** Parameters required to register a freshly authenticated SSE connection. */
|
|
858
|
+
interface RegisterSseConnectionParams {
|
|
859
|
+
connectionId: string;
|
|
860
|
+
auth: AuthenticationResult;
|
|
861
|
+
subject: Subject<MessageEvent>;
|
|
862
|
+
close$: Subject<void>;
|
|
863
|
+
ip: string;
|
|
864
|
+
userAgent: string | undefined;
|
|
865
|
+
}
|
|
866
|
+
/**
|
|
867
|
+
* SSE transport implementation.
|
|
868
|
+
*
|
|
869
|
+
* Each public `emitTo*`/`broadcast` performs local delivery via the matching
|
|
870
|
+
* `*Local` method and then publishes exactly once to `IRealtimePubSub`. Remote
|
|
871
|
+
* messages received from the bus are dispatched by `RealtimePubSubSubscriber`
|
|
872
|
+
* (not this class) to the `*Local` methods only (never re-published), and
|
|
873
|
+
* self-originated messages are filtered there — so a single instance never
|
|
874
|
+
* double-delivers and multiple instances never ping-pong.
|
|
875
|
+
*
|
|
876
|
+
* Teardown of an SSE stream is driven by the per-connection `close$` subject:
|
|
877
|
+
* `disconnectLocal` completes it (which ends the `@Sse` Observable via
|
|
878
|
+
* `takeUntil`) before unregistering. See `docs/technical_specification.md` §6.1.
|
|
879
|
+
*/
|
|
880
|
+
declare class SseTransport implements ITransport {
|
|
881
|
+
private readonly connections;
|
|
882
|
+
private readonly rooms;
|
|
883
|
+
private readonly replayBuffer;
|
|
884
|
+
private readonly idGen;
|
|
885
|
+
private readonly heartbeat;
|
|
886
|
+
private readonly auth;
|
|
887
|
+
private readonly pubsub;
|
|
888
|
+
private readonly hooks;
|
|
889
|
+
private readonly options;
|
|
890
|
+
private readonly instanceId;
|
|
891
|
+
private readonly offlineQueue?;
|
|
892
|
+
readonly kind: "sse";
|
|
893
|
+
private readonly logger;
|
|
894
|
+
constructor(connections: ConnectionRegistry, rooms: RoomRegistry, replayBuffer: EventReplayBuffer, idGen: EventIdGenerator, heartbeat: HeartbeatService, auth: IConnectionAuthenticator, pubsub: IRealtimePubSub, hooks: IConnectionLifecycleHooks, options: BymaxRealtimeModuleOptions, instanceId: string, offlineQueue?: IOfflineQueueStorage | undefined);
|
|
895
|
+
/** Tear down every SSE connection and stop heartbeat on process shutdown. */
|
|
896
|
+
onApplicationShutdown(): Promise<void>;
|
|
897
|
+
/** The resolved heartbeat interval for this transport. */
|
|
898
|
+
get heartbeatMs(): number;
|
|
899
|
+
/** Whether the `connection:established` event should be emitted on connect. */
|
|
900
|
+
get emitConnectionEvent(): boolean;
|
|
901
|
+
/** Authenticate a connection through the consumer-provided authenticator. */
|
|
902
|
+
authenticate(context: ConnectionAuthContext): Promise<AuthenticationResult | null>;
|
|
903
|
+
/**
|
|
904
|
+
* Register an authenticated SSE connection and auto-join its user/tenant rooms.
|
|
905
|
+
*
|
|
906
|
+
* Fires FIFO eviction if the user exceeds `maxConnectionsPerUser`. The `onConnect`
|
|
907
|
+
* lifecycle hook is fired by the subscription handler after this returns, so that the
|
|
908
|
+
* handler can carry a consistent connection record reference.
|
|
909
|
+
*/
|
|
910
|
+
registerConnection(params: RegisterSseConnectionParams): Promise<void>;
|
|
911
|
+
/** Idempotent cleanup for a connection — runs the disconnect hook exactly once. */
|
|
912
|
+
unregisterConnection(connectionId: string, reason?: string): Promise<void>;
|
|
913
|
+
/** Replay the events a user missed after `lastEventId`. */
|
|
914
|
+
getReplayEvents(userId: string, lastEventId: string): MessageEvent[];
|
|
915
|
+
/**
|
|
916
|
+
* All SSE connections for a user — public accessor so external callers can
|
|
917
|
+
* inspect or iterate without reaching into a private registry field.
|
|
918
|
+
*
|
|
919
|
+
* @param userId - The user whose active connections are returned.
|
|
920
|
+
* @returns A snapshot of the user's current SSE `ConnectionRecord` list.
|
|
921
|
+
*/
|
|
922
|
+
connectionsForUser(userId: string): ConnectionRecord[];
|
|
923
|
+
/**
|
|
924
|
+
* Look up a single connection by id.
|
|
925
|
+
*
|
|
926
|
+
* @param connectionId - The unique connection identifier.
|
|
927
|
+
* @returns The `ConnectionRecord`, or `undefined` when not found.
|
|
928
|
+
*/
|
|
929
|
+
getConnection(connectionId: string): ConnectionRecord | undefined;
|
|
930
|
+
emitToUser(userId: string, event: string, data: unknown): Promise<void>;
|
|
931
|
+
emitToTenant(tenantId: string, event: string, data: unknown): Promise<void>;
|
|
932
|
+
emitToRoom(roomId: string, event: string, data: unknown): Promise<void>;
|
|
933
|
+
broadcast(event: string, data: unknown): Promise<void>;
|
|
934
|
+
joinRoom(connectionId: string, roomId: string): Promise<void>;
|
|
935
|
+
leaveRoom(connectionId: string, roomId: string): Promise<void>;
|
|
936
|
+
/** Disconnect a connection locally if owned here, otherwise revoke cross-instance. */
|
|
937
|
+
disconnect(connectionId: string, reason?: string): Promise<void>;
|
|
938
|
+
/**
|
|
939
|
+
* Deliver an event to a user's local SSE connections and update the replay buffer.
|
|
940
|
+
*
|
|
941
|
+
* @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
|
|
942
|
+
* must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
|
|
943
|
+
*/
|
|
944
|
+
emitToUserLocal(userId: string, event: string, data: unknown, id: string): void;
|
|
945
|
+
/**
|
|
946
|
+
* Deliver an event to all local SSE connections for a tenant.
|
|
947
|
+
*
|
|
948
|
+
* @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
|
|
949
|
+
* must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
|
|
950
|
+
* @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
|
|
951
|
+
* buffer or offline queue — only emitToUser populates per-user replay/offline state.
|
|
952
|
+
*/
|
|
953
|
+
emitToTenantLocal(tenantId: string, event: string, data: unknown, id: string): void;
|
|
954
|
+
/**
|
|
955
|
+
* Deliver an event to all local SSE connections that joined the given room.
|
|
956
|
+
*
|
|
957
|
+
* @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
|
|
958
|
+
* must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
|
|
959
|
+
* @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
|
|
960
|
+
* buffer or offline queue — only emitToUser populates per-user replay/offline state.
|
|
961
|
+
*/
|
|
962
|
+
emitToRoomLocal(roomId: string, event: string, data: unknown, id: string): void;
|
|
963
|
+
/**
|
|
964
|
+
* Deliver an event to all local SSE connections.
|
|
965
|
+
*
|
|
966
|
+
* @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
|
|
967
|
+
* must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
|
|
968
|
+
* @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
|
|
969
|
+
* buffer or offline queue — only emitToUser populates per-user replay/offline state.
|
|
970
|
+
*/
|
|
971
|
+
broadcastLocal(event: string, data: unknown, id: string): void;
|
|
972
|
+
/**
|
|
973
|
+
* Tear down a locally-owned SSE stream, then clean up (no re-publish).
|
|
974
|
+
*
|
|
975
|
+
* @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
|
|
976
|
+
* must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
|
|
977
|
+
*/
|
|
978
|
+
disconnectLocal(connectionId: string, reason?: string): Promise<void>;
|
|
979
|
+
private buildMessage;
|
|
980
|
+
/** Deliver to one connection, isolating failures so others still receive the event. */
|
|
981
|
+
private deliver;
|
|
982
|
+
/** Publish once to the bus; pub/sub failures never affect the live emit path. */
|
|
983
|
+
private publish;
|
|
984
|
+
/** Evict a user's oldest connections (FIFO) when over `maxConnectionsPerUser`. */
|
|
985
|
+
private evictBeyondLimit;
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
/**
|
|
989
|
+
* Owns the complete SSE subscribe flow: auth context → authenticate →
|
|
990
|
+
* register (transport handles FIFO eviction) → onConnect → heartbeat → replay → merged stream with teardown.
|
|
991
|
+
*
|
|
992
|
+
* The factory produces a thin `@Controller` shell that delegates every request here,
|
|
993
|
+
* keeping the controller itself free of business logic and independently testable.
|
|
994
|
+
* Lifecycle hooks are invoked best-effort so a throwing hook never disrupts delivery.
|
|
995
|
+
*/
|
|
996
|
+
declare class SseSubscriptionHandler {
|
|
997
|
+
private readonly transport;
|
|
998
|
+
private readonly heartbeat;
|
|
999
|
+
private readonly options;
|
|
1000
|
+
private readonly hooks?;
|
|
1001
|
+
private readonly offlineDelivery?;
|
|
1002
|
+
private readonly logger;
|
|
1003
|
+
constructor(transport: SseTransport, heartbeat: HeartbeatService, options: BymaxRealtimeModuleOptions, hooks?: IConnectionLifecycleHooks | undefined, offlineDelivery?: OfflineQueueDeliveryService | undefined);
|
|
1004
|
+
/**
|
|
1005
|
+
* Handle an incoming SSE connection request end-to-end.
|
|
1006
|
+
*
|
|
1007
|
+
* Sets anti-buffering headers, authenticates the request, captures the offline-gap
|
|
1008
|
+
* before exposing the connection, then returns an Observable whose subscriber callback
|
|
1009
|
+
* wires the downstream listener BEFORE calling `registerConnection` — so a plain
|
|
1010
|
+
* `Subject` suffices and the replay buffer cannot grow unboundedly.
|
|
1011
|
+
*
|
|
1012
|
+
* @param req - The Express request (SSE GET).
|
|
1013
|
+
* @param res - The Express response (passthrough for header mutations and heartbeat writes).
|
|
1014
|
+
* @returns An Observable of `MessageEvent` values for NestJS `@Sse` to stream.
|
|
1015
|
+
* @throws UnauthorizedException when authentication returns null.
|
|
1016
|
+
*/
|
|
1017
|
+
handle(req: Request, res: Response): Promise<Observable<MessageEvent>>;
|
|
1018
|
+
/**
|
|
1019
|
+
* Build the live Observable using a subscribe-before-register pattern.
|
|
1020
|
+
*
|
|
1021
|
+
* The downstream subscriber is wired to the merged pipeline FIRST, so `subject`
|
|
1022
|
+
* already has a listener when `registerConnection` runs. Any `subject.next()` that
|
|
1023
|
+
* occurs during or after registration goes directly to the subscriber — nothing is
|
|
1024
|
+
* buffered or retained, nothing is dropped, and ordering (established → replay →
|
|
1025
|
+
* queue → live) is preserved.
|
|
1026
|
+
*/
|
|
1027
|
+
private buildStream;
|
|
1028
|
+
/**
|
|
1029
|
+
* Wire the merged pipeline to the downstream subscriber with teardown.
|
|
1030
|
+
*
|
|
1031
|
+
* Subscribing first guarantees `subject` has a listener before registration can emit,
|
|
1032
|
+
* so a plain `Subject` suffices and ordering (established → replay → queue → live) holds.
|
|
1033
|
+
*/
|
|
1034
|
+
private subscribePipeline;
|
|
1035
|
+
/**
|
|
1036
|
+
* Register the connection (after the subscriber is wired) and activate it on resolution.
|
|
1037
|
+
*
|
|
1038
|
+
* A registration failure routes to `onError` and errors the stream; a failure that
|
|
1039
|
+
* arrives after teardown is a no-op since `subscriber.error` is ignored once closed.
|
|
1040
|
+
*/
|
|
1041
|
+
private activateConnection;
|
|
1042
|
+
/**
|
|
1043
|
+
* Complete the connection handshake once registration resolves.
|
|
1044
|
+
*
|
|
1045
|
+
* Registration is async and can resolve AFTER the downstream subscriber has already
|
|
1046
|
+
* torn down (client disconnected mid-handshake). When that happens `finalize` has
|
|
1047
|
+
* already stopped the heartbeat and unregistered, so re-firing onConnect or starting
|
|
1048
|
+
* a fresh heartbeat would leak the connection and write after close. Guard on
|
|
1049
|
+
* `subscriber.closed`: if closed, undo the late registration idempotently and return.
|
|
1050
|
+
*/
|
|
1051
|
+
private onRegistered;
|
|
1052
|
+
/**
|
|
1053
|
+
* Invoke a lifecycle hook best-effort — a throwing hook is logged and swallowed
|
|
1054
|
+
* so it never disrupts the connection lifecycle or live event delivery.
|
|
1055
|
+
*
|
|
1056
|
+
* @param invoke - A zero-arg function that calls the hook (handles optionality).
|
|
1057
|
+
*/
|
|
1058
|
+
private fireHook;
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
/**
|
|
1062
|
+
* Build a dynamic NestJS controller bound to `endpoint`.
|
|
1063
|
+
*
|
|
1064
|
+
* NestJS evaluates `@Sse(path)` at class-decoration time, so a fresh class is
|
|
1065
|
+
* generated per module instantiation to keep the path configurable without global
|
|
1066
|
+
* mutable state. The controller is a thin shell: every request is delegated to
|
|
1067
|
+
* `SseSubscriptionHandler.handle`, which owns the full subscribe lifecycle.
|
|
1068
|
+
*/
|
|
1069
|
+
declare function createSseController(endpoint: string): Type<unknown>;
|
|
1070
|
+
|
|
1071
|
+
/**
|
|
1072
|
+
* Default single-instance pub/sub.
|
|
1073
|
+
*
|
|
1074
|
+
* `publish` defers delivery one microtask (`await Promise.resolve()`) before
|
|
1075
|
+
* iterating handlers, matching Redis async-callback semantics. A handler that
|
|
1076
|
+
* throws is caught internally so the remaining handlers still receive the message.
|
|
1077
|
+
* Multi-instance deployments replace this with a Redis-backed `IRealtimePubSub`.
|
|
1078
|
+
*/
|
|
1079
|
+
declare class InMemoryPubSub implements IRealtimePubSub {
|
|
1080
|
+
private readonly handlers;
|
|
1081
|
+
/**
|
|
1082
|
+
* Publish a message to all subscribed handlers.
|
|
1083
|
+
*
|
|
1084
|
+
* Delivery is deferred one microtask so a handler that enqueues further publishes
|
|
1085
|
+
* does not deepen the current call stack. One handler's failure does not block others.
|
|
1086
|
+
*
|
|
1087
|
+
* @param message - The pub/sub message to fan out.
|
|
1088
|
+
*/
|
|
1089
|
+
publish(message: RealtimePubSubMessage): Promise<void>;
|
|
1090
|
+
/**
|
|
1091
|
+
* Subscribe to pub/sub messages.
|
|
1092
|
+
*
|
|
1093
|
+
* @param handler - Called for every published message.
|
|
1094
|
+
* @returns An async unsubscribe function that removes this handler.
|
|
1095
|
+
*/
|
|
1096
|
+
subscribe(handler: (message: RealtimePubSubMessage) => void): Promise<() => Promise<void>>;
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
/**
|
|
1100
|
+
* @fileoverview Cross-instance pub/sub subscriber — re-emits remote messages locally.
|
|
1101
|
+
* @layer infrastructure
|
|
1102
|
+
*/
|
|
1103
|
+
|
|
1104
|
+
/**
|
|
1105
|
+
* Subscribes to the pub/sub bus on startup and dispatches remote messages to
|
|
1106
|
+
* the transport's `*Local` methods, which deliver without re-publishing.
|
|
1107
|
+
*
|
|
1108
|
+
* Messages from this instance (echo) are dropped via the `origin` guard.
|
|
1109
|
+
* Subscribe/unsubscribe failures are logged and swallowed so a Redis hiccup at
|
|
1110
|
+
* startup does not crash the application.
|
|
1111
|
+
*/
|
|
1112
|
+
declare class RealtimePubSubSubscriber implements OnModuleInit, OnApplicationShutdown {
|
|
1113
|
+
private readonly pubsub;
|
|
1114
|
+
private readonly instanceId;
|
|
1115
|
+
private readonly sse;
|
|
1116
|
+
private readonly logger;
|
|
1117
|
+
private unsubscribe;
|
|
1118
|
+
constructor(pubsub: IRealtimePubSub, instanceId: string, sse: SseTransport);
|
|
1119
|
+
onModuleInit(): Promise<void>;
|
|
1120
|
+
onApplicationShutdown(): Promise<void>;
|
|
1121
|
+
private handle;
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
/**
|
|
1125
|
+
* @fileoverview Redis-backed pub/sub for cross-instance SSE fan-out.
|
|
1126
|
+
* @layer infrastructure
|
|
1127
|
+
*/
|
|
1128
|
+
|
|
1129
|
+
/** Options for RedisRealtimePubSub. */
|
|
1130
|
+
interface RedisRealtimePubSubOptions {
|
|
1131
|
+
/** The Redis client used for publishing. A separate subscriber clone is created internally. */
|
|
1132
|
+
readonly client: Redis;
|
|
1133
|
+
/** The Redis pub/sub channel name. Defaults to `bymax:realtime`. */
|
|
1134
|
+
readonly channel?: string;
|
|
1135
|
+
}
|
|
1136
|
+
/**
|
|
1137
|
+
* Redis-backed `IRealtimePubSub` for horizontal scaling.
|
|
1138
|
+
*
|
|
1139
|
+
* Uses two Redis clients: one for `PUBLISH` (the provided client) and one for
|
|
1140
|
+
* `SUBSCRIBE` (a lazily-duplicated clone). The subscriber clone is created on
|
|
1141
|
+
* the first `subscribe()` call and quit on the last `unsubscribe()`.
|
|
1142
|
+
*
|
|
1143
|
+
* Messages are JSON-encoded. Malformed payloads are silently dropped.
|
|
1144
|
+
*
|
|
1145
|
+
* @example
|
|
1146
|
+
* ```ts
|
|
1147
|
+
* const redis = new Redis(process.env.REDIS_URL)
|
|
1148
|
+
* BymaxRealtimeModule.forRoot({
|
|
1149
|
+
* transport: 'sse',
|
|
1150
|
+
* authenticator,
|
|
1151
|
+
* pubsub: new RedisRealtimePubSub({ client: redis }),
|
|
1152
|
+
* })
|
|
1153
|
+
* ```
|
|
1154
|
+
*/
|
|
1155
|
+
declare class RedisRealtimePubSub implements IRealtimePubSub {
|
|
1156
|
+
private readonly pub;
|
|
1157
|
+
private readonly channel;
|
|
1158
|
+
private subInit;
|
|
1159
|
+
private readonly handlers;
|
|
1160
|
+
constructor(options: RedisRealtimePubSubOptions);
|
|
1161
|
+
/** JSON-encodes the message and PUBLISHes it to the configured channel. */
|
|
1162
|
+
publish(message: RealtimePubSubMessage): Promise<void>;
|
|
1163
|
+
/**
|
|
1164
|
+
* Lazily creates the single shared subscribe client on first call; returns an async
|
|
1165
|
+
* unsubscribe that quits the client when the last handler is removed. Concurrent
|
|
1166
|
+
* subscribe calls are idempotent — only one client is ever created. Malformed
|
|
1167
|
+
* payloads are dropped silently.
|
|
1168
|
+
*
|
|
1169
|
+
* If the subscriber client cannot be created (e.g. Redis temporarily unavailable),
|
|
1170
|
+
* the handler registration is rolled back and the cached init promise is cleared so
|
|
1171
|
+
* the next call retries from scratch.
|
|
1172
|
+
*/
|
|
1173
|
+
subscribe(handler: (message: RealtimePubSubMessage) => void): Promise<() => Promise<void>>;
|
|
1174
|
+
/** Lazily create the single shared subscribe client (idempotent under concurrent calls). */
|
|
1175
|
+
private ensureSubscriber;
|
|
1176
|
+
private createSubscriber;
|
|
1177
|
+
private dispatch;
|
|
1178
|
+
}
|
|
1179
|
+
|
|
1180
|
+
/**
|
|
1181
|
+
* @fileoverview Redis sorted-set offline queue for durable per-user event retention.
|
|
1182
|
+
* @layer infrastructure
|
|
1183
|
+
*/
|
|
1184
|
+
|
|
1185
|
+
/** Options for RedisOfflineQueue. */
|
|
1186
|
+
interface RedisOfflineQueueOptions {
|
|
1187
|
+
/** The Redis client to use for all queue operations. */
|
|
1188
|
+
readonly client: Redis;
|
|
1189
|
+
/** Maximum events retained per user (oldest are trimmed). Defaults to 500. */
|
|
1190
|
+
readonly maxPerUser?: number;
|
|
1191
|
+
/** TTL for each user's key in seconds. Defaults to 3600 (1 hour). */
|
|
1192
|
+
readonly ttlSeconds?: number;
|
|
1193
|
+
}
|
|
1194
|
+
/**
|
|
1195
|
+
* Redis sorted-set–backed implementation of `IOfflineQueueStorage`.
|
|
1196
|
+
*
|
|
1197
|
+
* Each user's events are stored in a sorted set keyed `bymax:oq:{userId}`.
|
|
1198
|
+
* All entries share score 0; ordering is purely lexicographic on the member
|
|
1199
|
+
* prefix `${ms_padded}-${counter_padded}|${json}`, which is immune to the
|
|
1200
|
+
* IEEE-754 double precision loss that affects fractional ZSET scores at
|
|
1201
|
+
* epoch-millisecond magnitude. Events are trimmed to `maxPerUser` oldest-first,
|
|
1202
|
+
* and the key expires after `ttlSeconds` of inactivity.
|
|
1203
|
+
*
|
|
1204
|
+
* @example
|
|
1205
|
+
* ```ts
|
|
1206
|
+
* const redis = new Redis(process.env.REDIS_URL)
|
|
1207
|
+
* BymaxRealtimeModule.forRoot({
|
|
1208
|
+
* transport: 'sse',
|
|
1209
|
+
* authenticator,
|
|
1210
|
+
* offlineQueue: new RedisOfflineQueue({ client: redis }),
|
|
1211
|
+
* })
|
|
1212
|
+
* ```
|
|
1213
|
+
*/
|
|
1214
|
+
declare class RedisOfflineQueue implements IOfflineQueueStorage {
|
|
1215
|
+
private readonly client;
|
|
1216
|
+
private readonly maxPerUser;
|
|
1217
|
+
private readonly ttlSeconds;
|
|
1218
|
+
/** Zero-pad width for the epoch-millisecond component of the sort key. */
|
|
1219
|
+
private static readonly MS_PAD;
|
|
1220
|
+
/** Zero-pad width for the intra-millisecond counter component of the sort key. */
|
|
1221
|
+
private static readonly COUNTER_PAD;
|
|
1222
|
+
constructor(options: RedisOfflineQueueOptions);
|
|
1223
|
+
private key;
|
|
1224
|
+
/**
|
|
1225
|
+
* Build the fixed-width lexicographic sort key for an event id.
|
|
1226
|
+
*
|
|
1227
|
+
* Handles two id formats:
|
|
1228
|
+
* - `{ms}-{counter}` from EventIdGenerator: `1717000000000-000001`
|
|
1229
|
+
* - Legacy plain numeric strings: `1700000000000`
|
|
1230
|
+
*/
|
|
1231
|
+
private lexKey;
|
|
1232
|
+
/**
|
|
1233
|
+
* Return the lexicographically next sort key after `id`, used as an
|
|
1234
|
+
* inclusive ZRANGEBYLEX lower bound that excludes the `id` event itself.
|
|
1235
|
+
*/
|
|
1236
|
+
private lexKeyNext;
|
|
1237
|
+
/** Encode an event into a lexicographically sortable ZSET member string. */
|
|
1238
|
+
private encodeMember;
|
|
1239
|
+
append(userId: string, event: OfflineQueuedEvent): Promise<void>;
|
|
1240
|
+
retrieveSince(userId: string, sinceId: string, limit: number): Promise<OfflineQueuedEvent[]>;
|
|
1241
|
+
acknowledge(userId: string, upToId: string): Promise<void>;
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
/**
|
|
1245
|
+
* @fileoverview Canonical room id prefixes for scoping emits and auto-join.
|
|
1246
|
+
* @layer shared
|
|
1247
|
+
*/
|
|
1248
|
+
/**
|
|
1249
|
+
* Canonical room id prefixes — used to scope emits and auto-join connections.
|
|
1250
|
+
*
|
|
1251
|
+
* Convention:
|
|
1252
|
+
* - `user:{userId}` — a single user's connections
|
|
1253
|
+
* - `tenant:{tenantId}` — every connection within a tenant
|
|
1254
|
+
* - `resource:{resourceType}:{id}` — a per-resource room (e.g. invoice, session)
|
|
1255
|
+
*
|
|
1256
|
+
* Anything else is application-defined and free-form. Changing a prefix value is
|
|
1257
|
+
* a breaking change for every connected client and stored room id.
|
|
1258
|
+
*/
|
|
1259
|
+
declare const ROOM_PREFIXES: {
|
|
1260
|
+
readonly USER: "user";
|
|
1261
|
+
readonly TENANT: "tenant";
|
|
1262
|
+
readonly RESOURCE: "resource";
|
|
1263
|
+
};
|
|
1264
|
+
/** Union of canonical room prefix values (`'user' | 'tenant' | 'resource'`). */
|
|
1265
|
+
type RoomPrefix = (typeof ROOM_PREFIXES)[keyof typeof ROOM_PREFIXES];
|
|
1266
|
+
|
|
1267
|
+
/**
|
|
1268
|
+
* @fileoverview Helper that builds canonical room ids from the prefix convention.
|
|
1269
|
+
* @layer utils
|
|
1270
|
+
*/
|
|
1271
|
+
|
|
1272
|
+
/**
|
|
1273
|
+
* Build a canonical room id following the library's prefix convention.
|
|
1274
|
+
*
|
|
1275
|
+
* Validation of the parts (e.g. non-empty ids) is the caller's responsibility —
|
|
1276
|
+
* this helper only joins the prefix and parts with `:`.
|
|
1277
|
+
*
|
|
1278
|
+
* @example
|
|
1279
|
+
* ```ts
|
|
1280
|
+
* composeRoomId('USER', 'u_abc') // → 'user:u_abc'
|
|
1281
|
+
* composeRoomId('TENANT', 't_acme') // → 'tenant:t_acme'
|
|
1282
|
+
* composeRoomId('RESOURCE', 'invoice', 'inv_123') // → 'resource:invoice:inv_123'
|
|
1283
|
+
* ```
|
|
1284
|
+
*/
|
|
1285
|
+
declare function composeRoomId(prefix: keyof typeof ROOM_PREFIXES, ...parts: string[]): string;
|
|
1286
|
+
|
|
1287
|
+
/**
|
|
1288
|
+
* @fileoverview Parser turning a raw HTTP `Cookie` header into a plain object.
|
|
1289
|
+
* @layer utils
|
|
1290
|
+
*/
|
|
1291
|
+
/**
|
|
1292
|
+
* Parse an HTTP `Cookie` header into a plain object.
|
|
1293
|
+
*
|
|
1294
|
+
* Returns an empty object for empty/missing input and ignores malformed pairs
|
|
1295
|
+
* (no `=`, or an empty name). Values are NOT URL-decoded — that is the consumer's
|
|
1296
|
+
* responsibility, since tokens in HttpOnly cookies set by server frameworks are
|
|
1297
|
+
* typically not URL-encoded.
|
|
1298
|
+
*
|
|
1299
|
+
* @example
|
|
1300
|
+
* ```ts
|
|
1301
|
+
* parseCookieHeader('access_token=eyJ...; theme=dark')
|
|
1302
|
+
* // → { access_token: 'eyJ...', theme: 'dark' }
|
|
1303
|
+
* ```
|
|
1304
|
+
*/
|
|
1305
|
+
declare function parseCookieHeader(cookieHeader: string): Record<string, string>;
|
|
1306
|
+
|
|
1307
|
+
/**
|
|
1308
|
+
* @fileoverview Generic realtime event shape shared across transports and the client.
|
|
1309
|
+
* @layer shared
|
|
1310
|
+
*/
|
|
1311
|
+
/**
|
|
1312
|
+
* Generic shape of an event traveling over a realtime transport.
|
|
1313
|
+
*
|
|
1314
|
+
* Consumers typically declare a mapped type describing their own events and layer
|
|
1315
|
+
* it on top of this generic for end-to-end type safety:
|
|
1316
|
+
*
|
|
1317
|
+
* @example
|
|
1318
|
+
* ```ts
|
|
1319
|
+
* interface MyAppEvents {
|
|
1320
|
+
* 'invoice.paid': { id: string; amount: number }
|
|
1321
|
+
* 'webhook.dlq': { webhookId: string; reason: string }
|
|
1322
|
+
* }
|
|
1323
|
+
*
|
|
1324
|
+
* type InvoicePaid = RealtimeEvent<MyAppEvents['invoice.paid']>
|
|
1325
|
+
* ```
|
|
1326
|
+
*/
|
|
1327
|
+
interface RealtimeEvent<TData = unknown> {
|
|
1328
|
+
/** Monotonically increasing event id — used for `Last-Event-ID` replay. */
|
|
1329
|
+
readonly id: string;
|
|
1330
|
+
/** Event name (matches the consumer's mapped-type key). */
|
|
1331
|
+
readonly type: string;
|
|
1332
|
+
/** Free-form payload. */
|
|
1333
|
+
readonly data: TData;
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
/**
|
|
1337
|
+
* @fileoverview Public-facing metadata about a single realtime connection.
|
|
1338
|
+
* @layer shared
|
|
1339
|
+
*/
|
|
1340
|
+
/**
|
|
1341
|
+
* Public-facing metadata about a single realtime connection.
|
|
1342
|
+
*
|
|
1343
|
+
* The full internal record (which, for SSE, also holds the per-connection RxJS
|
|
1344
|
+
* `Subject` and `close$` teardown signal) is kept private to the server runtime —
|
|
1345
|
+
* see `src/server/services/connection-registry.service.ts`. This type exposes only
|
|
1346
|
+
* the fields that are safe to share with diagnostics and the client.
|
|
1347
|
+
*/
|
|
1348
|
+
interface PublicConnectionMeta {
|
|
1349
|
+
readonly connectionId: string;
|
|
1350
|
+
readonly userId: string;
|
|
1351
|
+
readonly tenantId?: string;
|
|
1352
|
+
readonly transport: 'sse' | 'websocket';
|
|
1353
|
+
readonly connectedAt: Date;
|
|
1354
|
+
}
|
|
1355
|
+
|
|
1356
|
+
/**
|
|
1357
|
+
* @fileoverview Event names reserved by the library (the §13 catalog).
|
|
1358
|
+
* @layer shared
|
|
1359
|
+
*/
|
|
1360
|
+
/**
|
|
1361
|
+
* Event names reserved by the library.
|
|
1362
|
+
*
|
|
1363
|
+
* Consumer apps should not reuse these names for application-level events; doing
|
|
1364
|
+
* so will not throw, but causes confusion in logs and client-side listeners.
|
|
1365
|
+
*
|
|
1366
|
+
* Note: the SSE heartbeat is intentionally absent. It is a raw `: keepalive`
|
|
1367
|
+
* comment written directly to the response stream (not a named event and outside
|
|
1368
|
+
* the `Last-Event-ID` id-space), so it is not part of this catalog.
|
|
1369
|
+
*/
|
|
1370
|
+
declare const RESERVED_EVENT_NAMES: {
|
|
1371
|
+
readonly CONNECTION_ESTABLISHED: "connection:established";
|
|
1372
|
+
readonly CONNECTION_REAUTH_FAILED: "connection:reauthentication-failed";
|
|
1373
|
+
readonly CONNECTION_CREDENTIAL_EXPIRING: "connection:credential-expiring";
|
|
1374
|
+
readonly ROOM_JOINED: "room:joined";
|
|
1375
|
+
readonly ROOM_LEFT: "room:left";
|
|
1376
|
+
readonly ERROR: "error";
|
|
1377
|
+
};
|
|
1378
|
+
/** Union of reserved event name values. */
|
|
1379
|
+
type ReservedEventName = (typeof RESERVED_EVENT_NAMES)[keyof typeof RESERVED_EVENT_NAMES];
|
|
1380
|
+
|
|
1381
|
+
/**
|
|
1382
|
+
* @fileoverview Canonical error codes emitted by the library (the §14 catalog).
|
|
1383
|
+
* @layer shared
|
|
1384
|
+
*/
|
|
1385
|
+
/**
|
|
1386
|
+
* Canonical error codes emitted by the library. Map 1-to-1 with
|
|
1387
|
+
* `docs/technical_specification.md` §14.
|
|
1388
|
+
*
|
|
1389
|
+
* `TOO_MANY_CONNECTIONS` signals FIFO eviction: when a user exceeds
|
|
1390
|
+
* `maxConnectionsPerUser`, the OLDEST connection is evicted (closed with this
|
|
1391
|
+
* code) and the new one is admitted — it is never an HTTP 429 rejection.
|
|
1392
|
+
*/
|
|
1393
|
+
declare const REALTIME_ERROR_CODES: {
|
|
1394
|
+
readonly INVALID_OPTIONS: "REALTIME_INVALID_OPTIONS";
|
|
1395
|
+
readonly NO_AUTHENTICATOR: "REALTIME_NO_AUTHENTICATOR";
|
|
1396
|
+
readonly AUTH_FAILED: "REALTIME_AUTH_FAILED";
|
|
1397
|
+
readonly REAUTHENTICATION_FAILED: "REALTIME_REAUTHENTICATION_FAILED";
|
|
1398
|
+
readonly TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS";
|
|
1399
|
+
readonly INVALID_TICKET: "REALTIME_INVALID_TICKET";
|
|
1400
|
+
readonly PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE";
|
|
1401
|
+
readonly PAYLOAD_TOO_LARGE: "REALTIME_PAYLOAD_TOO_LARGE";
|
|
1402
|
+
readonly REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS";
|
|
1403
|
+
};
|
|
1404
|
+
/** Union of canonical error code values. */
|
|
1405
|
+
type RealtimeErrorCode = (typeof REALTIME_ERROR_CODES)[keyof typeof REALTIME_ERROR_CODES];
|
|
1406
|
+
|
|
1407
|
+
export { type AuthenticationResult, BymaxRealtimeModule, type BymaxRealtimeModuleAsyncOptions, type BymaxRealtimeModuleOptions, type BymaxRealtimeModuleOptionsFactory, type ConnectionAuthContext, type ConnectionEventMeta, ConnectionRegistry, type CorsConfig, EventIdGenerator, EventReplayBuffer, HeartbeatService, type IConnectionAuthenticator, type IConnectionLifecycleHooks, type IOfflineQueueStorage, type IPresenceStorage, type IRealtimePubSub, type ITransport, InMemoryPubSub, OfflineQueueDeliveryService, type OfflineQueuedEvent, type PublicConnectionMeta, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, type RealtimeErrorCode, type RealtimeEvent, type RealtimePubSubMessage, RealtimePubSubSubscriber, RealtimeService, type ReauthenticationPolicy, ReauthenticationService, RedisOfflineQueue, type RedisOfflineQueueOptions, RedisRealtimePubSub, type RedisRealtimePubSubOptions, type ReservedEventName, type RoomPrefix, RoomRegistry, type SseOptions, type SseRealtimeModuleAsyncOptions, type SseRealtimeModuleOptions, SseSubscriptionHandler, SseTransport, type TransportMode, type TransportRegistration, type TransportWiring, type WebSocketOptions, type WebSocketRealtimeModuleAsyncOptions, type WebSocketRealtimeModuleOptions, composeForRoot, composeForRootAsync, composeRoomId, createSseController, parseCookieHeader, sseWiring };
|