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