@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
package/dist/websocket/index.mjs
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
import { Injectable,
|
|
2
|
-
import {
|
|
3
|
-
import { Subject, of, EMPTY, Observable, merge } from 'rxjs';
|
|
4
|
-
import { takeUntil, catchError, finalize } from 'rxjs/operators';
|
|
1
|
+
import { Injectable, Inject, Logger, Global, Module } from '@nestjs/common';
|
|
2
|
+
import { ConnectionRegistry, RoomRegistry, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_HOOKS_TOKEN, REALTIME_OPTIONS_TOKEN, SseTransport, ROOM_PREFIXES, REALTIME_ERROR_CODES, composeForRoot, composeForRootAsync, REALTIME_TRANSPORT_TOKEN, SseSubscriptionHandler, RealtimePubSubSubscriber, createSseController, parseCookieHeader, RESERVED_EVENT_NAMES } from '@bymax-one/nest-realtime/internal';
|
|
5
3
|
import { WebSocketServer, WebSocketGateway } from '@nestjs/websockets';
|
|
6
4
|
import { IoAdapter } from '@nestjs/platform-socket.io';
|
|
7
5
|
|
|
@@ -24,1347 +22,6 @@ var __decorateClass = (decorators, target, key, kind) => {
|
|
|
24
22
|
};
|
|
25
23
|
var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
|
|
26
24
|
var __publicField = (obj, key, value) => __defNormalProp(obj, key + "" , value);
|
|
27
|
-
|
|
28
|
-
// src/shared/constants/error-codes.constants.ts
|
|
29
|
-
var REALTIME_ERROR_CODES = {
|
|
30
|
-
INVALID_OPTIONS: "REALTIME_INVALID_OPTIONS",
|
|
31
|
-
NO_AUTHENTICATOR: "REALTIME_NO_AUTHENTICATOR",
|
|
32
|
-
AUTH_FAILED: "REALTIME_AUTH_FAILED",
|
|
33
|
-
REAUTHENTICATION_FAILED: "REALTIME_REAUTHENTICATION_FAILED",
|
|
34
|
-
TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS"};
|
|
35
|
-
|
|
36
|
-
// src/server/config/default-options.ts
|
|
37
|
-
var DEFAULT_SSE = {
|
|
38
|
-
endpoint: "/realtime/sse",
|
|
39
|
-
heartbeatMs: 3e4,
|
|
40
|
-
replayBufferSize: 100,
|
|
41
|
-
maxConnectionsPerUser: 5,
|
|
42
|
-
emitConnectionEvent: true
|
|
43
|
-
};
|
|
44
|
-
function applyDefaults(options) {
|
|
45
|
-
return Object.freeze({
|
|
46
|
-
...options,
|
|
47
|
-
sse: { ...DEFAULT_SSE, ...options.sse ?? {} }
|
|
48
|
-
});
|
|
49
|
-
}
|
|
50
|
-
var VALID_TRANSPORTS = /* @__PURE__ */ new Set(["sse", "websocket", "both"]);
|
|
51
|
-
function validateOptions(options) {
|
|
52
|
-
if (!options.transport || !VALID_TRANSPORTS.has(options.transport)) {
|
|
53
|
-
throw new Error(
|
|
54
|
-
`[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: options.transport must be one of 'sse' | 'websocket' | 'both' (got: ${String(options.transport)})`
|
|
55
|
-
);
|
|
56
|
-
}
|
|
57
|
-
if (!options.authenticator) {
|
|
58
|
-
throw new Error(
|
|
59
|
-
`[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.NO_AUTHENTICATOR}: options.authenticator is required \u2014 the library never ships a default authenticator`
|
|
60
|
-
);
|
|
61
|
-
}
|
|
62
|
-
if (typeof options.authenticator.authenticate !== "function") {
|
|
63
|
-
throw new Error(
|
|
64
|
-
`[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.NO_AUTHENTICATOR}: options.authenticator must implement IConnectionAuthenticator.authenticate(context)`
|
|
65
|
-
);
|
|
66
|
-
}
|
|
67
|
-
validateSseOptions(options);
|
|
68
|
-
validateReauthPolicy(options);
|
|
69
|
-
}
|
|
70
|
-
function validateReauthPolicy(options) {
|
|
71
|
-
const policy = options.reauthenticationPolicy;
|
|
72
|
-
if (policy?.cacheTtlMs !== void 0 && policy.intervalSeconds !== void 0 && policy.cacheTtlMs > policy.intervalSeconds * 1e3) {
|
|
73
|
-
Logger.warn(
|
|
74
|
-
`[BymaxRealtimeModule] reauthenticationPolicy.cacheTtlMs (${policy.cacheTtlMs} ms) exceeds intervalSeconds*1000 (${policy.intervalSeconds * 1e3} ms): the positive reauth cache outlives the interval, so revalidate is skipped on ticks within the cache window \u2014 reauthentication is effectively weakened`,
|
|
75
|
-
"BymaxRealtimeModule"
|
|
76
|
-
);
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
function validateSseOptions(options) {
|
|
80
|
-
const sse = options.sse;
|
|
81
|
-
if (sse?.heartbeatMs !== void 0 && sse.heartbeatMs <= 0) {
|
|
82
|
-
throw new Error(
|
|
83
|
-
`[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: options.sse.heartbeatMs must be > 0`
|
|
84
|
-
);
|
|
85
|
-
}
|
|
86
|
-
if (sse?.replayBufferSize !== void 0 && sse.replayBufferSize < 0) {
|
|
87
|
-
throw new Error(
|
|
88
|
-
`[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: options.sse.replayBufferSize must be >= 0`
|
|
89
|
-
);
|
|
90
|
-
}
|
|
91
|
-
if (sse?.maxConnectionsPerUser !== void 0 && sse.maxConnectionsPerUser < 0) {
|
|
92
|
-
throw new Error(
|
|
93
|
-
`[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: options.sse.maxConnectionsPerUser must be >= 0 (0 disables the per-user connection cap)`
|
|
94
|
-
);
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
// src/server/constants/injection-tokens.constants.ts
|
|
99
|
-
var REALTIME_OPTIONS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_OPTIONS");
|
|
100
|
-
var REALTIME_TRANSPORT_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_TRANSPORT");
|
|
101
|
-
var REALTIME_AUTHENTICATOR_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_AUTHENTICATOR");
|
|
102
|
-
var REALTIME_PUBSUB_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_PUBSUB");
|
|
103
|
-
var REALTIME_OFFLINE_QUEUE_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_OFFLINE_QUEUE");
|
|
104
|
-
var REALTIME_PRESENCE_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_PRESENCE");
|
|
105
|
-
var REALTIME_HOOKS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_HOOKS");
|
|
106
|
-
var REALTIME_INSTANCE_ID_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_INSTANCE_ID");
|
|
107
|
-
var DEFAULT_HEARTBEAT_MS = 3e4;
|
|
108
|
-
var RETRIEVE_LIMIT = 200;
|
|
109
|
-
var OfflineQueueDeliveryService = class {
|
|
110
|
-
constructor(storage) {
|
|
111
|
-
this.storage = storage;
|
|
112
|
-
}
|
|
113
|
-
storage;
|
|
114
|
-
logger = new Logger(OfflineQueueDeliveryService.name);
|
|
115
|
-
/**
|
|
116
|
-
* Return events for `userId` that arrived after `lastEventId` and are NOT
|
|
117
|
-
* already covered by `ringBufferIds` (already replayed from in-memory buffer).
|
|
118
|
-
*
|
|
119
|
-
* Retrieval does NOT acknowledge: the durable queue is pruned only after the events
|
|
120
|
-
* have been emitted to a live subscriber via {@link acknowledge}. This guarantees
|
|
121
|
-
* at-least-once delivery — events that never reach the client are never lost.
|
|
122
|
-
*
|
|
123
|
-
* @param userId - The reconnecting user.
|
|
124
|
-
* @param lastEventId - The `Last-Event-ID` header value.
|
|
125
|
-
* @param ringBufferIds - Set of event ids already replayed from the ring buffer.
|
|
126
|
-
* @returns Gap events, or an empty array when no offline queue is configured.
|
|
127
|
-
*/
|
|
128
|
-
async retrieve(userId, lastEventId, ringBufferIds) {
|
|
129
|
-
if (!this.storage) return [];
|
|
130
|
-
let events;
|
|
131
|
-
try {
|
|
132
|
-
events = await this.storage.retrieveSince(userId, lastEventId, RETRIEVE_LIMIT);
|
|
133
|
-
} catch (err) {
|
|
134
|
-
this.logger.warn(`Offline queue retrieve failed: ${err.message}`);
|
|
135
|
-
return [];
|
|
136
|
-
}
|
|
137
|
-
if (events.length === RETRIEVE_LIMIT) {
|
|
138
|
-
this.logger.warn(
|
|
139
|
-
`Offline queue retrieve hit the ${RETRIEVE_LIMIT}-event limit for user; older gap events may be dropped.`
|
|
140
|
-
);
|
|
141
|
-
}
|
|
142
|
-
return events.filter((e) => !ringBufferIds.has(e.id));
|
|
143
|
-
}
|
|
144
|
-
/**
|
|
145
|
-
* Acknowledge delivered offline events so the storage backend can prune them.
|
|
146
|
-
*
|
|
147
|
-
* At-least-once contract: call this ONLY after the events have been emitted to a
|
|
148
|
-
* still-open subscriber. Acknowledging before emission would permanently drop events
|
|
149
|
-
* that never reached the client. A failure is swallowed (logged) so a transient
|
|
150
|
-
* storage error never disrupts delivery; the events simply redeliver on reconnect.
|
|
151
|
-
*
|
|
152
|
-
* @param userId - The user whose queue is acknowledged.
|
|
153
|
-
* @param events - The delivered gap events; the last id is the prune watermark.
|
|
154
|
-
*/
|
|
155
|
-
async acknowledge(userId, events) {
|
|
156
|
-
if (!this.storage || events.length === 0) return;
|
|
157
|
-
const lastId = events[events.length - 1].id;
|
|
158
|
-
try {
|
|
159
|
-
await this.storage.acknowledge(userId, lastId);
|
|
160
|
-
} catch (err) {
|
|
161
|
-
this.logger.warn(`Offline queue acknowledge failed: ${err.message}`);
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
};
|
|
165
|
-
OfflineQueueDeliveryService = __decorateClass([
|
|
166
|
-
Injectable(),
|
|
167
|
-
__decorateParam(0, Optional()),
|
|
168
|
-
__decorateParam(0, Inject(REALTIME_OFFLINE_QUEUE_TOKEN))
|
|
169
|
-
], OfflineQueueDeliveryService);
|
|
170
|
-
|
|
171
|
-
// src/shared/constants/reserved-events.constants.ts
|
|
172
|
-
var RESERVED_EVENT_NAMES = {
|
|
173
|
-
CONNECTION_ESTABLISHED: "connection:established",
|
|
174
|
-
CONNECTION_REAUTH_FAILED: "connection:reauthentication-failed",
|
|
175
|
-
CONNECTION_CREDENTIAL_EXPIRING: "connection:credential-expiring",
|
|
176
|
-
ROOM_JOINED: "room:joined",
|
|
177
|
-
ROOM_LEFT: "room:left",
|
|
178
|
-
ERROR: "error"
|
|
179
|
-
};
|
|
180
|
-
|
|
181
|
-
// src/server/utils/parse-cookie-header.ts
|
|
182
|
-
function parseCookieHeader(cookieHeader) {
|
|
183
|
-
const out = /* @__PURE__ */ Object.create(null);
|
|
184
|
-
if (!cookieHeader) return out;
|
|
185
|
-
for (const pair of cookieHeader.split(";")) {
|
|
186
|
-
const idx = pair.indexOf("=");
|
|
187
|
-
if (idx === -1) continue;
|
|
188
|
-
const name = pair.slice(0, idx).trim();
|
|
189
|
-
const value = pair.slice(idx + 1).trim();
|
|
190
|
-
if (name) out[name] = value;
|
|
191
|
-
}
|
|
192
|
-
return out;
|
|
193
|
-
}
|
|
194
|
-
var ConnectionRegistry = class {
|
|
195
|
-
byId = /* @__PURE__ */ new Map();
|
|
196
|
-
byUserId = /* @__PURE__ */ new Map();
|
|
197
|
-
byTenantId = /* @__PURE__ */ new Map();
|
|
198
|
-
/** Register a connection and index it by user and tenant. */
|
|
199
|
-
register(record) {
|
|
200
|
-
this.byId.set(record.connectionId, record);
|
|
201
|
-
this.addToSetMap(this.byUserId, record.userId, record.connectionId);
|
|
202
|
-
if (record.tenantId !== void 0) {
|
|
203
|
-
this.addToSetMap(this.byTenantId, record.tenantId, record.connectionId);
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
/** Remove a connection from every index. Returns the removed record, if any. */
|
|
207
|
-
unregister(connectionId) {
|
|
208
|
-
const record = this.byId.get(connectionId);
|
|
209
|
-
if (!record) return void 0;
|
|
210
|
-
this.byId.delete(connectionId);
|
|
211
|
-
this.removeFromSetMap(this.byUserId, record.userId, connectionId);
|
|
212
|
-
if (record.tenantId !== void 0) {
|
|
213
|
-
this.removeFromSetMap(this.byTenantId, record.tenantId, connectionId);
|
|
214
|
-
}
|
|
215
|
-
return record;
|
|
216
|
-
}
|
|
217
|
-
/** Look up a single connection by id. */
|
|
218
|
-
get(connectionId) {
|
|
219
|
-
return this.byId.get(connectionId);
|
|
220
|
-
}
|
|
221
|
-
/** All connections of a user, optionally filtered by transport. */
|
|
222
|
-
byUser(userId, transport) {
|
|
223
|
-
return this.resolve(this.byUserId.get(userId), transport);
|
|
224
|
-
}
|
|
225
|
-
/** All connections of a tenant, optionally filtered by transport. */
|
|
226
|
-
byTenant(tenantId, transport) {
|
|
227
|
-
return this.resolve(this.byTenantId.get(tenantId), transport);
|
|
228
|
-
}
|
|
229
|
-
/** All connections of a given transport. */
|
|
230
|
-
allByTransport(transport) {
|
|
231
|
-
return Array.from(this.byId.values()).filter((record) => record.transport === transport);
|
|
232
|
-
}
|
|
233
|
-
/** Total number of active connections. */
|
|
234
|
-
count() {
|
|
235
|
-
return this.byId.size;
|
|
236
|
-
}
|
|
237
|
-
/** Number of distinct users currently connected. */
|
|
238
|
-
countUsers() {
|
|
239
|
-
return this.byUserId.size;
|
|
240
|
-
}
|
|
241
|
-
resolve(ids, transport) {
|
|
242
|
-
if (!ids) return [];
|
|
243
|
-
const out = [];
|
|
244
|
-
for (const id of ids) {
|
|
245
|
-
const record = this.byId.get(id);
|
|
246
|
-
if (record && (transport === void 0 || record.transport === transport)) {
|
|
247
|
-
out.push(record);
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
return out;
|
|
251
|
-
}
|
|
252
|
-
addToSetMap(map, key, value) {
|
|
253
|
-
const existing = map.get(key);
|
|
254
|
-
if (existing) existing.add(value);
|
|
255
|
-
else map.set(key, /* @__PURE__ */ new Set([value]));
|
|
256
|
-
}
|
|
257
|
-
removeFromSetMap(map, key, value) {
|
|
258
|
-
const existing = map.get(key);
|
|
259
|
-
if (!existing) return;
|
|
260
|
-
existing.delete(value);
|
|
261
|
-
if (existing.size === 0) map.delete(key);
|
|
262
|
-
}
|
|
263
|
-
};
|
|
264
|
-
ConnectionRegistry = __decorateClass([
|
|
265
|
-
Injectable()
|
|
266
|
-
], ConnectionRegistry);
|
|
267
|
-
var COUNTER_WIDTH = 6;
|
|
268
|
-
var EventIdGenerator = class {
|
|
269
|
-
lastMs = 0;
|
|
270
|
-
counter = 0;
|
|
271
|
-
/** Produce the next monotonic event id. */
|
|
272
|
-
next() {
|
|
273
|
-
const now = Date.now();
|
|
274
|
-
if (now === this.lastMs) {
|
|
275
|
-
this.counter += 1;
|
|
276
|
-
} else {
|
|
277
|
-
this.lastMs = now;
|
|
278
|
-
this.counter = 1;
|
|
279
|
-
}
|
|
280
|
-
return `${now}-${String(this.counter).padStart(COUNTER_WIDTH, "0")}`;
|
|
281
|
-
}
|
|
282
|
-
};
|
|
283
|
-
EventIdGenerator = __decorateClass([
|
|
284
|
-
Injectable()
|
|
285
|
-
], EventIdGenerator);
|
|
286
|
-
var RoomRegistry = class {
|
|
287
|
-
rooms = /* @__PURE__ */ new Map();
|
|
288
|
-
connectionRooms = /* @__PURE__ */ new Map();
|
|
289
|
-
/** Join a connection to a room (idempotent). */
|
|
290
|
-
join(connectionId, roomId) {
|
|
291
|
-
const room = this.rooms.get(roomId) ?? /* @__PURE__ */ new Set();
|
|
292
|
-
room.add(connectionId);
|
|
293
|
-
this.rooms.set(roomId, room);
|
|
294
|
-
const conn = this.connectionRooms.get(connectionId) ?? /* @__PURE__ */ new Set();
|
|
295
|
-
conn.add(roomId);
|
|
296
|
-
this.connectionRooms.set(connectionId, conn);
|
|
297
|
-
}
|
|
298
|
-
/** Remove a connection from a room (idempotent); prunes empty entries. */
|
|
299
|
-
leave(connectionId, roomId) {
|
|
300
|
-
const room = this.rooms.get(roomId);
|
|
301
|
-
if (room) {
|
|
302
|
-
room.delete(connectionId);
|
|
303
|
-
if (room.size === 0) this.rooms.delete(roomId);
|
|
304
|
-
}
|
|
305
|
-
const conn = this.connectionRooms.get(connectionId);
|
|
306
|
-
if (conn) {
|
|
307
|
-
conn.delete(roomId);
|
|
308
|
-
if (conn.size === 0) this.connectionRooms.delete(connectionId);
|
|
309
|
-
}
|
|
310
|
-
}
|
|
311
|
-
/** Snapshot of a room's members — safe to iterate while membership mutates. */
|
|
312
|
-
members(roomId) {
|
|
313
|
-
const set = this.rooms.get(roomId);
|
|
314
|
-
return set ? Array.from(set) : [];
|
|
315
|
-
}
|
|
316
|
-
/** Snapshot of the rooms a connection currently belongs to. */
|
|
317
|
-
roomsOf(connectionId) {
|
|
318
|
-
const set = this.connectionRooms.get(connectionId);
|
|
319
|
-
return set ? Array.from(set) : [];
|
|
320
|
-
}
|
|
321
|
-
/** Remove a connection from every room (called on disconnect). */
|
|
322
|
-
leaveAll(connectionId) {
|
|
323
|
-
const rooms = this.connectionRooms.get(connectionId);
|
|
324
|
-
if (!rooms) return;
|
|
325
|
-
for (const roomId of rooms) {
|
|
326
|
-
const set = this.rooms.get(roomId);
|
|
327
|
-
if (set) {
|
|
328
|
-
set.delete(connectionId);
|
|
329
|
-
if (set.size === 0) this.rooms.delete(roomId);
|
|
330
|
-
}
|
|
331
|
-
}
|
|
332
|
-
this.connectionRooms.delete(connectionId);
|
|
333
|
-
}
|
|
334
|
-
/** Total number of distinct rooms. */
|
|
335
|
-
countRooms() {
|
|
336
|
-
return this.rooms.size;
|
|
337
|
-
}
|
|
338
|
-
};
|
|
339
|
-
RoomRegistry = __decorateClass([
|
|
340
|
-
Injectable()
|
|
341
|
-
], RoomRegistry);
|
|
342
|
-
|
|
343
|
-
// src/shared/constants/room-prefixes.constants.ts
|
|
344
|
-
var ROOM_PREFIXES = {
|
|
345
|
-
USER: "user",
|
|
346
|
-
TENANT: "tenant",
|
|
347
|
-
RESOURCE: "resource"
|
|
348
|
-
};
|
|
349
|
-
|
|
350
|
-
// src/server/utils/compose-room-id.ts
|
|
351
|
-
function composeRoomId(prefix, ...parts) {
|
|
352
|
-
return [ROOM_PREFIXES[prefix], ...parts].join(":");
|
|
353
|
-
}
|
|
354
|
-
var DEFAULT_REPLAY_BUFFER_SIZE = 100;
|
|
355
|
-
var EventReplayBuffer = class {
|
|
356
|
-
constructor(opts) {
|
|
357
|
-
this.opts = opts;
|
|
358
|
-
}
|
|
359
|
-
opts;
|
|
360
|
-
buffers = /* @__PURE__ */ new Map();
|
|
361
|
-
/** Append an event to a user's ring buffer, evicting the oldest beyond the cap. */
|
|
362
|
-
append(userId, event) {
|
|
363
|
-
const buf = this.buffers.get(userId) ?? [];
|
|
364
|
-
buf.push(event);
|
|
365
|
-
const cap = this.opts.sse?.replayBufferSize ?? DEFAULT_REPLAY_BUFFER_SIZE;
|
|
366
|
-
if (buf.length > cap) buf.shift();
|
|
367
|
-
this.buffers.set(userId, buf);
|
|
368
|
-
}
|
|
369
|
-
/**
|
|
370
|
-
* Return the events emitted after `lastEventId`.
|
|
371
|
-
*
|
|
372
|
-
* Returns an empty array when the user has no buffer, or when `lastEventId` is
|
|
373
|
-
* not present (a gap — the caller should fall back to `IOfflineQueueStorage`).
|
|
374
|
-
*/
|
|
375
|
-
since(userId, lastEventId) {
|
|
376
|
-
const buf = this.buffers.get(userId);
|
|
377
|
-
if (!buf) return [];
|
|
378
|
-
const idx = buf.findIndex((event) => event.id === lastEventId);
|
|
379
|
-
if (idx === -1) return [];
|
|
380
|
-
return buf.slice(idx + 1);
|
|
381
|
-
}
|
|
382
|
-
/** Number of events currently buffered for a user (diagnostics). */
|
|
383
|
-
size(userId) {
|
|
384
|
-
return this.buffers.get(userId)?.length ?? 0;
|
|
385
|
-
}
|
|
386
|
-
};
|
|
387
|
-
EventReplayBuffer = __decorateClass([
|
|
388
|
-
Injectable(),
|
|
389
|
-
__decorateParam(0, Inject(REALTIME_OPTIONS_TOKEN))
|
|
390
|
-
], EventReplayBuffer);
|
|
391
|
-
var KEEPALIVE_COMMENT = ": keepalive\n\n";
|
|
392
|
-
var HEARTBEAT_MIN_MS = 5e3;
|
|
393
|
-
var HEARTBEAT_MAX_MS = 9e4;
|
|
394
|
-
var HeartbeatService = class {
|
|
395
|
-
timers = /* @__PURE__ */ new Map();
|
|
396
|
-
/**
|
|
397
|
-
* Start writing keepalives for a connection every `intervalMs`.
|
|
398
|
-
*
|
|
399
|
-
* @param connectionId - Unique connection identifier used to track the timer.
|
|
400
|
-
* @param res - The writable response stream (or any object with a `write` method).
|
|
401
|
-
* @param intervalMs - Keepalive interval in milliseconds; must be within
|
|
402
|
-
* `[5_000, 90_000]`.
|
|
403
|
-
* @throws {Error} When `intervalMs` is outside the valid range.
|
|
404
|
-
*/
|
|
405
|
-
start(connectionId, res, intervalMs) {
|
|
406
|
-
if (intervalMs < HEARTBEAT_MIN_MS || intervalMs > HEARTBEAT_MAX_MS) {
|
|
407
|
-
throw new Error(
|
|
408
|
-
`${REALTIME_ERROR_CODES.INVALID_OPTIONS}: heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms (got ${intervalMs})`
|
|
409
|
-
);
|
|
410
|
-
}
|
|
411
|
-
this.stop(connectionId);
|
|
412
|
-
const timer = setInterval(() => {
|
|
413
|
-
try {
|
|
414
|
-
res.write(KEEPALIVE_COMMENT);
|
|
415
|
-
} catch {
|
|
416
|
-
this.stop(connectionId);
|
|
417
|
-
}
|
|
418
|
-
}, intervalMs);
|
|
419
|
-
timer.unref();
|
|
420
|
-
this.timers.set(connectionId, timer);
|
|
421
|
-
}
|
|
422
|
-
/** Stop and clear the keepalive timer for a connection (idempotent). */
|
|
423
|
-
stop(connectionId) {
|
|
424
|
-
const timer = this.timers.get(connectionId);
|
|
425
|
-
if (timer) {
|
|
426
|
-
clearInterval(timer);
|
|
427
|
-
this.timers.delete(connectionId);
|
|
428
|
-
}
|
|
429
|
-
}
|
|
430
|
-
/** Stop every keepalive timer (used on shutdown). */
|
|
431
|
-
stopAll() {
|
|
432
|
-
for (const timer of this.timers.values()) clearInterval(timer);
|
|
433
|
-
this.timers.clear();
|
|
434
|
-
}
|
|
435
|
-
};
|
|
436
|
-
HeartbeatService = __decorateClass([
|
|
437
|
-
Injectable()
|
|
438
|
-
], HeartbeatService);
|
|
439
|
-
|
|
440
|
-
// src/server/transports/sse/sse.transport.ts
|
|
441
|
-
var SseTransport = class {
|
|
442
|
-
constructor(connections, rooms, replayBuffer, idGen, heartbeat, auth, pubsub, hooks, options, instanceId, offlineQueue) {
|
|
443
|
-
this.connections = connections;
|
|
444
|
-
this.rooms = rooms;
|
|
445
|
-
this.replayBuffer = replayBuffer;
|
|
446
|
-
this.idGen = idGen;
|
|
447
|
-
this.heartbeat = heartbeat;
|
|
448
|
-
this.auth = auth;
|
|
449
|
-
this.pubsub = pubsub;
|
|
450
|
-
this.hooks = hooks;
|
|
451
|
-
this.options = options;
|
|
452
|
-
this.instanceId = instanceId;
|
|
453
|
-
this.offlineQueue = offlineQueue;
|
|
454
|
-
}
|
|
455
|
-
connections;
|
|
456
|
-
rooms;
|
|
457
|
-
replayBuffer;
|
|
458
|
-
idGen;
|
|
459
|
-
heartbeat;
|
|
460
|
-
auth;
|
|
461
|
-
pubsub;
|
|
462
|
-
hooks;
|
|
463
|
-
options;
|
|
464
|
-
instanceId;
|
|
465
|
-
offlineQueue;
|
|
466
|
-
kind = "sse";
|
|
467
|
-
logger = new Logger(SseTransport.name);
|
|
468
|
-
/** Tear down every SSE connection and stop heartbeat on process shutdown. */
|
|
469
|
-
async onApplicationShutdown() {
|
|
470
|
-
this.heartbeat.stopAll();
|
|
471
|
-
for (const conn of this.connections.allByTransport("sse")) {
|
|
472
|
-
await this.disconnectLocal(conn.connectionId);
|
|
473
|
-
}
|
|
474
|
-
}
|
|
475
|
-
/** The resolved heartbeat interval for this transport. */
|
|
476
|
-
get heartbeatMs() {
|
|
477
|
-
return this.options.sse?.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
|
|
478
|
-
}
|
|
479
|
-
/** Whether the `connection:established` event should be emitted on connect. */
|
|
480
|
-
get emitConnectionEvent() {
|
|
481
|
-
return this.options.sse?.emitConnectionEvent !== false;
|
|
482
|
-
}
|
|
483
|
-
/** Authenticate a connection through the consumer-provided authenticator. */
|
|
484
|
-
authenticate(context) {
|
|
485
|
-
return this.auth.authenticate(context);
|
|
486
|
-
}
|
|
487
|
-
/**
|
|
488
|
-
* Register an authenticated SSE connection and auto-join its user/tenant rooms.
|
|
489
|
-
*
|
|
490
|
-
* Fires FIFO eviction if the user exceeds `maxConnectionsPerUser`. The `onConnect`
|
|
491
|
-
* lifecycle hook is fired by the subscription handler after this returns, so that the
|
|
492
|
-
* handler can carry a consistent connection record reference.
|
|
493
|
-
*/
|
|
494
|
-
async registerConnection(params) {
|
|
495
|
-
const record = {
|
|
496
|
-
connectionId: params.connectionId,
|
|
497
|
-
userId: params.auth.userId,
|
|
498
|
-
tenantId: params.auth.tenantId,
|
|
499
|
-
transport: "sse",
|
|
500
|
-
ip: params.ip,
|
|
501
|
-
userAgent: params.userAgent,
|
|
502
|
-
connectedAt: /* @__PURE__ */ new Date(),
|
|
503
|
-
subject: params.subject,
|
|
504
|
-
close$: params.close$,
|
|
505
|
-
originalAuth: {
|
|
506
|
-
userId: params.auth.userId,
|
|
507
|
-
tenantId: params.auth.tenantId,
|
|
508
|
-
roles: params.auth.roles
|
|
509
|
-
}
|
|
510
|
-
};
|
|
511
|
-
this.connections.register(record);
|
|
512
|
-
this.rooms.join(params.connectionId, composeRoomId("USER", params.auth.userId));
|
|
513
|
-
if (params.auth.tenantId !== void 0) {
|
|
514
|
-
this.rooms.join(params.connectionId, composeRoomId("TENANT", params.auth.tenantId));
|
|
515
|
-
}
|
|
516
|
-
await this.evictBeyondLimit(params.auth.userId);
|
|
517
|
-
}
|
|
518
|
-
/** Idempotent cleanup for a connection — runs the disconnect hook exactly once. */
|
|
519
|
-
async unregisterConnection(connectionId, reason) {
|
|
520
|
-
const record = this.connections.unregister(connectionId);
|
|
521
|
-
if (!record) return;
|
|
522
|
-
this.rooms.leaveAll(connectionId);
|
|
523
|
-
this.heartbeat.stop(connectionId);
|
|
524
|
-
try {
|
|
525
|
-
await this.hooks.onDisconnect?.({
|
|
526
|
-
connectionId: record.connectionId,
|
|
527
|
-
userId: record.userId,
|
|
528
|
-
tenantId: record.tenantId,
|
|
529
|
-
transport: "sse",
|
|
530
|
-
ip: record.ip,
|
|
531
|
-
userAgent: record.userAgent,
|
|
532
|
-
connectedAt: record.connectedAt,
|
|
533
|
-
durationMs: Date.now() - record.connectedAt.getTime(),
|
|
534
|
-
...reason !== void 0 ? { reason } : {}
|
|
535
|
-
});
|
|
536
|
-
} catch (error) {
|
|
537
|
-
this.logger.error(`onDisconnect hook failed: ${error.message}`);
|
|
538
|
-
}
|
|
539
|
-
}
|
|
540
|
-
/** Replay the events a user missed after `lastEventId`. */
|
|
541
|
-
getReplayEvents(userId, lastEventId) {
|
|
542
|
-
return this.replayBuffer.since(userId, lastEventId);
|
|
543
|
-
}
|
|
544
|
-
/**
|
|
545
|
-
* All SSE connections for a user — public accessor so external callers can
|
|
546
|
-
* inspect or iterate without reaching into a private registry field.
|
|
547
|
-
*
|
|
548
|
-
* @param userId - The user whose active connections are returned.
|
|
549
|
-
* @returns A snapshot of the user's current SSE `ConnectionRecord` list.
|
|
550
|
-
*/
|
|
551
|
-
connectionsForUser(userId) {
|
|
552
|
-
return this.connections.byUser(userId, "sse");
|
|
553
|
-
}
|
|
554
|
-
/**
|
|
555
|
-
* Look up a single connection by id.
|
|
556
|
-
*
|
|
557
|
-
* @param connectionId - The unique connection identifier.
|
|
558
|
-
* @returns The `ConnectionRecord`, or `undefined` when not found.
|
|
559
|
-
*/
|
|
560
|
-
getConnection(connectionId) {
|
|
561
|
-
return this.connections.get(connectionId);
|
|
562
|
-
}
|
|
563
|
-
async emitToUser(userId, event, data) {
|
|
564
|
-
const id = this.idGen.next();
|
|
565
|
-
this.emitToUserLocal(userId, event, data, id);
|
|
566
|
-
if (this.offlineQueue && this.connections.byUser(userId, "sse").length === 0) {
|
|
567
|
-
void this.offlineQueue.append(userId, { id, event, data, emittedAt: /* @__PURE__ */ new Date() }).catch(
|
|
568
|
-
(error) => this.logger.warn(`Offline queue append failed: ${error.message}`)
|
|
569
|
-
);
|
|
570
|
-
}
|
|
571
|
-
await this.publish({ op: "emitToUser", args: { userId, event, data, id } });
|
|
572
|
-
}
|
|
573
|
-
async emitToTenant(tenantId, event, data) {
|
|
574
|
-
const id = this.idGen.next();
|
|
575
|
-
this.emitToTenantLocal(tenantId, event, data, id);
|
|
576
|
-
await this.publish({ op: "emitToTenant", args: { tenantId, event, data, id } });
|
|
577
|
-
}
|
|
578
|
-
async emitToRoom(roomId, event, data) {
|
|
579
|
-
const id = this.idGen.next();
|
|
580
|
-
this.emitToRoomLocal(roomId, event, data, id);
|
|
581
|
-
await this.publish({ op: "emitToRoom", args: { roomId, event, data, id } });
|
|
582
|
-
}
|
|
583
|
-
async broadcast(event, data) {
|
|
584
|
-
const id = this.idGen.next();
|
|
585
|
-
this.broadcastLocal(event, data, id);
|
|
586
|
-
await this.publish({ op: "broadcast", args: { event, data, id } });
|
|
587
|
-
}
|
|
588
|
-
async joinRoom(connectionId, roomId) {
|
|
589
|
-
this.rooms.join(connectionId, roomId);
|
|
590
|
-
}
|
|
591
|
-
async leaveRoom(connectionId, roomId) {
|
|
592
|
-
this.rooms.leave(connectionId, roomId);
|
|
593
|
-
}
|
|
594
|
-
/** Disconnect a connection locally if owned here, otherwise revoke cross-instance. */
|
|
595
|
-
async disconnect(connectionId, reason) {
|
|
596
|
-
const record = this.connections.get(connectionId);
|
|
597
|
-
if (record && record.transport === "sse") {
|
|
598
|
-
await this.disconnectLocal(connectionId, reason);
|
|
599
|
-
return;
|
|
600
|
-
}
|
|
601
|
-
await this.publish({ op: "disconnect", args: { connectionId, reason } });
|
|
602
|
-
}
|
|
603
|
-
/**
|
|
604
|
-
* Deliver an event to a user's local SSE connections and update the replay buffer.
|
|
605
|
-
*
|
|
606
|
-
* @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
|
|
607
|
-
* must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
|
|
608
|
-
*/
|
|
609
|
-
emitToUserLocal(userId, event, data, id) {
|
|
610
|
-
const message = this.buildMessage(id, event, data);
|
|
611
|
-
this.replayBuffer.append(userId, message);
|
|
612
|
-
for (const conn of this.connections.byUser(userId, "sse")) this.deliver(conn, message);
|
|
613
|
-
}
|
|
614
|
-
/**
|
|
615
|
-
* Deliver an event to all local SSE connections for a tenant.
|
|
616
|
-
*
|
|
617
|
-
* @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
|
|
618
|
-
* must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
|
|
619
|
-
* @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
|
|
620
|
-
* buffer or offline queue — only emitToUser populates per-user replay/offline state.
|
|
621
|
-
*/
|
|
622
|
-
emitToTenantLocal(tenantId, event, data, id) {
|
|
623
|
-
const message = this.buildMessage(id, event, data);
|
|
624
|
-
for (const conn of this.connections.byTenant(tenantId, "sse")) this.deliver(conn, message);
|
|
625
|
-
}
|
|
626
|
-
/**
|
|
627
|
-
* Deliver an event to all local SSE connections that joined the given room.
|
|
628
|
-
*
|
|
629
|
-
* @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
|
|
630
|
-
* must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
|
|
631
|
-
* @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
|
|
632
|
-
* buffer or offline queue — only emitToUser populates per-user replay/offline state.
|
|
633
|
-
*/
|
|
634
|
-
emitToRoomLocal(roomId, event, data, id) {
|
|
635
|
-
const message = this.buildMessage(id, event, data);
|
|
636
|
-
for (const connectionId of this.rooms.members(roomId)) {
|
|
637
|
-
const conn = this.connections.get(connectionId);
|
|
638
|
-
if (conn && conn.transport === "sse") this.deliver(conn, message);
|
|
639
|
-
}
|
|
640
|
-
}
|
|
641
|
-
/**
|
|
642
|
-
* Deliver an event to all local SSE connections.
|
|
643
|
-
*
|
|
644
|
-
* @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
|
|
645
|
-
* must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
|
|
646
|
-
* @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
|
|
647
|
-
* buffer or offline queue — only emitToUser populates per-user replay/offline state.
|
|
648
|
-
*/
|
|
649
|
-
broadcastLocal(event, data, id) {
|
|
650
|
-
const message = this.buildMessage(id, event, data);
|
|
651
|
-
for (const conn of this.connections.allByTransport("sse")) this.deliver(conn, message);
|
|
652
|
-
}
|
|
653
|
-
/**
|
|
654
|
-
* Tear down a locally-owned SSE stream, then clean up (no re-publish).
|
|
655
|
-
*
|
|
656
|
-
* @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
|
|
657
|
-
* must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
|
|
658
|
-
*/
|
|
659
|
-
async disconnectLocal(connectionId, reason) {
|
|
660
|
-
const record = this.connections.get(connectionId);
|
|
661
|
-
if (!record || record.transport !== "sse") return;
|
|
662
|
-
await this.unregisterConnection(connectionId, reason);
|
|
663
|
-
record.close$?.next();
|
|
664
|
-
record.close$?.complete();
|
|
665
|
-
}
|
|
666
|
-
buildMessage(id, event, data) {
|
|
667
|
-
return { id, type: event, data };
|
|
668
|
-
}
|
|
669
|
-
/** Deliver to one connection, isolating failures so others still receive the event. */
|
|
670
|
-
deliver(conn, message) {
|
|
671
|
-
try {
|
|
672
|
-
conn.subject?.next(message);
|
|
673
|
-
} catch (error) {
|
|
674
|
-
this.logger.warn(`SSE delivery failed for ${conn.connectionId}: ${error.message}`);
|
|
675
|
-
}
|
|
676
|
-
}
|
|
677
|
-
/** Publish once to the bus; pub/sub failures never affect the live emit path. */
|
|
678
|
-
async publish(message) {
|
|
679
|
-
try {
|
|
680
|
-
await this.pubsub.publish({ ...message, origin: this.instanceId });
|
|
681
|
-
} catch (error) {
|
|
682
|
-
this.logger.warn(`pubsub.publish failed: ${error.message}`);
|
|
683
|
-
}
|
|
684
|
-
}
|
|
685
|
-
/** Evict a user's oldest connections (FIFO) when over `maxConnectionsPerUser`. */
|
|
686
|
-
async evictBeyondLimit(userId) {
|
|
687
|
-
const max = this.options.sse?.maxConnectionsPerUser;
|
|
688
|
-
if (max === void 0 || max <= 0) return;
|
|
689
|
-
let userConnections = this.connections.byUser(userId, "sse");
|
|
690
|
-
while (userConnections.length > max) {
|
|
691
|
-
const oldest = userConnections.reduce((a, b) => a.connectedAt <= b.connectedAt ? a : b);
|
|
692
|
-
await this.disconnectLocal(oldest.connectionId, REALTIME_ERROR_CODES.TOO_MANY_CONNECTIONS);
|
|
693
|
-
userConnections = this.connections.byUser(userId, "sse");
|
|
694
|
-
}
|
|
695
|
-
}
|
|
696
|
-
};
|
|
697
|
-
SseTransport = __decorateClass([
|
|
698
|
-
Injectable(),
|
|
699
|
-
__decorateParam(0, Inject(ConnectionRegistry)),
|
|
700
|
-
__decorateParam(1, Inject(RoomRegistry)),
|
|
701
|
-
__decorateParam(2, Inject(EventReplayBuffer)),
|
|
702
|
-
__decorateParam(3, Inject(EventIdGenerator)),
|
|
703
|
-
__decorateParam(4, Inject(HeartbeatService)),
|
|
704
|
-
__decorateParam(5, Inject(REALTIME_AUTHENTICATOR_TOKEN)),
|
|
705
|
-
__decorateParam(6, Inject(REALTIME_PUBSUB_TOKEN)),
|
|
706
|
-
__decorateParam(7, Inject(REALTIME_HOOKS_TOKEN)),
|
|
707
|
-
__decorateParam(8, Inject(REALTIME_OPTIONS_TOKEN)),
|
|
708
|
-
__decorateParam(9, Inject(REALTIME_INSTANCE_ID_TOKEN)),
|
|
709
|
-
__decorateParam(10, Optional()),
|
|
710
|
-
__decorateParam(10, Inject(REALTIME_OFFLINE_QUEUE_TOKEN))
|
|
711
|
-
], SseTransport);
|
|
712
|
-
|
|
713
|
-
// src/server/transports/sse/sse-subscription.handler.ts
|
|
714
|
-
function singleHeader(value) {
|
|
715
|
-
return typeof value === "string" ? value : void 0;
|
|
716
|
-
}
|
|
717
|
-
function resolveIp(req) {
|
|
718
|
-
const forwarded = req.headers["x-forwarded-for"];
|
|
719
|
-
const candidate = (typeof forwarded === "string" ? forwarded.split(",")[0] : void 0) ?? "";
|
|
720
|
-
return candidate.trim() || req.ip || "unknown";
|
|
721
|
-
}
|
|
722
|
-
function normalizeHeaders(headers) {
|
|
723
|
-
const out = /* @__PURE__ */ Object.create(null);
|
|
724
|
-
for (const [key, value] of Object.entries(headers)) {
|
|
725
|
-
out[key.toLowerCase()] = Array.isArray(value) ? value.join(",") : value;
|
|
726
|
-
}
|
|
727
|
-
return out;
|
|
728
|
-
}
|
|
729
|
-
function sanitizeQuery(query) {
|
|
730
|
-
const out = /* @__PURE__ */ Object.create(null);
|
|
731
|
-
for (const [key, value] of Object.entries(query)) {
|
|
732
|
-
out[key] = typeof value === "string" ? value : void 0;
|
|
733
|
-
}
|
|
734
|
-
return out;
|
|
735
|
-
}
|
|
736
|
-
function buildAuthContext(req) {
|
|
737
|
-
const headers = normalizeHeaders(req.headers);
|
|
738
|
-
delete headers["authorization"];
|
|
739
|
-
return {
|
|
740
|
-
cookies: parseCookieHeader(singleHeader(req.headers["cookie"]) ?? ""),
|
|
741
|
-
headers,
|
|
742
|
-
query: sanitizeQuery(req.query),
|
|
743
|
-
ip: resolveIp(req),
|
|
744
|
-
userAgent: singleHeader(req.headers["user-agent"]),
|
|
745
|
-
transport: "sse"
|
|
746
|
-
};
|
|
747
|
-
}
|
|
748
|
-
function buildEstablishedEvent(connectionId, auth) {
|
|
749
|
-
return {
|
|
750
|
-
type: RESERVED_EVENT_NAMES.CONNECTION_ESTABLISHED,
|
|
751
|
-
data: {
|
|
752
|
-
connectionId,
|
|
753
|
-
traits: { userId: auth.userId, tenantId: auth.tenantId, roles: auth.roles }
|
|
754
|
-
}
|
|
755
|
-
};
|
|
756
|
-
}
|
|
757
|
-
function toMessageEvent(event) {
|
|
758
|
-
return { id: event.id, type: event.event, data: event.data };
|
|
759
|
-
}
|
|
760
|
-
function buildMeta(record) {
|
|
761
|
-
return {
|
|
762
|
-
connectionId: record.connectionId,
|
|
763
|
-
userId: record.userId,
|
|
764
|
-
tenantId: record.tenantId,
|
|
765
|
-
transport: "sse",
|
|
766
|
-
ip: record.ip,
|
|
767
|
-
userAgent: record.userAgent,
|
|
768
|
-
connectedAt: record.connectedAt
|
|
769
|
-
};
|
|
770
|
-
}
|
|
771
|
-
var SseSubscriptionHandler = class {
|
|
772
|
-
constructor(transport, heartbeat, options, hooks, offlineDelivery) {
|
|
773
|
-
this.transport = transport;
|
|
774
|
-
this.heartbeat = heartbeat;
|
|
775
|
-
this.options = options;
|
|
776
|
-
this.hooks = hooks;
|
|
777
|
-
this.offlineDelivery = offlineDelivery;
|
|
778
|
-
}
|
|
779
|
-
transport;
|
|
780
|
-
heartbeat;
|
|
781
|
-
options;
|
|
782
|
-
hooks;
|
|
783
|
-
offlineDelivery;
|
|
784
|
-
logger = new Logger(SseSubscriptionHandler.name);
|
|
785
|
-
/**
|
|
786
|
-
* Handle an incoming SSE connection request end-to-end.
|
|
787
|
-
*
|
|
788
|
-
* Sets anti-buffering headers, authenticates the request, captures the offline-gap
|
|
789
|
-
* before exposing the connection, then returns an Observable whose subscriber callback
|
|
790
|
-
* wires the downstream listener BEFORE calling `registerConnection` — so a plain
|
|
791
|
-
* `Subject` suffices and the replay buffer cannot grow unboundedly.
|
|
792
|
-
*
|
|
793
|
-
* @param req - The Express request (SSE GET).
|
|
794
|
-
* @param res - The Express response (passthrough for header mutations and heartbeat writes).
|
|
795
|
-
* @returns An Observable of `MessageEvent` values for NestJS `@Sse` to stream.
|
|
796
|
-
* @throws UnauthorizedException when authentication returns null.
|
|
797
|
-
*/
|
|
798
|
-
async handle(req, res) {
|
|
799
|
-
res.setHeader("Cache-Control", "no-cache, no-transform");
|
|
800
|
-
res.setHeader("X-Accel-Buffering", "no");
|
|
801
|
-
const context = buildAuthContext(req);
|
|
802
|
-
const auth = await this.transport.authenticate(context);
|
|
803
|
-
if (!auth) throw new UnauthorizedException(REALTIME_ERROR_CODES.AUTH_FAILED);
|
|
804
|
-
const resolvedTenantId = this.options.tenantResolver?.(auth) ?? auth.tenantId;
|
|
805
|
-
const resolvedAuth = resolvedTenantId !== void 0 ? { ...auth, tenantId: resolvedTenantId } : auth;
|
|
806
|
-
const connectionId = randomUUID();
|
|
807
|
-
const subject = new Subject();
|
|
808
|
-
const close$ = new Subject();
|
|
809
|
-
const lastEventId = singleHeader(req.headers["last-event-id"]);
|
|
810
|
-
const replayEvents = lastEventId ? this.transport.getReplayEvents(resolvedAuth.userId, lastEventId) : [];
|
|
811
|
-
const replay$ = replayEvents.length > 0 ? of(...replayEvents) : EMPTY;
|
|
812
|
-
const ringBufferIds = new Set(replayEvents.map((e) => e.id ?? ""));
|
|
813
|
-
const queueEvents = lastEventId && this.offlineDelivery ? await this.offlineDelivery.retrieve(resolvedAuth.userId, lastEventId, ringBufferIds) : [];
|
|
814
|
-
const established$ = this.transport.emitConnectionEvent ? of(buildEstablishedEvent(connectionId, resolvedAuth)) : EMPTY;
|
|
815
|
-
return this.buildStream({
|
|
816
|
-
connectionId,
|
|
817
|
-
resolvedAuth,
|
|
818
|
-
ip: context.ip,
|
|
819
|
-
userAgent: context.userAgent,
|
|
820
|
-
res,
|
|
821
|
-
subject,
|
|
822
|
-
close$,
|
|
823
|
-
established$,
|
|
824
|
-
replay$,
|
|
825
|
-
queueEvents
|
|
826
|
-
});
|
|
827
|
-
}
|
|
828
|
-
/**
|
|
829
|
-
* Build the live Observable using a subscribe-before-register pattern.
|
|
830
|
-
*
|
|
831
|
-
* The downstream subscriber is wired to the merged pipeline FIRST, so `subject`
|
|
832
|
-
* already has a listener when `registerConnection` runs. Any `subject.next()` that
|
|
833
|
-
* occurs during or after registration goes directly to the subscriber — nothing is
|
|
834
|
-
* buffered or retained, nothing is dropped, and ordering (established → replay →
|
|
835
|
-
* queue → live) is preserved.
|
|
836
|
-
*/
|
|
837
|
-
buildStream(p) {
|
|
838
|
-
return new Observable((subscriber) => {
|
|
839
|
-
const inner = this.subscribePipeline(p, subscriber);
|
|
840
|
-
if (!subscriber.closed && p.queueEvents.length > 0) {
|
|
841
|
-
void this.offlineDelivery?.acknowledge(p.resolvedAuth.userId, p.queueEvents);
|
|
842
|
-
}
|
|
843
|
-
this.activateConnection(p, subscriber);
|
|
844
|
-
return () => inner.unsubscribe();
|
|
845
|
-
});
|
|
846
|
-
}
|
|
847
|
-
/**
|
|
848
|
-
* Wire the merged pipeline to the downstream subscriber with teardown.
|
|
849
|
-
*
|
|
850
|
-
* Subscribing first guarantees `subject` has a listener before registration can emit,
|
|
851
|
-
* so a plain `Subject` suffices and ordering (established → replay → queue → live) holds.
|
|
852
|
-
*/
|
|
853
|
-
subscribePipeline(p, subscriber) {
|
|
854
|
-
const { connectionId, subject, close$, established$, replay$, queueEvents } = p;
|
|
855
|
-
const queueReplay$ = queueEvents.length > 0 ? of(...queueEvents.map(toMessageEvent)) : EMPTY;
|
|
856
|
-
return merge(established$, replay$, queueReplay$, subject).pipe(
|
|
857
|
-
takeUntil(close$),
|
|
858
|
-
catchError((error) => {
|
|
859
|
-
this.fireHook(
|
|
860
|
-
() => this.hooks?.onError?.({ connectionId, error, transport: "sse" })
|
|
861
|
-
);
|
|
862
|
-
return EMPTY;
|
|
863
|
-
}),
|
|
864
|
-
finalize(() => {
|
|
865
|
-
this.heartbeat.stop(connectionId);
|
|
866
|
-
void this.transport.unregisterConnection(connectionId);
|
|
867
|
-
})
|
|
868
|
-
).subscribe(subscriber);
|
|
869
|
-
}
|
|
870
|
-
/**
|
|
871
|
-
* Register the connection (after the subscriber is wired) and activate it on resolution.
|
|
872
|
-
*
|
|
873
|
-
* A registration failure routes to `onError` and errors the stream; a failure that
|
|
874
|
-
* arrives after teardown is a no-op since `subscriber.error` is ignored once closed.
|
|
875
|
-
*/
|
|
876
|
-
activateConnection(p, subscriber) {
|
|
877
|
-
const { connectionId, resolvedAuth, ip, userAgent, subject, close$ } = p;
|
|
878
|
-
this.transport.registerConnection({ connectionId, auth: resolvedAuth, subject, close$, ip, userAgent }).then(() => this.onRegistered(p, subscriber)).catch((err) => {
|
|
879
|
-
this.fireHook(
|
|
880
|
-
() => this.hooks?.onError?.({ connectionId, error: err, transport: "sse" })
|
|
881
|
-
);
|
|
882
|
-
subscriber.error(err);
|
|
883
|
-
});
|
|
884
|
-
}
|
|
885
|
-
/**
|
|
886
|
-
* Complete the connection handshake once registration resolves.
|
|
887
|
-
*
|
|
888
|
-
* Registration is async and can resolve AFTER the downstream subscriber has already
|
|
889
|
-
* torn down (client disconnected mid-handshake). When that happens `finalize` has
|
|
890
|
-
* already stopped the heartbeat and unregistered, so re-firing onConnect or starting
|
|
891
|
-
* a fresh heartbeat would leak the connection and write after close. Guard on
|
|
892
|
-
* `subscriber.closed`: if closed, undo the late registration idempotently and return.
|
|
893
|
-
*/
|
|
894
|
-
onRegistered(p, subscriber) {
|
|
895
|
-
const { connectionId, res } = p;
|
|
896
|
-
if (subscriber.closed) {
|
|
897
|
-
this.heartbeat.stop(connectionId);
|
|
898
|
-
void this.transport.unregisterConnection(connectionId);
|
|
899
|
-
return;
|
|
900
|
-
}
|
|
901
|
-
const record = this.transport.getConnection(connectionId);
|
|
902
|
-
if (record) {
|
|
903
|
-
this.fireHook(() => this.hooks?.onConnect?.(buildMeta(record)));
|
|
904
|
-
}
|
|
905
|
-
const heartbeatMs = this.options.sse?.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
|
|
906
|
-
this.heartbeat.start(connectionId, res, heartbeatMs);
|
|
907
|
-
}
|
|
908
|
-
/**
|
|
909
|
-
* Invoke a lifecycle hook best-effort — a throwing hook is logged and swallowed
|
|
910
|
-
* so it never disrupts the connection lifecycle or live event delivery.
|
|
911
|
-
*
|
|
912
|
-
* @param invoke - A zero-arg function that calls the hook (handles optionality).
|
|
913
|
-
*/
|
|
914
|
-
fireHook(invoke) {
|
|
915
|
-
void Promise.resolve(invoke()).catch((err) => {
|
|
916
|
-
this.logger.warn(`Lifecycle hook failed: ${err.message}`);
|
|
917
|
-
});
|
|
918
|
-
}
|
|
919
|
-
};
|
|
920
|
-
SseSubscriptionHandler = __decorateClass([
|
|
921
|
-
Injectable(),
|
|
922
|
-
__decorateParam(0, Inject(SseTransport)),
|
|
923
|
-
__decorateParam(1, Inject(HeartbeatService)),
|
|
924
|
-
__decorateParam(2, Inject(REALTIME_OPTIONS_TOKEN)),
|
|
925
|
-
__decorateParam(3, Optional()),
|
|
926
|
-
__decorateParam(3, Inject(REALTIME_HOOKS_TOKEN)),
|
|
927
|
-
__decorateParam(4, Optional()),
|
|
928
|
-
__decorateParam(4, Inject(OfflineQueueDeliveryService))
|
|
929
|
-
], SseSubscriptionHandler);
|
|
930
|
-
|
|
931
|
-
// src/server/factories/sse-controller.factory.ts
|
|
932
|
-
function createSseController(endpoint) {
|
|
933
|
-
const ssePath = endpoint.startsWith("/") ? endpoint.slice(1) : endpoint;
|
|
934
|
-
let DynamicSseController = class {
|
|
935
|
-
// Explicit @Inject: the published bundle is built by esbuild/tsup, which does
|
|
936
|
-
// not emit `design:paramtypes` decorator metadata, so constructor params must
|
|
937
|
-
// be resolved by token rather than by reflected type.
|
|
938
|
-
constructor(handler) {
|
|
939
|
-
this.handler = handler;
|
|
940
|
-
}
|
|
941
|
-
handler;
|
|
942
|
-
subscribe(req, res) {
|
|
943
|
-
return this.handler.handle(req, res);
|
|
944
|
-
}
|
|
945
|
-
};
|
|
946
|
-
__decorateClass([
|
|
947
|
-
Sse(ssePath),
|
|
948
|
-
__decorateParam(0, Req()),
|
|
949
|
-
__decorateParam(1, Res({ passthrough: true }))
|
|
950
|
-
], DynamicSseController.prototype, "subscribe", 1);
|
|
951
|
-
DynamicSseController = __decorateClass([
|
|
952
|
-
Controller(),
|
|
953
|
-
__decorateParam(0, Inject(SseSubscriptionHandler))
|
|
954
|
-
], DynamicSseController);
|
|
955
|
-
return DynamicSseController;
|
|
956
|
-
}
|
|
957
|
-
var InMemoryPubSub = class {
|
|
958
|
-
handlers = /* @__PURE__ */ new Set();
|
|
959
|
-
/**
|
|
960
|
-
* Publish a message to all subscribed handlers.
|
|
961
|
-
*
|
|
962
|
-
* Delivery is deferred one microtask so a handler that enqueues further publishes
|
|
963
|
-
* does not deepen the current call stack. One handler's failure does not block others.
|
|
964
|
-
*
|
|
965
|
-
* @param message - The pub/sub message to fan out.
|
|
966
|
-
*/
|
|
967
|
-
async publish(message) {
|
|
968
|
-
await Promise.resolve();
|
|
969
|
-
for (const handler of this.handlers) {
|
|
970
|
-
try {
|
|
971
|
-
handler(message);
|
|
972
|
-
} catch {
|
|
973
|
-
}
|
|
974
|
-
}
|
|
975
|
-
}
|
|
976
|
-
/**
|
|
977
|
-
* Subscribe to pub/sub messages.
|
|
978
|
-
*
|
|
979
|
-
* @param handler - Called for every published message.
|
|
980
|
-
* @returns An async unsubscribe function that removes this handler.
|
|
981
|
-
*/
|
|
982
|
-
async subscribe(handler) {
|
|
983
|
-
this.handlers.add(handler);
|
|
984
|
-
return async () => {
|
|
985
|
-
this.handlers.delete(handler);
|
|
986
|
-
};
|
|
987
|
-
}
|
|
988
|
-
};
|
|
989
|
-
InMemoryPubSub = __decorateClass([
|
|
990
|
-
Injectable()
|
|
991
|
-
], InMemoryPubSub);
|
|
992
|
-
var RealtimeService = class {
|
|
993
|
-
constructor(transport) {
|
|
994
|
-
this.transport = transport;
|
|
995
|
-
}
|
|
996
|
-
transport;
|
|
997
|
-
/**
|
|
998
|
-
* Send to all of a user's connections (across devices/tabs).
|
|
999
|
-
*
|
|
1000
|
-
* @example
|
|
1001
|
-
* ```ts
|
|
1002
|
-
* await realtime.emitToUser('u_abc', 'invoice.paid', { id: 'inv_123' })
|
|
1003
|
-
* ```
|
|
1004
|
-
*/
|
|
1005
|
-
emitToUser(userId, event, data) {
|
|
1006
|
-
return this.transport.emitToUser(userId, event, data);
|
|
1007
|
-
}
|
|
1008
|
-
/** Send to every connection in a tenant. */
|
|
1009
|
-
emitToTenant(tenantId, event, data) {
|
|
1010
|
-
return this.transport.emitToTenant(tenantId, event, data);
|
|
1011
|
-
}
|
|
1012
|
-
/**
|
|
1013
|
-
* Send to a logical room. Use the prefix convention (`user:{id}`,
|
|
1014
|
-
* `tenant:{id}`, `resource:{type}:{id}`) or a custom non-colliding id.
|
|
1015
|
-
*/
|
|
1016
|
-
emitToRoom(roomId, event, data) {
|
|
1017
|
-
return this.transport.emitToRoom(roomId, event, data);
|
|
1018
|
-
}
|
|
1019
|
-
/** Send to every connected client. Use sparingly. */
|
|
1020
|
-
broadcast(event, data) {
|
|
1021
|
-
return this.transport.broadcast(event, data);
|
|
1022
|
-
}
|
|
1023
|
-
/** Add a specific connection to a room. */
|
|
1024
|
-
joinRoom(connectionId, roomId) {
|
|
1025
|
-
return this.transport.joinRoom(connectionId, roomId);
|
|
1026
|
-
}
|
|
1027
|
-
/** Remove a specific connection from a room. */
|
|
1028
|
-
leaveRoom(connectionId, roomId) {
|
|
1029
|
-
return this.transport.leaveRoom(connectionId, roomId);
|
|
1030
|
-
}
|
|
1031
|
-
/** Force-disconnect a specific connection (e.g. on auth revocation). */
|
|
1032
|
-
disconnect(connectionId, reason) {
|
|
1033
|
-
return this.transport.disconnect(connectionId, reason);
|
|
1034
|
-
}
|
|
1035
|
-
};
|
|
1036
|
-
RealtimeService = __decorateClass([
|
|
1037
|
-
Injectable(),
|
|
1038
|
-
__decorateParam(0, Inject(REALTIME_TRANSPORT_TOKEN))
|
|
1039
|
-
], RealtimeService);
|
|
1040
|
-
function resolvePolicy(raw) {
|
|
1041
|
-
return {
|
|
1042
|
-
intervalSeconds: raw?.intervalSeconds ?? 300,
|
|
1043
|
-
onFailure: raw?.onFailure ?? "disconnect",
|
|
1044
|
-
cacheTtlMs: raw?.cacheTtlMs ?? 6e4
|
|
1045
|
-
};
|
|
1046
|
-
}
|
|
1047
|
-
var ReauthenticationService = class {
|
|
1048
|
-
constructor(connections, realtime, auth, options, hooks) {
|
|
1049
|
-
this.connections = connections;
|
|
1050
|
-
this.realtime = realtime;
|
|
1051
|
-
this.auth = auth;
|
|
1052
|
-
this.hooks = hooks;
|
|
1053
|
-
this.policy = resolvePolicy(options.reauthenticationPolicy);
|
|
1054
|
-
}
|
|
1055
|
-
connections;
|
|
1056
|
-
realtime;
|
|
1057
|
-
auth;
|
|
1058
|
-
hooks;
|
|
1059
|
-
logger = new Logger(ReauthenticationService.name);
|
|
1060
|
-
timer = null;
|
|
1061
|
-
/** connectionId → epoch-ms timestamp of last successful revalidation. */
|
|
1062
|
-
positiveCache = /* @__PURE__ */ new Map();
|
|
1063
|
-
policy;
|
|
1064
|
-
/**
|
|
1065
|
-
* Schedule the periodic revalidation cycle.
|
|
1066
|
-
*
|
|
1067
|
-
* The timer is unref'd so it never keeps the process alive on its own.
|
|
1068
|
-
* When the authenticator does not implement `revalidate`, the service stays
|
|
1069
|
-
* idle and emits an informative log.
|
|
1070
|
-
*/
|
|
1071
|
-
onModuleInit() {
|
|
1072
|
-
if (!this.auth.revalidate) {
|
|
1073
|
-
this.logger.log("Authenticator does not implement revalidate() \u2014 reauthentication disabled");
|
|
1074
|
-
return;
|
|
1075
|
-
}
|
|
1076
|
-
this.timer = setInterval(() => void this.runCycle(), this.policy.intervalSeconds * 1e3);
|
|
1077
|
-
this.timer.unref();
|
|
1078
|
-
this.logger.log(`Reauthentication scheduled every ${this.policy.intervalSeconds}s`);
|
|
1079
|
-
}
|
|
1080
|
-
/**
|
|
1081
|
-
* Clear the timer and the positive cache.
|
|
1082
|
-
*
|
|
1083
|
-
* Called by NestJS on graceful shutdown to prevent leaks.
|
|
1084
|
-
*/
|
|
1085
|
-
onApplicationShutdown() {
|
|
1086
|
-
if (this.timer) {
|
|
1087
|
-
clearInterval(this.timer);
|
|
1088
|
-
this.timer = null;
|
|
1089
|
-
}
|
|
1090
|
-
this.positiveCache.clear();
|
|
1091
|
-
}
|
|
1092
|
-
/**
|
|
1093
|
-
* Run one revalidation cycle over all active SSE connections.
|
|
1094
|
-
*
|
|
1095
|
-
* A cache hit within `cacheTtlMs` skips the `revalidate` call. A positive result
|
|
1096
|
-
* refreshes the cache. A negative result (or a thrown error) invokes the configured
|
|
1097
|
-
* `onFailure` policy and fires the `onReauthenticationFailed` hook best-effort.
|
|
1098
|
-
*
|
|
1099
|
-
* Exposed as public for test access.
|
|
1100
|
-
*/
|
|
1101
|
-
async runCycle() {
|
|
1102
|
-
const now = Date.now();
|
|
1103
|
-
for (const conn of this.connections.allByTransport("sse")) {
|
|
1104
|
-
try {
|
|
1105
|
-
const lastValid = this.positiveCache.get(conn.connectionId);
|
|
1106
|
-
if (lastValid !== void 0 && now - lastValid < this.policy.cacheTtlMs) continue;
|
|
1107
|
-
const originalAuth = {
|
|
1108
|
-
userId: conn.originalAuth.userId,
|
|
1109
|
-
...conn.originalAuth.tenantId !== void 0 ? { tenantId: conn.originalAuth.tenantId } : {},
|
|
1110
|
-
...conn.originalAuth.roles !== void 0 ? { roles: conn.originalAuth.roles } : {}
|
|
1111
|
-
};
|
|
1112
|
-
const rawResult = await this.auth.revalidate?.(conn.connectionId, originalAuth) ?? true;
|
|
1113
|
-
if (rawResult === true) {
|
|
1114
|
-
this.positiveCache.set(conn.connectionId, now);
|
|
1115
|
-
continue;
|
|
1116
|
-
}
|
|
1117
|
-
await this.handleFailure(conn);
|
|
1118
|
-
} catch (err) {
|
|
1119
|
-
this.logger.warn(
|
|
1120
|
-
`Reauthentication errored for ${conn.connectionId}: ${err.message}`
|
|
1121
|
-
);
|
|
1122
|
-
await this.handleFailure(conn);
|
|
1123
|
-
}
|
|
1124
|
-
}
|
|
1125
|
-
}
|
|
1126
|
-
/** Evict the positive-cache entry, optionally emit the failure event, then disconnect. */
|
|
1127
|
-
async handleFailure(conn) {
|
|
1128
|
-
this.positiveCache.delete(conn.connectionId);
|
|
1129
|
-
if (this.policy.onFailure === "event") {
|
|
1130
|
-
await this.realtime.emitToUser(conn.userId, RESERVED_EVENT_NAMES.CONNECTION_REAUTH_FAILED, {
|
|
1131
|
-
reason: REALTIME_ERROR_CODES.REAUTHENTICATION_FAILED
|
|
1132
|
-
});
|
|
1133
|
-
}
|
|
1134
|
-
void Promise.resolve(
|
|
1135
|
-
this.hooks?.onReauthenticationFailed?.({
|
|
1136
|
-
connectionId: conn.connectionId,
|
|
1137
|
-
userId: conn.userId,
|
|
1138
|
-
tenantId: conn.tenantId,
|
|
1139
|
-
transport: "sse",
|
|
1140
|
-
ip: conn.ip,
|
|
1141
|
-
userAgent: conn.userAgent,
|
|
1142
|
-
connectedAt: conn.connectedAt
|
|
1143
|
-
})
|
|
1144
|
-
).catch((err) => {
|
|
1145
|
-
this.logger.warn(`onReauthenticationFailed hook failed: ${err.message}`);
|
|
1146
|
-
});
|
|
1147
|
-
await this.realtime.disconnect(conn.connectionId, REALTIME_ERROR_CODES.REAUTHENTICATION_FAILED);
|
|
1148
|
-
}
|
|
1149
|
-
};
|
|
1150
|
-
ReauthenticationService = __decorateClass([
|
|
1151
|
-
Injectable(),
|
|
1152
|
-
__decorateParam(0, Inject(ConnectionRegistry)),
|
|
1153
|
-
__decorateParam(1, Inject(RealtimeService)),
|
|
1154
|
-
__decorateParam(2, Inject(REALTIME_AUTHENTICATOR_TOKEN)),
|
|
1155
|
-
__decorateParam(3, Inject(REALTIME_OPTIONS_TOKEN)),
|
|
1156
|
-
__decorateParam(4, Optional()),
|
|
1157
|
-
__decorateParam(4, Inject(REALTIME_HOOKS_TOKEN))
|
|
1158
|
-
], ReauthenticationService);
|
|
1159
|
-
|
|
1160
|
-
// src/server/composition/realtime-module.factory.ts
|
|
1161
|
-
var EXPORTED_TOKENS = [
|
|
1162
|
-
RealtimeService,
|
|
1163
|
-
ConnectionRegistry,
|
|
1164
|
-
REALTIME_OPTIONS_TOKEN,
|
|
1165
|
-
REALTIME_INSTANCE_ID_TOKEN,
|
|
1166
|
-
REALTIME_AUTHENTICATOR_TOKEN,
|
|
1167
|
-
REALTIME_PUBSUB_TOKEN,
|
|
1168
|
-
REALTIME_HOOKS_TOKEN,
|
|
1169
|
-
REALTIME_OFFLINE_QUEUE_TOKEN,
|
|
1170
|
-
REALTIME_PRESENCE_TOKEN,
|
|
1171
|
-
REALTIME_TRANSPORT_TOKEN
|
|
1172
|
-
];
|
|
1173
|
-
var SHARED_SERVICES = [
|
|
1174
|
-
ConnectionRegistry,
|
|
1175
|
-
RoomRegistry,
|
|
1176
|
-
EventIdGenerator,
|
|
1177
|
-
EventReplayBuffer,
|
|
1178
|
-
HeartbeatService,
|
|
1179
|
-
RealtimeService,
|
|
1180
|
-
ReauthenticationService,
|
|
1181
|
-
OfflineQueueDeliveryService
|
|
1182
|
-
];
|
|
1183
|
-
function assertModeSupported(wiring, mode, moduleName) {
|
|
1184
|
-
if (wiring.modes.includes(mode)) return;
|
|
1185
|
-
const alternative = mode === "sse" ? "'BymaxRealtimeModule' from '@bymax-one/nest-realtime'" : "'BymaxRealtimeWebSocketModule' from '@bymax-one/nest-realtime/websocket'";
|
|
1186
|
-
throw new Error(
|
|
1187
|
-
`[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: transport '${mode}' is not served by this module (it serves ${wiring.modes.map((m) => `'${m}'`).join(", ")}). Use ${alternative}.`
|
|
1188
|
-
);
|
|
1189
|
-
}
|
|
1190
|
-
function warnIfSingleInstance(pubsub, transport, logger) {
|
|
1191
|
-
if (transport === "websocket") return;
|
|
1192
|
-
if (!pubsub && process.env["NODE_ENV"] === "production") {
|
|
1193
|
-
logger.warn(
|
|
1194
|
-
"No IRealtimePubSub provided in production \u2014 single-instance only. Provide a Redis-backed IRealtimePubSub for horizontal scaling."
|
|
1195
|
-
);
|
|
1196
|
-
}
|
|
1197
|
-
}
|
|
1198
|
-
function buildCommonProviders(resolved, instanceId) {
|
|
1199
|
-
return [
|
|
1200
|
-
{ provide: REALTIME_OPTIONS_TOKEN, useValue: resolved },
|
|
1201
|
-
{ provide: REALTIME_INSTANCE_ID_TOKEN, useValue: instanceId },
|
|
1202
|
-
{ provide: REALTIME_AUTHENTICATOR_TOKEN, useValue: resolved.authenticator },
|
|
1203
|
-
{ provide: REALTIME_PUBSUB_TOKEN, useValue: resolved.pubsub ?? new InMemoryPubSub() },
|
|
1204
|
-
{ provide: REALTIME_HOOKS_TOKEN, useValue: resolved.hooks ?? {} },
|
|
1205
|
-
{ provide: REALTIME_OFFLINE_QUEUE_TOKEN, useValue: resolved.offlineQueue },
|
|
1206
|
-
{ provide: REALTIME_PRESENCE_TOKEN, useValue: resolved.presence },
|
|
1207
|
-
...SHARED_SERVICES
|
|
1208
|
-
];
|
|
1209
|
-
}
|
|
1210
|
-
function composeForRoot(moduleClass, wiring, logger, options) {
|
|
1211
|
-
validateOptions(options);
|
|
1212
|
-
assertModeSupported(wiring, options.transport, moduleClass.name);
|
|
1213
|
-
const resolved = applyDefaults(options);
|
|
1214
|
-
const instanceId = randomUUID();
|
|
1215
|
-
warnIfSingleInstance(resolved.pubsub, resolved.transport, logger);
|
|
1216
|
-
const { providers, endpoints, gateways } = wiring.build(resolved);
|
|
1217
|
-
logger.log(`Bootstrapped (transport=${resolved.transport}, instanceId=${instanceId})`);
|
|
1218
|
-
return {
|
|
1219
|
-
module: moduleClass,
|
|
1220
|
-
controllers: endpoints.map((endpoint) => createSseController(endpoint)),
|
|
1221
|
-
providers: [...buildCommonProviders(resolved, instanceId), ...providers, ...gateways],
|
|
1222
|
-
exports: EXPORTED_TOKENS
|
|
1223
|
-
};
|
|
1224
|
-
}
|
|
1225
|
-
function resolveAsyncOptions(raw, declaredMode, instanceId, source, logger, moduleName) {
|
|
1226
|
-
if (!raw) {
|
|
1227
|
-
throw new Error(`${REALTIME_ERROR_CODES.INVALID_OPTIONS}: ${source} returned nothing`);
|
|
1228
|
-
}
|
|
1229
|
-
validateOptions(raw);
|
|
1230
|
-
if (raw.transport !== declaredMode) {
|
|
1231
|
-
throw new Error(
|
|
1232
|
-
`[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: forRootAsync was registered for transport '${declaredMode}' but the factory resolved '${raw.transport}'`
|
|
1233
|
-
);
|
|
1234
|
-
}
|
|
1235
|
-
const resolved = applyDefaults(raw);
|
|
1236
|
-
logger.log(`Bootstrapped (transport=${resolved.transport}, instanceId=${instanceId})`);
|
|
1237
|
-
return resolved;
|
|
1238
|
-
}
|
|
1239
|
-
function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
|
|
1240
|
-
const moduleName = moduleClass.name;
|
|
1241
|
-
const patterns = [
|
|
1242
|
-
asyncOptions.useFactory,
|
|
1243
|
-
asyncOptions.useClass,
|
|
1244
|
-
asyncOptions.useExisting
|
|
1245
|
-
].filter((pattern) => pattern !== void 0);
|
|
1246
|
-
if (patterns.length !== 1) {
|
|
1247
|
-
throw new Error(
|
|
1248
|
-
`[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: forRootAsync requires exactly one of useFactory, useClass, or useExisting (received ${patterns.length})`
|
|
1249
|
-
);
|
|
1250
|
-
}
|
|
1251
|
-
assertModeSupported(wiring, asyncOptions.transport, moduleName);
|
|
1252
|
-
const FACTORY_TOKEN = /* @__PURE__ */ Symbol("REALTIME_OPTIONS_FACTORY");
|
|
1253
|
-
const instanceId = randomUUID();
|
|
1254
|
-
const resolve = (raw, source) => resolveAsyncOptions(raw, asyncOptions.transport, instanceId, source, logger, moduleName);
|
|
1255
|
-
const resolvedOptionsProvider = asyncOptions.useFactory ? {
|
|
1256
|
-
provide: REALTIME_OPTIONS_TOKEN,
|
|
1257
|
-
useFactory: async (...args) => resolve(await asyncOptions.useFactory(...args), "useFactory"),
|
|
1258
|
-
inject: [...asyncOptions.inject ?? []]
|
|
1259
|
-
} : {
|
|
1260
|
-
provide: REALTIME_OPTIONS_TOKEN,
|
|
1261
|
-
useFactory: async (factory) => resolve(
|
|
1262
|
-
await factory.createRealtimeOptions(),
|
|
1263
|
-
"createRealtimeOptions"
|
|
1264
|
-
),
|
|
1265
|
-
inject: [asyncOptions.useExisting ?? FACTORY_TOKEN]
|
|
1266
|
-
};
|
|
1267
|
-
const factoryClassProvider = asyncOptions.useClass ? [{ provide: FACTORY_TOKEN, useClass: asyncOptions.useClass }] : [];
|
|
1268
|
-
const fromOptions = (token, read) => ({ provide: token, useFactory: read, inject: [REALTIME_OPTIONS_TOKEN] });
|
|
1269
|
-
const { providers: transportProviders, controllers } = wiring.buildAsync(asyncOptions.transport);
|
|
1270
|
-
return {
|
|
1271
|
-
module: moduleClass,
|
|
1272
|
-
imports: asyncOptions.imports ?? [],
|
|
1273
|
-
controllers,
|
|
1274
|
-
providers: [
|
|
1275
|
-
...factoryClassProvider,
|
|
1276
|
-
resolvedOptionsProvider,
|
|
1277
|
-
fromOptions(REALTIME_AUTHENTICATOR_TOKEN, (opts) => opts.authenticator),
|
|
1278
|
-
fromOptions(REALTIME_PUBSUB_TOKEN, (opts) => {
|
|
1279
|
-
warnIfSingleInstance(opts.pubsub, opts.transport, logger);
|
|
1280
|
-
return opts.pubsub ?? new InMemoryPubSub();
|
|
1281
|
-
}),
|
|
1282
|
-
fromOptions(REALTIME_HOOKS_TOKEN, (opts) => opts.hooks ?? {}),
|
|
1283
|
-
{ provide: REALTIME_INSTANCE_ID_TOKEN, useValue: instanceId },
|
|
1284
|
-
fromOptions(REALTIME_OFFLINE_QUEUE_TOKEN, (opts) => opts.offlineQueue),
|
|
1285
|
-
fromOptions(REALTIME_PRESENCE_TOKEN, (opts) => opts.presence),
|
|
1286
|
-
...SHARED_SERVICES,
|
|
1287
|
-
...transportProviders,
|
|
1288
|
-
...asyncOptions.extraProviders ?? []
|
|
1289
|
-
],
|
|
1290
|
-
exports: EXPORTED_TOKENS
|
|
1291
|
-
};
|
|
1292
|
-
}
|
|
1293
|
-
var RealtimePubSubSubscriber = class {
|
|
1294
|
-
constructor(pubsub, instanceId, sse) {
|
|
1295
|
-
this.pubsub = pubsub;
|
|
1296
|
-
this.instanceId = instanceId;
|
|
1297
|
-
this.sse = sse;
|
|
1298
|
-
}
|
|
1299
|
-
pubsub;
|
|
1300
|
-
instanceId;
|
|
1301
|
-
sse;
|
|
1302
|
-
logger = new Logger(RealtimePubSubSubscriber.name);
|
|
1303
|
-
unsubscribe = null;
|
|
1304
|
-
async onModuleInit() {
|
|
1305
|
-
try {
|
|
1306
|
-
this.unsubscribe = await this.pubsub.subscribe((msg) => this.handle(msg));
|
|
1307
|
-
} catch (err) {
|
|
1308
|
-
this.logger.warn(
|
|
1309
|
-
`Failed to subscribe to pub/sub: ${err.message}. Cross-instance fan-out disabled; remote events will not reach this instance.`
|
|
1310
|
-
);
|
|
1311
|
-
}
|
|
1312
|
-
}
|
|
1313
|
-
async onApplicationShutdown() {
|
|
1314
|
-
if (this.unsubscribe) {
|
|
1315
|
-
try {
|
|
1316
|
-
await this.unsubscribe();
|
|
1317
|
-
} catch (err) {
|
|
1318
|
-
this.logger.warn(`Pub/sub unsubscribe failed: ${err.message}`);
|
|
1319
|
-
}
|
|
1320
|
-
this.unsubscribe = null;
|
|
1321
|
-
}
|
|
1322
|
-
}
|
|
1323
|
-
handle(msg) {
|
|
1324
|
-
if (msg.origin === this.instanceId) return;
|
|
1325
|
-
try {
|
|
1326
|
-
switch (msg.op) {
|
|
1327
|
-
case "emitToUser": {
|
|
1328
|
-
const a = msg.args;
|
|
1329
|
-
this.sse.emitToUserLocal(a.userId, a.event, a.data, a.id);
|
|
1330
|
-
break;
|
|
1331
|
-
}
|
|
1332
|
-
case "emitToTenant": {
|
|
1333
|
-
const a = msg.args;
|
|
1334
|
-
this.sse.emitToTenantLocal(a.tenantId, a.event, a.data, a.id);
|
|
1335
|
-
break;
|
|
1336
|
-
}
|
|
1337
|
-
case "emitToRoom": {
|
|
1338
|
-
const a = msg.args;
|
|
1339
|
-
this.sse.emitToRoomLocal(a.roomId, a.event, a.data, a.id);
|
|
1340
|
-
break;
|
|
1341
|
-
}
|
|
1342
|
-
case "broadcast": {
|
|
1343
|
-
const a = msg.args;
|
|
1344
|
-
this.sse.broadcastLocal(a.event, a.data, a.id);
|
|
1345
|
-
break;
|
|
1346
|
-
}
|
|
1347
|
-
case "disconnect": {
|
|
1348
|
-
const a = msg.args;
|
|
1349
|
-
void this.sse.disconnectLocal(a.connectionId, a.reason);
|
|
1350
|
-
break;
|
|
1351
|
-
}
|
|
1352
|
-
default: {
|
|
1353
|
-
const exhaustive = msg.op;
|
|
1354
|
-
this.logger.warn(`Unknown pub/sub op: ${String(exhaustive)}`);
|
|
1355
|
-
}
|
|
1356
|
-
}
|
|
1357
|
-
} catch (err) {
|
|
1358
|
-
this.logger.warn(`Pub/sub message handling failed: ${err.message}`);
|
|
1359
|
-
}
|
|
1360
|
-
}
|
|
1361
|
-
};
|
|
1362
|
-
RealtimePubSubSubscriber = __decorateClass([
|
|
1363
|
-
Injectable(),
|
|
1364
|
-
__decorateParam(0, Inject(REALTIME_PUBSUB_TOKEN)),
|
|
1365
|
-
__decorateParam(1, Inject(REALTIME_INSTANCE_ID_TOKEN)),
|
|
1366
|
-
__decorateParam(2, Inject(SseTransport))
|
|
1367
|
-
], RealtimePubSubSubscriber);
|
|
1368
25
|
var CONNECTION_ROOM_PREFIX = "connection";
|
|
1369
26
|
var WebSocketTransport = class {
|
|
1370
27
|
constructor(connections, rooms, auth, hooks, options) {
|
|
@@ -1603,7 +260,7 @@ WebSocketTransport = __decorateClass([
|
|
|
1603
260
|
__decorateParam(4, Inject(REALTIME_OPTIONS_TOKEN))
|
|
1604
261
|
], WebSocketTransport);
|
|
1605
262
|
|
|
1606
|
-
// src/
|
|
263
|
+
// src/websocket/transports/composite/composite.transport.ts
|
|
1607
264
|
var CompositeTransport = class {
|
|
1608
265
|
constructor(sse, ws) {
|
|
1609
266
|
this.sse = sse;
|