@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
|
@@ -1,336 +1,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { DynamicModule, INestApplicationContext } from '@nestjs/common';
|
|
2
|
+
import { WebSocketRealtimeModuleOptions, WebSocketRealtimeModuleAsyncOptions, ITransport, ConnectionRegistry, RoomRegistry, IConnectionAuthenticator, IConnectionLifecycleHooks, BymaxRealtimeModuleOptions, AuthenticationResult, SseTransport } from '@bymax-one/nest-realtime/internal';
|
|
3
|
+
export { WebSocketRealtimeModuleAsyncOptions, WebSocketRealtimeModuleOptions } from '@bymax-one/nest-realtime/internal';
|
|
2
4
|
import { Server, Socket, ServerOptions } from 'socket.io';
|
|
3
|
-
import { Subject } from 'rxjs';
|
|
4
5
|
import { OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect } from '@nestjs/websockets';
|
|
5
6
|
import { IoAdapter } from '@nestjs/platform-socket.io';
|
|
6
7
|
|
|
7
|
-
/**
|
|
8
|
-
* @fileoverview Config-level transport mode selection.
|
|
9
|
-
* @layer shared
|
|
10
|
-
*/
|
|
11
|
-
/**
|
|
12
|
-
* Transport mode chosen by the consumer at module configuration time.
|
|
13
|
-
*
|
|
14
|
-
* - `sse` — Server-Sent Events only. HTTP-based, server → client push.
|
|
15
|
-
* - `websocket` — Socket.IO only. Full duplex.
|
|
16
|
-
* - `both` — Compose SSE and WebSocket. Useful during migrations or when
|
|
17
|
-
* different product surfaces need different transports.
|
|
18
|
-
*
|
|
19
|
-
* Distinct from `ITransport.kind` (`'sse' | 'websocket'`), which identifies a
|
|
20
|
-
* single concrete transport implementation. See
|
|
21
|
-
* `docs/technical_specification.md` §1.3 for selection criteria.
|
|
22
|
-
*
|
|
23
|
-
* @example
|
|
24
|
-
* ```ts
|
|
25
|
-
* const mode: TransportMode = 'sse'
|
|
26
|
-
* ```
|
|
27
|
-
*/
|
|
28
|
-
type TransportMode = 'sse' | 'websocket' | 'both';
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* @fileoverview The single auth contract the library owns (auth inversion).
|
|
32
|
-
* @layer contracts
|
|
33
|
-
*/
|
|
34
|
-
/**
|
|
35
|
-
* Transport-agnostic context passed to `IConnectionAuthenticator.authenticate`.
|
|
36
|
-
*
|
|
37
|
-
* Built from the HTTP request (SSE) or the Socket.IO handshake (WebSocket).
|
|
38
|
-
* Cookies are parsed; header names are normalized to lowercase.
|
|
39
|
-
*/
|
|
40
|
-
interface ConnectionAuthContext {
|
|
41
|
-
/** Cookies parsed from the request/handshake headers. */
|
|
42
|
-
readonly cookies: Record<string, string>;
|
|
43
|
-
/**
|
|
44
|
-
* Selected headers (lowercase keys). `authorization` is always stripped for SSE:
|
|
45
|
-
* an `EventSource` cannot send custom headers, so it is never a valid SSE auth
|
|
46
|
-
* channel (use a cookie or the ticket pattern). It is available for WebSocket.
|
|
47
|
-
*/
|
|
48
|
-
readonly headers: Record<string, string | undefined>;
|
|
49
|
-
/**
|
|
50
|
-
* Query string parameters — useful for the ticket pattern.
|
|
51
|
-
*
|
|
52
|
-
* Values follow the Node `ParsedUrlQuery` shape: a repeated key (`?a=1&a=2`)
|
|
53
|
-
* arrives as a `string[]`. Authenticators that expect a single value should
|
|
54
|
-
* normalize accordingly; the WebSocket gateway already collapses the `ticket`
|
|
55
|
-
* parameter to a single string before delegating.
|
|
56
|
-
*/
|
|
57
|
-
readonly query: Record<string, string | string[] | undefined>;
|
|
58
|
-
/**
|
|
59
|
-
* Client IP — best-effort. Derived from `X-Forwarded-For` when present, which is
|
|
60
|
-
* spoofable unless set by a trusted proxy; do not use it for security decisions
|
|
61
|
-
* without validating the proxy chain.
|
|
62
|
-
*/
|
|
63
|
-
readonly ip: string;
|
|
64
|
-
/** Raw User-Agent. */
|
|
65
|
-
readonly userAgent: string | undefined;
|
|
66
|
-
/** Transport kind initiating the connection. */
|
|
67
|
-
readonly transport: 'sse' | 'websocket';
|
|
68
|
-
}
|
|
69
|
-
/**
|
|
70
|
-
* Authenticated traits returned by a successful `authenticate()` call. Consumers
|
|
71
|
-
* may carry extra fields through the `metadata` bag.
|
|
72
|
-
*/
|
|
73
|
-
interface AuthenticationResult {
|
|
74
|
-
readonly userId: string;
|
|
75
|
-
readonly tenantId?: string;
|
|
76
|
-
readonly roles?: readonly string[];
|
|
77
|
-
/** Free-form extras for downstream code (e.g. feature flags, plan tier). */
|
|
78
|
-
readonly metadata?: Record<string, unknown>;
|
|
79
|
-
}
|
|
80
|
-
/**
|
|
81
|
-
* Connection authenticator contract — the only auth surface the library owns.
|
|
82
|
-
*
|
|
83
|
-
* Implementations bridge the library to whatever auth strategy the consumer uses
|
|
84
|
-
* (cookie JWT, the ticket pattern, a bearer header in WS, etc.). The library
|
|
85
|
-
* NEVER imports a concrete auth library; see `docs/technical_specification.md`
|
|
86
|
-
* §1.6 ("auth inversion").
|
|
87
|
-
*
|
|
88
|
-
* @example
|
|
89
|
-
* ```ts
|
|
90
|
-
* class CookieAuthenticator implements IConnectionAuthenticator {
|
|
91
|
-
* async authenticate(ctx: ConnectionAuthContext): Promise<AuthenticationResult | null> {
|
|
92
|
-
* const token = ctx.cookies['access_token']
|
|
93
|
-
* if (!token) return null
|
|
94
|
-
* const claims = await verify(token)
|
|
95
|
-
* return { userId: claims.sub, tenantId: claims.tid, roles: claims.roles }
|
|
96
|
-
* }
|
|
97
|
-
* }
|
|
98
|
-
* ```
|
|
99
|
-
*/
|
|
100
|
-
interface IConnectionAuthenticator {
|
|
101
|
-
/**
|
|
102
|
-
* Authenticate a new connection request.
|
|
103
|
-
*
|
|
104
|
-
* @returns the authenticated result, or `null` to reject the connection (the
|
|
105
|
-
* transport replies 401 / disconnects accordingly).
|
|
106
|
-
*/
|
|
107
|
-
authenticate(context: ConnectionAuthContext): Promise<AuthenticationResult | null>;
|
|
108
|
-
/**
|
|
109
|
-
* Optionally re-validate during long sessions. Called periodically based on
|
|
110
|
-
* `reauthenticationPolicy.intervalSeconds`.
|
|
111
|
-
*
|
|
112
|
-
* @returns `true` to keep the connection alive, `false` to disconnect.
|
|
113
|
-
*/
|
|
114
|
-
revalidate?(connectionId: string, originalAuth: AuthenticationResult): Promise<boolean>;
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
/**
|
|
118
|
-
* @fileoverview Optional connection lifecycle hooks the consumer can provide.
|
|
119
|
-
* @layer contracts
|
|
120
|
-
*/
|
|
121
|
-
/** Metadata describing a connection at a lifecycle transition. */
|
|
122
|
-
interface ConnectionEventMeta {
|
|
123
|
-
readonly connectionId: string;
|
|
124
|
-
readonly userId: string;
|
|
125
|
-
readonly tenantId: string | undefined;
|
|
126
|
-
readonly transport: 'sse' | 'websocket';
|
|
127
|
-
readonly ip: string;
|
|
128
|
-
readonly userAgent: string | undefined;
|
|
129
|
-
readonly connectedAt: Date;
|
|
130
|
-
}
|
|
131
|
-
/**
|
|
132
|
-
* Optional lifecycle hooks invoked by the active transport. Every hook may be
|
|
133
|
-
* synchronous or asynchronous; rejected promises are isolated so one failing hook
|
|
134
|
-
* never blocks delivery to other connections.
|
|
135
|
-
*/
|
|
136
|
-
interface IConnectionLifecycleHooks {
|
|
137
|
-
/** Called after authentication succeeds and the connection is registered. */
|
|
138
|
-
onConnect?(meta: ConnectionEventMeta): void | Promise<void>;
|
|
139
|
-
/** Called when the connection closes for any reason. */
|
|
140
|
-
onDisconnect?(meta: ConnectionEventMeta & {
|
|
141
|
-
reason?: string;
|
|
142
|
-
durationMs: number;
|
|
143
|
-
}): void | Promise<void>;
|
|
144
|
-
/** Called on a transport error. */
|
|
145
|
-
onError?(meta: {
|
|
146
|
-
connectionId?: string;
|
|
147
|
-
error: Error;
|
|
148
|
-
transport: 'sse' | 'websocket';
|
|
149
|
-
}): void | Promise<void>;
|
|
150
|
-
/** Called on re-authentication failure, before disconnect. */
|
|
151
|
-
onReauthenticationFailed?(meta: ConnectionEventMeta): void | Promise<void>;
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
/**
|
|
155
|
-
* @fileoverview Cross-instance message bus contract for SSE horizontal scaling.
|
|
156
|
-
* @layer contracts
|
|
157
|
-
*/
|
|
158
|
-
/** A single cross-instance fan-out message. */
|
|
159
|
-
interface RealtimePubSubMessage {
|
|
160
|
-
/** Operation type. */
|
|
161
|
-
readonly op: 'emitToUser' | 'emitToTenant' | 'emitToRoom' | 'broadcast' | 'disconnect';
|
|
162
|
-
/** Operation arguments — the concrete shape is narrowed per `op` at the call site. */
|
|
163
|
-
readonly args: unknown;
|
|
164
|
-
/** Instance id that originated the message (used to avoid echo). */
|
|
165
|
-
readonly origin: string;
|
|
166
|
-
}
|
|
167
|
-
/**
|
|
168
|
-
* Cross-instance message bus.
|
|
169
|
-
*
|
|
170
|
-
* The library provides `InMemoryPubSub` (the single-instance default) and ships a
|
|
171
|
-
* reference Redis-backed implementation (`RedisRealtimePubSub`) for multi-instance
|
|
172
|
-
* deployments. For WebSocket-only deployments, `@socket.io/redis-adapter` is the
|
|
173
|
-
* recommended scaling primitive and `IRealtimePubSub` is not required.
|
|
174
|
-
*/
|
|
175
|
-
interface IRealtimePubSub {
|
|
176
|
-
/** Publish a message to all subscribers (the other instances). */
|
|
177
|
-
publish(message: RealtimePubSubMessage): Promise<void>;
|
|
178
|
-
/** Subscribe to messages. Resolves to an async unsubscribe handle. */
|
|
179
|
-
subscribe(handler: (message: RealtimePubSubMessage) => void): Promise<() => Promise<void>>;
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
/**
|
|
183
|
-
* @fileoverview Optional durable offline-queue storage for Last-Event-ID replay.
|
|
184
|
-
* @layer contracts
|
|
185
|
-
*/
|
|
186
|
-
/** A single event persisted in a user's offline queue. */
|
|
187
|
-
interface OfflineQueuedEvent {
|
|
188
|
-
/** Monotonic id — used as `Last-Event-ID` across reconnections. */
|
|
189
|
-
readonly id: string;
|
|
190
|
-
readonly event: string;
|
|
191
|
-
readonly data: unknown;
|
|
192
|
-
readonly emittedAt: Date;
|
|
193
|
-
}
|
|
194
|
-
/**
|
|
195
|
-
* Optional durable per-user offline queue.
|
|
196
|
-
*
|
|
197
|
-
* Consulted as a fallback when a reconnect's gap exceeds the in-memory replay
|
|
198
|
-
* buffer. Implementations should enforce per-user retention (size + TTL).
|
|
199
|
-
*/
|
|
200
|
-
interface IOfflineQueueStorage {
|
|
201
|
-
/** Append an event to a user's offline queue. */
|
|
202
|
-
append(userId: string, event: OfflineQueuedEvent): Promise<void>;
|
|
203
|
-
/** Retrieve events with `id > sinceId`, up to `limit`. */
|
|
204
|
-
retrieveSince(userId: string, sinceId: string, limit: number): Promise<OfflineQueuedEvent[]>;
|
|
205
|
-
/** Mark events delivered up to `upToId`. Implementations may purge or retain. */
|
|
206
|
-
acknowledge(userId: string, upToId: string): Promise<void>;
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
/**
|
|
210
|
-
* @fileoverview Optional presence-tracking contract ("who is online?").
|
|
211
|
-
* @layer contracts
|
|
212
|
-
*/
|
|
213
|
-
/**
|
|
214
|
-
* Optional presence tracking — answers "who is online?" across instances. When it
|
|
215
|
-
* is not provided, presence-dependent features (e.g. the `usePresence` hook) are
|
|
216
|
-
* disabled.
|
|
217
|
-
*/
|
|
218
|
-
interface IPresenceStorage {
|
|
219
|
-
setOnline(userId: string, connectionId: string, tenantId?: string): Promise<void>;
|
|
220
|
-
setOffline(userId: string, connectionId: string): Promise<void>;
|
|
221
|
-
isOnline(userId: string): Promise<boolean>;
|
|
222
|
-
listOnlineByTenant(tenantId: string): Promise<string[]>;
|
|
223
|
-
countOnline(): Promise<number>;
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
/**
|
|
227
|
-
* @fileoverview Module configuration contracts (sync + async dynamic module).
|
|
228
|
-
* @layer contracts
|
|
229
|
-
*/
|
|
230
|
-
|
|
231
|
-
/** CORS configuration shared by the SSE and WebSocket transports. */
|
|
232
|
-
interface CorsConfig {
|
|
233
|
-
origin?: string | readonly string[] | boolean;
|
|
234
|
-
credentials?: boolean;
|
|
235
|
-
methods?: readonly string[];
|
|
236
|
-
}
|
|
237
|
-
/**
|
|
238
|
-
* SSE-transport-specific options.
|
|
239
|
-
*
|
|
240
|
-
* CORS for the SSE endpoint is intentionally not configured here: the endpoint is a
|
|
241
|
-
* standard HTTP GET, so cross-origin access is controlled at the NestJS application
|
|
242
|
-
* level (`app.enableCors(...)`). `CorsConfig` applies to the WebSocket transport.
|
|
243
|
-
*/
|
|
244
|
-
interface SseOptions {
|
|
245
|
-
endpoint?: string;
|
|
246
|
-
heartbeatMs?: number;
|
|
247
|
-
replayBufferSize?: number;
|
|
248
|
-
maxConnectionsPerUser?: number;
|
|
249
|
-
emitConnectionEvent?: boolean;
|
|
250
|
-
}
|
|
251
|
-
/** WebSocket-transport-specific options. */
|
|
252
|
-
interface WebSocketOptions {
|
|
253
|
-
namespace?: string;
|
|
254
|
-
cors?: CorsConfig;
|
|
255
|
-
maxHttpBufferSize?: number;
|
|
256
|
-
pingIntervalMs?: number;
|
|
257
|
-
pingTimeoutMs?: number;
|
|
258
|
-
maxConnectionsPerUser?: number;
|
|
259
|
-
/**
|
|
260
|
-
* Emit a `connection:established` event to the client immediately after a
|
|
261
|
-
* successful WebSocket handshake. Defaults to `true`.
|
|
262
|
-
*
|
|
263
|
-
* Transport-neutral for WebSocket and independent of `sse.emitConnectionEvent`,
|
|
264
|
-
* so toggling the SSE flag never changes WebSocket behavior.
|
|
265
|
-
*/
|
|
266
|
-
emitConnectionEvent?: boolean;
|
|
267
|
-
redisAdapter?: {
|
|
268
|
-
/**
|
|
269
|
-
* The ioredis client used by `@socket.io/redis-adapter`. Typed `unknown` so
|
|
270
|
-
* the library never imports `ioredis`; the consumer passes a concrete client
|
|
271
|
-
* and the WebSocket transport calls `.duplicate()` for the subscriber.
|
|
272
|
-
*/
|
|
273
|
-
pubClient: unknown;
|
|
274
|
-
};
|
|
275
|
-
}
|
|
276
|
-
/** Periodic re-authentication policy for long-lived connections. */
|
|
277
|
-
interface ReauthenticationPolicy {
|
|
278
|
-
intervalSeconds?: number;
|
|
279
|
-
onFailure?: 'disconnect' | 'event';
|
|
280
|
-
cacheTtlMs?: number;
|
|
281
|
-
}
|
|
282
|
-
/** Synchronous module configuration. */
|
|
283
|
-
interface BymaxRealtimeModuleOptions {
|
|
284
|
-
transport: TransportMode;
|
|
285
|
-
service?: {
|
|
286
|
-
name: string;
|
|
287
|
-
version: string;
|
|
288
|
-
};
|
|
289
|
-
authenticator: IConnectionAuthenticator;
|
|
290
|
-
tenantResolver?: (auth: AuthenticationResult) => string | undefined;
|
|
291
|
-
hooks?: IConnectionLifecycleHooks;
|
|
292
|
-
pubsub?: IRealtimePubSub;
|
|
293
|
-
offlineQueue?: IOfflineQueueStorage;
|
|
294
|
-
presence?: IPresenceStorage;
|
|
295
|
-
sse?: SseOptions;
|
|
296
|
-
websocket?: WebSocketOptions;
|
|
297
|
-
reauthenticationPolicy?: ReauthenticationPolicy;
|
|
298
|
-
}
|
|
299
|
-
/**
|
|
300
|
-
* Synchronous configuration for `BymaxRealtimeWebSocketModule`, which serves
|
|
301
|
-
* `'websocket'` and `'both'`. An SSE-only application wants the root module.
|
|
302
|
-
*/
|
|
303
|
-
type WebSocketRealtimeModuleOptions = Omit<BymaxRealtimeModuleOptions, 'transport'> & {
|
|
304
|
-
transport: 'websocket' | 'both';
|
|
305
|
-
};
|
|
306
|
-
/** A factory that builds module options (async dynamic-module pattern). */
|
|
307
|
-
interface BymaxRealtimeModuleOptionsFactory {
|
|
308
|
-
createRealtimeOptions(): BymaxRealtimeModuleOptions | Promise<BymaxRealtimeModuleOptions>;
|
|
309
|
-
}
|
|
310
|
-
/** Asynchronous module configuration — the standard NestJS dynamic-module pattern. */
|
|
311
|
-
interface BymaxRealtimeModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'> {
|
|
312
|
-
/**
|
|
313
|
-
* The transport this registration wires. Required, not a hint: providers and
|
|
314
|
-
* controllers are fixed at decoration time, long before a factory runs, so the
|
|
315
|
-
* module cannot discover its own transport later. It MUST equal the
|
|
316
|
-
* `transport` the factory resolves; a mismatch fails fast at bootstrap.
|
|
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
|
-
/** Asynchronous configuration for `BymaxRealtimeWebSocketModule`. */
|
|
330
|
-
type WebSocketRealtimeModuleAsyncOptions = Omit<BymaxRealtimeModuleAsyncOptions, 'transport'> & {
|
|
331
|
-
transport: 'websocket' | 'both';
|
|
332
|
-
};
|
|
333
|
-
|
|
334
8
|
/**
|
|
335
9
|
* Realtime module for Socket.IO, and for `'both'` where SSE and WebSocket are
|
|
336
10
|
* composed. Registered globally so a single configuration serves the whole
|
|
@@ -382,140 +56,6 @@ declare class BymaxRealtimeWebSocketModule {
|
|
|
382
56
|
static forRootAsync(asyncOptions: WebSocketRealtimeModuleAsyncOptions): DynamicModule;
|
|
383
57
|
}
|
|
384
58
|
|
|
385
|
-
/**
|
|
386
|
-
* @fileoverview Unified transport abstraction implemented by every transport.
|
|
387
|
-
* @layer contracts
|
|
388
|
-
*/
|
|
389
|
-
/**
|
|
390
|
-
* Unified transport abstraction.
|
|
391
|
-
*
|
|
392
|
-
* The library ships concrete implementations (`SseTransport`, the WebSocket
|
|
393
|
-
* transport, and a composite that fans out to both). Consumers normally interact
|
|
394
|
-
* with `RealtimeService`, which delegates to the active transport; implementing a
|
|
395
|
-
* custom `ITransport` is an advanced use case (e.g. bridging an external bus).
|
|
396
|
-
*
|
|
397
|
-
* @example
|
|
398
|
-
* ```ts
|
|
399
|
-
* class NoopTransport implements ITransport {
|
|
400
|
-
* readonly kind = 'sse' as const
|
|
401
|
-
* async emitToUser() {}
|
|
402
|
-
* async emitToTenant() {}
|
|
403
|
-
* async emitToRoom() {}
|
|
404
|
-
* async broadcast() {}
|
|
405
|
-
* async joinRoom() {}
|
|
406
|
-
* async leaveRoom() {}
|
|
407
|
-
* async disconnect() {}
|
|
408
|
-
* }
|
|
409
|
-
* ```
|
|
410
|
-
*/
|
|
411
|
-
interface ITransport {
|
|
412
|
-
/** Transport identifier. A composite reports its dominant kind (`'sse'`). */
|
|
413
|
-
readonly kind: 'sse' | 'websocket';
|
|
414
|
-
/** Send to every connection of a single user. */
|
|
415
|
-
emitToUser(userId: string, event: string, data: unknown): Promise<void>;
|
|
416
|
-
/** Send to every connection of every user in a tenant. */
|
|
417
|
-
emitToTenant(tenantId: string, event: string, data: unknown): Promise<void>;
|
|
418
|
-
/** Send to every connection in a logical room. */
|
|
419
|
-
emitToRoom(roomId: string, event: string, data: unknown): Promise<void>;
|
|
420
|
-
/** Send to all connected clients. Use sparingly. */
|
|
421
|
-
broadcast(event: string, data: unknown): Promise<void>;
|
|
422
|
-
/** Join a connection to a room (idempotent). */
|
|
423
|
-
joinRoom(connectionId: string, roomId: string): Promise<void>;
|
|
424
|
-
/** Leave a connection from a room (idempotent). */
|
|
425
|
-
leaveRoom(connectionId: string, roomId: string): Promise<void>;
|
|
426
|
-
/** Disconnect a specific connection (e.g. on auth revocation). */
|
|
427
|
-
disconnect(connectionId: string, reason?: string): Promise<void>;
|
|
428
|
-
/** Lifecycle hook — called on NestJS bootstrap. */
|
|
429
|
-
onModuleInit?(): Promise<void>;
|
|
430
|
-
/** Lifecycle hook — called on NestJS shutdown. */
|
|
431
|
-
onApplicationShutdown?(): Promise<void>;
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
/** Transport kind a connection belongs to. */
|
|
435
|
-
type ConnectionTransport = 'sse' | 'websocket';
|
|
436
|
-
/**
|
|
437
|
-
* Internal record kept per active connection.
|
|
438
|
-
*
|
|
439
|
-
* `subject` and `close$` are populated only for SSE connections (the per-connection
|
|
440
|
-
* RxJS stream and its server-initiated teardown signal). WebSocket connections set
|
|
441
|
-
* both to `null` and rely on the Socket.IO server's own emit/disconnect mechanism.
|
|
442
|
-
*/
|
|
443
|
-
interface ConnectionRecord {
|
|
444
|
-
connectionId: string;
|
|
445
|
-
userId: string;
|
|
446
|
-
tenantId: string | undefined;
|
|
447
|
-
transport: ConnectionTransport;
|
|
448
|
-
ip: string;
|
|
449
|
-
userAgent: string | undefined;
|
|
450
|
-
connectedAt: Date;
|
|
451
|
-
/** Per-connection event stream (SSE only); `null` for WebSocket. */
|
|
452
|
-
subject: Subject<MessageEvent> | null;
|
|
453
|
-
/** Server-initiated teardown signal (SSE only); `null` for WebSocket. */
|
|
454
|
-
close$: Subject<void> | null;
|
|
455
|
-
/** Snapshot of the original authentication result — used by the re-auth policy. */
|
|
456
|
-
originalAuth: {
|
|
457
|
-
userId: string;
|
|
458
|
-
tenantId: string | undefined;
|
|
459
|
-
roles: readonly string[] | undefined;
|
|
460
|
-
};
|
|
461
|
-
}
|
|
462
|
-
/**
|
|
463
|
-
* Indexed registry of active connections.
|
|
464
|
-
*
|
|
465
|
-
* Maintains three maps — `byId` (connectionId → record), `byUserId` (userId →
|
|
466
|
-
* Set<connectionId>) and `byTenantId` (tenantId → Set<connectionId>) — kept
|
|
467
|
-
* consistent on every `register`/`unregister`. Operations are amortized O(1);
|
|
468
|
-
* mutation is single-threaded (the Node.js event loop), so no locking is needed.
|
|
469
|
-
*/
|
|
470
|
-
declare class ConnectionRegistry {
|
|
471
|
-
private readonly byId;
|
|
472
|
-
private readonly byUserId;
|
|
473
|
-
private readonly byTenantId;
|
|
474
|
-
/** Register a connection and index it by user and tenant. */
|
|
475
|
-
register(record: ConnectionRecord): void;
|
|
476
|
-
/** Remove a connection from every index. Returns the removed record, if any. */
|
|
477
|
-
unregister(connectionId: string): ConnectionRecord | undefined;
|
|
478
|
-
/** Look up a single connection by id. */
|
|
479
|
-
get(connectionId: string): ConnectionRecord | undefined;
|
|
480
|
-
/** All connections of a user, optionally filtered by transport. */
|
|
481
|
-
byUser(userId: string, transport?: ConnectionTransport): ConnectionRecord[];
|
|
482
|
-
/** All connections of a tenant, optionally filtered by transport. */
|
|
483
|
-
byTenant(tenantId: string, transport?: ConnectionTransport): ConnectionRecord[];
|
|
484
|
-
/** All connections of a given transport. */
|
|
485
|
-
allByTransport(transport: ConnectionTransport): ConnectionRecord[];
|
|
486
|
-
/** Total number of active connections. */
|
|
487
|
-
count(): number;
|
|
488
|
-
/** Number of distinct users currently connected. */
|
|
489
|
-
countUsers(): number;
|
|
490
|
-
private resolve;
|
|
491
|
-
private addToSetMap;
|
|
492
|
-
private removeFromSetMap;
|
|
493
|
-
}
|
|
494
|
-
|
|
495
|
-
/**
|
|
496
|
-
* Indexed registry of room membership.
|
|
497
|
-
*
|
|
498
|
-
* Maintains two maps — `rooms` (roomId → Set<connectionId>) and `connectionRooms`
|
|
499
|
-
* (connectionId → Set<roomId>). The reverse index makes `leaveAll()` on disconnect
|
|
500
|
-
* O(rooms-per-connection) instead of O(total rooms).
|
|
501
|
-
*/
|
|
502
|
-
declare class RoomRegistry {
|
|
503
|
-
private readonly rooms;
|
|
504
|
-
private readonly connectionRooms;
|
|
505
|
-
/** Join a connection to a room (idempotent). */
|
|
506
|
-
join(connectionId: string, roomId: string): void;
|
|
507
|
-
/** Remove a connection from a room (idempotent); prunes empty entries. */
|
|
508
|
-
leave(connectionId: string, roomId: string): void;
|
|
509
|
-
/** Snapshot of a room's members — safe to iterate while membership mutates. */
|
|
510
|
-
members(roomId: string): readonly string[];
|
|
511
|
-
/** Snapshot of the rooms a connection currently belongs to. */
|
|
512
|
-
roomsOf(connectionId: string): readonly string[];
|
|
513
|
-
/** Remove a connection from every room (called on disconnect). */
|
|
514
|
-
leaveAll(connectionId: string): void;
|
|
515
|
-
/** Total number of distinct rooms. */
|
|
516
|
-
countRooms(): number;
|
|
517
|
-
}
|
|
518
|
-
|
|
519
59
|
/**
|
|
520
60
|
* WebSocket transport implementing `ITransport` over a Socket.IO `Server`.
|
|
521
61
|
*
|
|
@@ -777,227 +317,6 @@ declare class RealtimeIoAdapter extends IoAdapter {
|
|
|
777
317
|
private installRedisAdapter;
|
|
778
318
|
}
|
|
779
319
|
|
|
780
|
-
/**
|
|
781
|
-
* Generates monotonically increasing event ids of the form
|
|
782
|
-
* `{epochMillis}-{counter}`, where the counter resets every millisecond.
|
|
783
|
-
*
|
|
784
|
-
* Guarantees:
|
|
785
|
-
* - Lexicographically sortable (the counter is zero-padded to a fixed width), so
|
|
786
|
-
* `Last-Event-ID` replay can string-compare ids.
|
|
787
|
-
* - Monotonic within a single instance even when called repeatedly at the same
|
|
788
|
-
* epoch millisecond.
|
|
789
|
-
*
|
|
790
|
-
* @example
|
|
791
|
-
* ```ts
|
|
792
|
-
* gen.next() // → '1717000000000-000001'
|
|
793
|
-
* gen.next() // → '1717000000000-000002'
|
|
794
|
-
* ```
|
|
795
|
-
*/
|
|
796
|
-
declare class EventIdGenerator {
|
|
797
|
-
private lastMs;
|
|
798
|
-
private counter;
|
|
799
|
-
/** Produce the next monotonic event id. */
|
|
800
|
-
next(): string;
|
|
801
|
-
}
|
|
802
|
-
|
|
803
|
-
/**
|
|
804
|
-
* Per-user ring buffer of recent events for `Last-Event-ID` replay.
|
|
805
|
-
*
|
|
806
|
-
* In-memory by design — it survives only as long as the process. Per-user buffers
|
|
807
|
-
* prevent one user from poisoning another's replay state. For durable replay
|
|
808
|
-
* (instance restart, or a gap larger than the buffer), a consumer can plug
|
|
809
|
-
* `IOfflineQueueStorage` as a fallback.
|
|
810
|
-
*
|
|
811
|
-
* @example
|
|
812
|
-
* ```ts
|
|
813
|
-
* // On reconnect with `Last-Event-ID: <id>`, replay what was missed:
|
|
814
|
-
* const missed = replayBuffer.since(userId, lastEventId)
|
|
815
|
-
* ```
|
|
816
|
-
*/
|
|
817
|
-
declare class EventReplayBuffer {
|
|
818
|
-
private readonly opts;
|
|
819
|
-
private readonly buffers;
|
|
820
|
-
constructor(opts: BymaxRealtimeModuleOptions);
|
|
821
|
-
/** Append an event to a user's ring buffer, evicting the oldest beyond the cap. */
|
|
822
|
-
append(userId: string, event: MessageEvent): void;
|
|
823
|
-
/**
|
|
824
|
-
* Return the events emitted after `lastEventId`.
|
|
825
|
-
*
|
|
826
|
-
* Returns an empty array when the user has no buffer, or when `lastEventId` is
|
|
827
|
-
* not present (a gap — the caller should fall back to `IOfflineQueueStorage`).
|
|
828
|
-
*/
|
|
829
|
-
since(userId: string, lastEventId: string): MessageEvent[];
|
|
830
|
-
/** Number of events currently buffered for a user (diagnostics). */
|
|
831
|
-
size(userId: string): number;
|
|
832
|
-
}
|
|
833
|
-
|
|
834
|
-
/** Minimal response surface the heartbeat needs — a writable text stream. */
|
|
835
|
-
interface HeartbeatWritable {
|
|
836
|
-
write(chunk: string): unknown;
|
|
837
|
-
}
|
|
838
|
-
/**
|
|
839
|
-
* Emits the SSE keepalive on an interval, per connection.
|
|
840
|
-
*
|
|
841
|
-
* The keepalive is a raw `: keepalive\n\n` comment written DIRECTLY to the response
|
|
842
|
-
* stream — not a `MessageEvent`, not a named event, and outside the `Last-Event-ID`
|
|
843
|
-
* id-space — so it never corrupts replay. Comments keep proxies and load balancers
|
|
844
|
-
* from idling out the connection. Timers are tracked per connection and cleared on
|
|
845
|
-
* `stop`.
|
|
846
|
-
*
|
|
847
|
-
* The configured interval must be within `[5_000, 90_000]` ms; values outside this
|
|
848
|
-
* range throw a `REALTIME_INVALID_OPTIONS` error.
|
|
849
|
-
*
|
|
850
|
-
* See `docs/proxies-cheat-sheet.md` for nginx, Cloudflare, and AWS ALB configuration.
|
|
851
|
-
*/
|
|
852
|
-
declare class HeartbeatService {
|
|
853
|
-
private readonly timers;
|
|
854
|
-
/**
|
|
855
|
-
* Start writing keepalives for a connection every `intervalMs`.
|
|
856
|
-
*
|
|
857
|
-
* @param connectionId - Unique connection identifier used to track the timer.
|
|
858
|
-
* @param res - The writable response stream (or any object with a `write` method).
|
|
859
|
-
* @param intervalMs - Keepalive interval in milliseconds; must be within
|
|
860
|
-
* `[5_000, 90_000]`.
|
|
861
|
-
* @throws {Error} When `intervalMs` is outside the valid range.
|
|
862
|
-
*/
|
|
863
|
-
start(connectionId: string, res: HeartbeatWritable, intervalMs: number): void;
|
|
864
|
-
/** Stop and clear the keepalive timer for a connection (idempotent). */
|
|
865
|
-
stop(connectionId: string): void;
|
|
866
|
-
/** Stop every keepalive timer (used on shutdown). */
|
|
867
|
-
stopAll(): void;
|
|
868
|
-
}
|
|
869
|
-
|
|
870
|
-
/** Parameters required to register a freshly authenticated SSE connection. */
|
|
871
|
-
interface RegisterSseConnectionParams {
|
|
872
|
-
connectionId: string;
|
|
873
|
-
auth: AuthenticationResult;
|
|
874
|
-
subject: Subject<MessageEvent>;
|
|
875
|
-
close$: Subject<void>;
|
|
876
|
-
ip: string;
|
|
877
|
-
userAgent: string | undefined;
|
|
878
|
-
}
|
|
879
|
-
/**
|
|
880
|
-
* SSE transport implementation.
|
|
881
|
-
*
|
|
882
|
-
* Each public `emitTo*`/`broadcast` performs local delivery via the matching
|
|
883
|
-
* `*Local` method and then publishes exactly once to `IRealtimePubSub`. Remote
|
|
884
|
-
* messages received from the bus are dispatched by `RealtimePubSubSubscriber`
|
|
885
|
-
* (not this class) to the `*Local` methods only (never re-published), and
|
|
886
|
-
* self-originated messages are filtered there — so a single instance never
|
|
887
|
-
* double-delivers and multiple instances never ping-pong.
|
|
888
|
-
*
|
|
889
|
-
* Teardown of an SSE stream is driven by the per-connection `close$` subject:
|
|
890
|
-
* `disconnectLocal` completes it (which ends the `@Sse` Observable via
|
|
891
|
-
* `takeUntil`) before unregistering. See `docs/technical_specification.md` §6.1.
|
|
892
|
-
*/
|
|
893
|
-
declare class SseTransport implements ITransport {
|
|
894
|
-
private readonly connections;
|
|
895
|
-
private readonly rooms;
|
|
896
|
-
private readonly replayBuffer;
|
|
897
|
-
private readonly idGen;
|
|
898
|
-
private readonly heartbeat;
|
|
899
|
-
private readonly auth;
|
|
900
|
-
private readonly pubsub;
|
|
901
|
-
private readonly hooks;
|
|
902
|
-
private readonly options;
|
|
903
|
-
private readonly instanceId;
|
|
904
|
-
private readonly offlineQueue?;
|
|
905
|
-
readonly kind: "sse";
|
|
906
|
-
private readonly logger;
|
|
907
|
-
constructor(connections: ConnectionRegistry, rooms: RoomRegistry, replayBuffer: EventReplayBuffer, idGen: EventIdGenerator, heartbeat: HeartbeatService, auth: IConnectionAuthenticator, pubsub: IRealtimePubSub, hooks: IConnectionLifecycleHooks, options: BymaxRealtimeModuleOptions, instanceId: string, offlineQueue?: IOfflineQueueStorage | undefined);
|
|
908
|
-
/** Tear down every SSE connection and stop heartbeat on process shutdown. */
|
|
909
|
-
onApplicationShutdown(): Promise<void>;
|
|
910
|
-
/** The resolved heartbeat interval for this transport. */
|
|
911
|
-
get heartbeatMs(): number;
|
|
912
|
-
/** Whether the `connection:established` event should be emitted on connect. */
|
|
913
|
-
get emitConnectionEvent(): boolean;
|
|
914
|
-
/** Authenticate a connection through the consumer-provided authenticator. */
|
|
915
|
-
authenticate(context: ConnectionAuthContext): Promise<AuthenticationResult | null>;
|
|
916
|
-
/**
|
|
917
|
-
* Register an authenticated SSE connection and auto-join its user/tenant rooms.
|
|
918
|
-
*
|
|
919
|
-
* Fires FIFO eviction if the user exceeds `maxConnectionsPerUser`. The `onConnect`
|
|
920
|
-
* lifecycle hook is fired by the subscription handler after this returns, so that the
|
|
921
|
-
* handler can carry a consistent connection record reference.
|
|
922
|
-
*/
|
|
923
|
-
registerConnection(params: RegisterSseConnectionParams): Promise<void>;
|
|
924
|
-
/** Idempotent cleanup for a connection — runs the disconnect hook exactly once. */
|
|
925
|
-
unregisterConnection(connectionId: string, reason?: string): Promise<void>;
|
|
926
|
-
/** Replay the events a user missed after `lastEventId`. */
|
|
927
|
-
getReplayEvents(userId: string, lastEventId: string): MessageEvent[];
|
|
928
|
-
/**
|
|
929
|
-
* All SSE connections for a user — public accessor so external callers can
|
|
930
|
-
* inspect or iterate without reaching into a private registry field.
|
|
931
|
-
*
|
|
932
|
-
* @param userId - The user whose active connections are returned.
|
|
933
|
-
* @returns A snapshot of the user's current SSE `ConnectionRecord` list.
|
|
934
|
-
*/
|
|
935
|
-
connectionsForUser(userId: string): ConnectionRecord[];
|
|
936
|
-
/**
|
|
937
|
-
* Look up a single connection by id.
|
|
938
|
-
*
|
|
939
|
-
* @param connectionId - The unique connection identifier.
|
|
940
|
-
* @returns The `ConnectionRecord`, or `undefined` when not found.
|
|
941
|
-
*/
|
|
942
|
-
getConnection(connectionId: string): ConnectionRecord | undefined;
|
|
943
|
-
emitToUser(userId: string, event: string, data: unknown): Promise<void>;
|
|
944
|
-
emitToTenant(tenantId: string, event: string, data: unknown): Promise<void>;
|
|
945
|
-
emitToRoom(roomId: string, event: string, data: unknown): Promise<void>;
|
|
946
|
-
broadcast(event: string, data: unknown): Promise<void>;
|
|
947
|
-
joinRoom(connectionId: string, roomId: string): Promise<void>;
|
|
948
|
-
leaveRoom(connectionId: string, roomId: string): Promise<void>;
|
|
949
|
-
/** Disconnect a connection locally if owned here, otherwise revoke cross-instance. */
|
|
950
|
-
disconnect(connectionId: string, reason?: string): Promise<void>;
|
|
951
|
-
/**
|
|
952
|
-
* Deliver an event to a user's local SSE connections and update the replay buffer.
|
|
953
|
-
*
|
|
954
|
-
* @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
|
|
955
|
-
* must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
|
|
956
|
-
*/
|
|
957
|
-
emitToUserLocal(userId: string, event: string, data: unknown, id: string): void;
|
|
958
|
-
/**
|
|
959
|
-
* Deliver an event to all local SSE connections for a tenant.
|
|
960
|
-
*
|
|
961
|
-
* @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
|
|
962
|
-
* must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
|
|
963
|
-
* @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
|
|
964
|
-
* buffer or offline queue — only emitToUser populates per-user replay/offline state.
|
|
965
|
-
*/
|
|
966
|
-
emitToTenantLocal(tenantId: string, event: string, data: unknown, id: string): void;
|
|
967
|
-
/**
|
|
968
|
-
* Deliver an event to all local SSE connections that joined the given room.
|
|
969
|
-
*
|
|
970
|
-
* @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
|
|
971
|
-
* must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
|
|
972
|
-
* @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
|
|
973
|
-
* buffer or offline queue — only emitToUser populates per-user replay/offline state.
|
|
974
|
-
*/
|
|
975
|
-
emitToRoomLocal(roomId: string, event: string, data: unknown, id: string): void;
|
|
976
|
-
/**
|
|
977
|
-
* Deliver an event to all local SSE connections.
|
|
978
|
-
*
|
|
979
|
-
* @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
|
|
980
|
-
* must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
|
|
981
|
-
* @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
|
|
982
|
-
* buffer or offline queue — only emitToUser populates per-user replay/offline state.
|
|
983
|
-
*/
|
|
984
|
-
broadcastLocal(event: string, data: unknown, id: string): void;
|
|
985
|
-
/**
|
|
986
|
-
* Tear down a locally-owned SSE stream, then clean up (no re-publish).
|
|
987
|
-
*
|
|
988
|
-
* @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
|
|
989
|
-
* must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
|
|
990
|
-
*/
|
|
991
|
-
disconnectLocal(connectionId: string, reason?: string): Promise<void>;
|
|
992
|
-
private buildMessage;
|
|
993
|
-
/** Deliver to one connection, isolating failures so others still receive the event. */
|
|
994
|
-
private deliver;
|
|
995
|
-
/** Publish once to the bus; pub/sub failures never affect the live emit path. */
|
|
996
|
-
private publish;
|
|
997
|
-
/** Evict a user's oldest connections (FIFO) when over `maxConnectionsPerUser`. */
|
|
998
|
-
private evictBeyondLimit;
|
|
999
|
-
}
|
|
1000
|
-
|
|
1001
320
|
/**
|
|
1002
321
|
* Fan-out transport activated when `transport: 'both'`.
|
|
1003
322
|
*
|
|
@@ -1080,4 +399,4 @@ declare class CompositeTransport implements ITransport {
|
|
|
1080
399
|
private fanOut;
|
|
1081
400
|
}
|
|
1082
401
|
|
|
1083
|
-
export { BymaxRealtimeWebSocketModule, CompositeTransport, RealtimeGateway, RealtimeIoAdapter,
|
|
402
|
+
export { BymaxRealtimeWebSocketModule, CompositeTransport, RealtimeGateway, RealtimeIoAdapter, WebSocketTransport };
|