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