@jskit-ai/realtime 0.2.17 → 0.2.18

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 CHANGED
@@ -2,7 +2,10 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - A server without `REDIS_URL` no longer loads Redis: `redis` and `@socket.io/redis-adapter`, about 650 modules and 0.3 s on their own, are imported only when the Socket.IO Redis adapter is configured. Real app boots load 480 fewer modules. `configureSocketIoRedisAdapter`'s `createRedisConnection` and `createRedisAdapter` still default to them.
5
6
  - `SESSION_REFRESH_REQUIRED` has its English in the catalog, so it translates.
7
+ - A publish to a user or workspace room checks only the sockets that can receive it: those already in a target room, those whose actor's contributed rooms include a target, and those not signed in yet. Before, once any audience contributor was registered, every connected socket was authenticated and had its actor's rooms looked up (one memberships query per online actor) inside the mutating request, and again on each Redis peer. A socket that cannot receive the publish is rechecked by the 30-second pass, as a socket outside any other room already was. An actor granted membership still receives the very next publish, and a removed or revoked one does not.
8
+ - Breaking: audience contributors register `resolveActorsScopes(actorIds)`, which returns, or resolves to, a `Map` from actor id to scopes, instead of `resolveActorScopes(actorId)`. A publish, and each 30-second pass, asks each contributor once for every actor it needs, whatever the number of connected sockets, and the sockets it then checks share that answer.
6
9
 
7
10
  ### New codes (1)
8
11
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/realtime",
3
- "version": "0.2.17",
3
+ "version": "0.2.18",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -23,7 +23,7 @@
23
23
  "socket.io-client": "^4.8.3"
24
24
  },
25
25
  "peerDependencies": {
26
- "@jskit-ai/kernel": "0.2.11",
26
+ "@jskit-ai/kernel": "0.2.12",
27
27
  "vue": "^3.5.13"
28
28
  },
29
29
  "description": "Thin, generic realtime runtime wrappers for socket.io server and client.",
@@ -2,7 +2,7 @@
2
2
  "private": true,
3
3
  "type": "module",
4
4
  "dependencies": {
5
- "@jskit-ai/realtime": "0.2.17",
6
- "@jskit-ai/shell-web": "0.2.14"
5
+ "@jskit-ai/realtime": "0.2.18",
6
+ "@jskit-ai/shell-web": "0.2.15"
7
7
  }
8
8
  }
@@ -5,6 +5,7 @@ import { normalizeRecordId, normalizeText } from "@jskit-ai/kernel/shared/suppor
5
5
  /** @typedef {import("@jskit-ai/database-runtime/server/types").RuntimeDatabase} RuntimeDatabase */
6
6
  /** @typedef {import("@jskit-ai/kernel/server/types").RuntimeLogger} RuntimeLogger */
7
7
  /** @typedef {import("./types.js").ActorRoomsResolver} ActorRoomsResolver */
8
+ /** @typedef {import("./types.js").ActorsRoomsResolver} ActorsRoomsResolver */
8
9
  /** @typedef {import("./types.js").AudienceContributors} AudienceContributors */
9
10
 
10
11
  const ALL_CLIENTS_ROOM = "clients";
@@ -73,22 +74,24 @@ function roomForScope(scope) {
73
74
  /**
74
75
  * Packages that know which scopes an actor belongs to (for example workspace
75
76
  * memberships) contribute them here; realtime only turns scopes into rooms.
77
+ * A contributor answers for many actors at once, so a publish that may let
78
+ * every online actor into a room asks each contributor once, not once per actor.
76
79
  */
77
80
  function createAudienceContributors() {
78
81
  const contributors = new Map();
79
82
 
80
83
  /** @param {import("./types.js").RealtimeAudienceContributor} contributor Validated here. */
81
- function register({ id, resolveActorScopes }) {
84
+ function register({ id, resolveActorsScopes }) {
82
85
  const contributorId = normalizeText(id);
83
86
  if (!contributorId) throw new TypeError("Realtime audience contributors require an id.");
84
87
  // readable-check: allow method-probe - input validation: a package registers its own contributor
85
- if (typeof resolveActorScopes !== "function") {
86
- throw new TypeError(`Realtime audience contributor "${contributorId}" requires resolveActorScopes().`);
88
+ if (typeof resolveActorsScopes !== "function") {
89
+ throw new TypeError(`Realtime audience contributor "${contributorId}" requires resolveActorsScopes().`);
87
90
  }
88
91
  if (contributors.has(contributorId)) {
89
92
  throw new Error(`Realtime audience contributor "${contributorId}" is already registered.`);
90
93
  }
91
- contributors.set(contributorId, resolveActorScopes);
94
+ contributors.set(contributorId, { id: contributorId, resolveActorsScopes });
92
95
  }
93
96
 
94
97
  /**
@@ -100,22 +103,40 @@ function createAudienceContributors() {
100
103
  return contributors.size > 0 && /^(?:user|workspace):/u.test(String(room));
101
104
  }
102
105
 
103
- /** @type {ActorRoomsResolver} */
104
- async function resolveActorRooms(actorId) {
105
- const rooms = new Set();
106
- for (const resolveActorScopes of contributors.values()) {
107
- for (const scope of flattenEntries(await resolveActorScopes(actorId))) {
108
- const room = roomForScope(scope);
109
- if (room) rooms.add(room);
106
+ /**
107
+ * Every actor's contributed rooms, with one call per contributor whatever
108
+ * the number of actors.
109
+ * @type {ActorsRoomsResolver}
110
+ */
111
+ async function resolveActorsRooms(actorIds) {
112
+ const roomsByActorId = new Map();
113
+ for (const actorId of actorIds) roomsByActorId.set(actorId, new Set());
114
+ if (roomsByActorId.size === 0) return roomsByActorId;
115
+ for (const { id, resolveActorsScopes } of contributors.values()) {
116
+ const scopesByActorId = await resolveActorsScopes([...roomsByActorId.keys()]);
117
+ if (!(scopesByActorId instanceof Map)) {
118
+ throw new TypeError(`Realtime audience contributor "${id}" must resolve to a Map of actor ids to scopes.`);
119
+ }
120
+ for (const [actorId, rooms] of roomsByActorId) {
121
+ for (const scope of flattenEntries(scopesByActorId.get(actorId))) {
122
+ const room = roomForScope(scope);
123
+ if (room) rooms.add(room);
124
+ }
110
125
  }
111
126
  }
112
- return rooms;
127
+ return roomsByActorId;
128
+ }
129
+
130
+ /** @type {ActorRoomsResolver} */
131
+ async function resolveActorRooms(actorId) {
132
+ return (await resolveActorsRooms([actorId])).get(actorId);
113
133
  }
114
134
 
115
135
  return Object.freeze({
116
136
  register,
117
137
  mayContribute,
118
- resolveActorRooms
138
+ resolveActorRooms,
139
+ resolveActorsRooms
119
140
  });
120
141
  }
121
142
 
@@ -4,6 +4,7 @@ import { countConnectedClients } from "./runtime.js";
4
4
 
5
5
  /** @typedef {import("@jskit-ai/auth-core/server/types").AuthService} AuthService */
6
6
  /** @typedef {import("./types.js").ActorRoomsResolver} ActorRoomsResolver */
7
+ /** @typedef {import("./types.js").ActorsRoomsResolver} ActorsRoomsResolver */
7
8
  /** @typedef {import("./types.js").AudienceContributors} AudienceContributors */
8
9
 
9
10
  const DELIVERY_EVENT = "jskit:realtime:delivery";
@@ -27,16 +28,8 @@ function publicRealtimePayload(event) {
27
28
  });
28
29
  }
29
30
 
30
- /**
31
- * A question's key when its value is the key.
32
- * @param {unknown} value
33
- */
34
- function valueAsKey(value) {
35
- return value;
36
- }
37
-
38
31
  /** One answer per question within one pass. */
39
- function sharedWithinPass(load, keyOf = valueAsKey) {
32
+ function sharedWithinPass(load, keyOf) {
40
33
  const answers = new Map();
41
34
  return (value) => {
42
35
  const key = keyOf(value);
@@ -48,20 +41,49 @@ function sharedWithinPass(load, keyOf = valueAsKey) {
48
41
  /**
49
42
  * The checks of one publish or 30-second pass. Identical socket requests share
50
43
  * one authentication (the auth service sees only the request), and sockets of
51
- * one actor share its contributed rooms. Revalidation asks only who is signed
52
- * in, so the provider reads the app profile instead of synchronizing it, and
53
- * never refreshes a session the socket could not store.
44
+ * one actor share its contributed rooms. The rooms of the actors a pass names
45
+ * up front are one bulk resolution, which the sockets it revalidates then
46
+ * share, so no actor's rooms are looked up twice in a pass. Revalidation asks
47
+ * only who is signed in, so the provider reads the app profile instead of
48
+ * synchronizing it, and never refreshes a session the socket could not store.
54
49
  * @param {AuthService} authService
55
- * @param {ActorRoomsResolver} resolveActorRooms
50
+ * @param {ActorsRoomsResolver} resolveActorsRooms
56
51
  */
57
- function createPassChecks(authService, resolveActorRooms) {
58
- return {
52
+ function createPassChecks(authService, resolveActorsRooms) {
53
+ const roomLookups = new Map();
54
+
55
+ /** @param {Iterable<string>} actorIds Resolved together, except those this pass already has. */
56
+ function lookUpActorsRooms(actorIds) {
57
+ const unknown = [...new Set(actorIds)].filter((actorId) => !roomLookups.has(actorId));
58
+ if (unknown.length === 0) return;
59
+ const lookup = (async () => resolveActorsRooms(unknown))();
60
+ // A failed lookup fails each revalidation that waits for it, not the process.
61
+ lookup.catch(() => {});
62
+ for (const actorId of unknown) roomLookups.set(actorId, lookup);
63
+ }
64
+
65
+ /** @type {ActorRoomsResolver} */
66
+ async function resolveActorRooms(actorId) {
67
+ lookUpActorsRooms([actorId]);
68
+ return (await roomLookups.get(actorId)).get(actorId);
69
+ }
70
+
71
+ return Object.freeze({
59
72
  authenticateRequest: sharedWithinPass(
60
73
  (request) => authService.authenticateRequest(request, { syncProfile: false, refreshSession: false }),
61
74
  JSON.stringify
62
75
  ),
63
- audiences: { resolveActorRooms: sharedWithinPass(resolveActorRooms) }
64
- };
76
+ lookUpActorsRooms,
77
+ audiences: Object.freeze({ resolveActorRooms })
78
+ });
79
+ }
80
+
81
+ /**
82
+ * The actor a socket signed in as, when it did.
83
+ * @param {import("socket.io").Socket} socket
84
+ */
85
+ function rememberedActorId(socket) {
86
+ return socket.data.actorId || null;
65
87
  }
66
88
 
67
89
  /**
@@ -73,7 +95,7 @@ function createPassChecks(authService, resolveActorRooms) {
73
95
  * @param {AudienceContributors} dependencies.audiences The rooms revalidation may make a socket join.
74
96
  * With no contributors registered, a socket stays in the rooms it already has.
75
97
  */
76
- function createRealtimeDelivery({ io, database, logger, authService, audiences: { mayContribute, resolveActorRooms } }) {
98
+ function createRealtimeDelivery({ io, database, logger, authService, audiences: { mayContribute, resolveActorsRooms } }) {
77
99
  // With an auth.service, each socket is revalidated before it receives an event;
78
100
  // without one, events go straight to their rooms.
79
101
  const guarded = Boolean(authService);
@@ -102,18 +124,45 @@ function createRealtimeDelivery({ io, database, logger, authService, audiences:
102
124
  }
103
125
 
104
126
  /**
127
+ * The sockets that can receive the event, and so are revalidated before it.
105
128
  * A socket outside every target room can enter one only by revalidation
106
- * joining a contributed room; otherwise checking it cannot change delivery.
129
+ * joining a contributed room, and the rooms it joins are exactly its actor's
130
+ * (a socket whose login now names another actor is disconnected instead). So
131
+ * a socket outside is checked only when its actor's rooms, one bulk lookup
132
+ * for every outside actor, include a target, or when it has no actor yet and
133
+ * may sign in now. Any other socket is left to the 30-second pass.
134
+ * @param {{ broadcastAllClients: boolean, rooms: readonly string[] }} targets
135
+ * @param {ReturnType<typeof createPassChecks>} checks
107
136
  */
108
- function candidateSockets(targets) {
137
+ async function candidateSockets(targets, checks) {
109
138
  const sockets = [...io.sockets.sockets.values()];
110
- if (targets.broadcastAllClients || targets.rooms.some((room) => mayContribute(room))) return sockets;
111
- return sockets.filter((socket) => targets.rooms.some((room) => socket.rooms.has(room)));
139
+ if (targets.broadcastAllClients) return sockets;
140
+ const inTargets = (socket) => targets.rooms.some((room) => socket.rooms.has(room));
141
+ const contributable = targets.rooms.filter((room) => mayContribute(room));
142
+ if (contributable.length === 0) return sockets.filter(inTargets);
143
+
144
+ // The rooms of every signed-in socket's actor, inside or outside, in one lookup.
145
+ checks.lookUpActorsRooms(sockets.map(rememberedActorId).filter(Boolean));
146
+ const entering = await Promise.all(sockets.map(async (socket) => {
147
+ if (inTargets(socket)) return true;
148
+ const actorId = rememberedActorId(socket);
149
+ if (!actorId) return true;
150
+ try {
151
+ const rooms = await checks.audiences.resolveActorRooms(actorId);
152
+ return contributable.some((room) => rooms.has(room));
153
+ } catch {
154
+ // Revalidating it meets the same failure and disconnects it, as before.
155
+ return true;
156
+ }
157
+ }));
158
+ return sockets.filter((_socket, index) => entering[index]);
112
159
  }
113
160
 
114
161
  async function deliverLocal({ eventName, payload, targets }) {
115
- const checks = createPassChecks(authService, resolveActorRooms);
116
- await Promise.all(candidateSockets(targets).map(async (socket) => {
162
+ const checks = createPassChecks(authService, resolveActorsRooms);
163
+ const candidates = await candidateSockets(targets, checks);
164
+ checks.lookUpActorsRooms(candidates.map(rememberedActorId).filter(Boolean));
165
+ await Promise.all(candidates.map(async (socket) => {
117
166
  try {
118
167
  const actor = await revalidate(socket, checks);
119
168
  if (!socket.connected) return;
@@ -143,8 +192,10 @@ function createRealtimeDelivery({ io, database, logger, authService, audiences:
143
192
  function scheduleRevalidation() {
144
193
  if (stopped) return;
145
194
  revalidationTimer = setTimeout(async () => {
146
- const checks = createPassChecks(authService, resolveActorRooms);
147
- await Promise.all([...io.sockets.sockets.values()].map((socket) => revalidate(socket, checks)));
195
+ const checks = createPassChecks(authService, resolveActorsRooms);
196
+ const sockets = [...io.sockets.sockets.values()];
197
+ checks.lookUpActorsRooms(sockets.map(rememberedActorId).filter(Boolean));
198
+ await Promise.all(sockets.map((socket) => revalidate(socket, checks)));
148
199
  scheduleRevalidation();
149
200
  }, 30_000);
150
201
  revalidationTimer.unref();
@@ -1,6 +1,4 @@
1
1
  import { Server as SocketIoServer } from "socket.io";
2
- import { createAdapter as createSocketIoRedisAdapter } from "@socket.io/redis-adapter";
3
- import { createClient as createRedisClient } from "redis";
4
2
  import { normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
5
3
  import { toRequestPathname } from "@jskit-ai/kernel/shared/surface/paths";
6
4
 
@@ -111,8 +109,8 @@ function buildSocketIoRedisAdapterKey(redisNamespace = "") {
111
109
  * @param {string} [options.redisUrl]
112
110
  * @param {string} [options.redisNamespace]
113
111
  * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} options.logger Warned when a Redis connection fails.
114
- * @param {typeof createSocketIoRedisAdapter} [options.createRedisAdapter]
115
- * @param {typeof createRedisClient} [options.createRedisConnection]
112
+ * @param {typeof import("@socket.io/redis-adapter").createAdapter} [options.createRedisAdapter]
113
+ * @param {typeof import("redis").createClient} [options.createRedisConnection]
116
114
  */
117
115
  async function configureSocketIoRedisAdapter(
118
116
  io,
@@ -120,8 +118,8 @@ async function configureSocketIoRedisAdapter(
120
118
  redisUrl = "",
121
119
  redisNamespace = "",
122
120
  logger,
123
- createRedisAdapter = createSocketIoRedisAdapter,
124
- createRedisConnection = createRedisClient
121
+ createRedisAdapter,
122
+ createRedisConnection
125
123
  }
126
124
  ) {
127
125
  const normalizedRedisUrl = normalizeText(redisUrl);
@@ -136,7 +134,10 @@ async function configureSocketIoRedisAdapter(
136
134
  subClient: null
137
135
  });
138
136
  }
139
- const pubClient = createRedisConnection({
137
+ // Redis and its Socket.IO adapter, about 500 modules, load only for a server that uses them.
138
+ const connectRedis = createRedisConnection || (await import("redis")).createClient;
139
+ const adaptToRedis = createRedisAdapter || (await import("@socket.io/redis-adapter")).createAdapter;
140
+ const pubClient = connectRedis({
140
141
  url: normalizedRedisUrl
141
142
  });
142
143
  const subClient = pubClient.duplicate();
@@ -158,7 +159,7 @@ async function configureSocketIoRedisAdapter(
158
159
  await pubClient.connect();
159
160
  await subClient.connect();
160
161
  const adapterOptions = adapterKey ? { key: adapterKey } : undefined;
161
- io.adapter(createRedisAdapter(pubClient, subClient, adapterOptions));
162
+ io.adapter(adaptToRedis(pubClient, subClient, adapterOptions));
162
163
  } catch (error) {
163
164
  await closeSocketIoRedisConnections({
164
165
  pubClient,
@@ -6,13 +6,20 @@
6
6
  * The rooms an actor's contributed scopes name.
7
7
  * @typedef {(actorId: string) => Promise<Set<string>>} ActorRoomsResolver
8
8
  */
9
+ /**
10
+ * The rooms each actor's contributed scopes name, every asked actor included.
11
+ * @typedef {(actorIds: string[]) => Promise<Map<string, Set<string>>>} ActorsRoomsResolver
12
+ */
9
13
  /** @typedef {ReturnType<typeof import("./realtimeAudience.js").createAudienceContributors>} AudienceContributors */
10
14
 
11
15
  /**
12
- * A package that knows which scopes an actor belongs to.
16
+ * A package that knows which scopes actors belong to. It answers for many
17
+ * actors in one call (one query, not one per actor), and a lone actor is asked
18
+ * as a list of one.
13
19
  * @typedef {object} RealtimeAudienceContributor
14
20
  * @property {string} id
15
- * @property {(actorId: string) => unknown} resolveActorScopes Returns, or resolves to, the actor's scopes.
21
+ * @property {(actorIds: string[]) => Map<string, unknown> | Promise<Map<string, unknown>>} resolveActorsScopes
22
+ * Returns, or resolves to, each actor's scopes by actor id; an actor it leaves out has none.
16
23
  */
17
24
 
18
25
  export {};
@@ -12,6 +12,9 @@ const logger = { debug() {}, warn() {} };
12
12
  // A wait that fails instead of hanging when the event never comes.
13
13
  const arrival = (emitter, name) => once(emitter, name, { signal: AbortSignal.timeout(5_000) });
14
14
 
15
+ // A bulk contributor's answer: each asked actor's scopes.
16
+ const scopesByActor = (actorIds, scopesOf) => new Map(actorIds.map((actorId) => [actorId, scopesOf(actorId)]));
17
+
15
18
  // Real sockets whose session cookies name their actors. `checks` lists each
16
19
  // authentication's session cookie, so a test sees which sockets were checked,
17
20
  // `profileSyncs` those that asked the provider to sync the profile, and
@@ -184,7 +187,10 @@ test("membership changes and revoked logins take effect on the very next publish
184
187
  const audiences = createAudienceContributors();
185
188
  audiences.register({
186
189
  id: "test.memberships",
187
- resolveActorScopes: (actorId) => (memberships.get(actorId) || []).map((id) => ({ kind: "workspace", id }))
190
+ resolveActorsScopes: (actorIds) => scopesByActor(
191
+ actorIds,
192
+ (actorId) => (memberships.get(actorId) || []).map((id) => ({ kind: "workspace", id }))
193
+ )
188
194
  });
189
195
  const f = await signedInSockets(t, { audiences });
190
196
  f.sessions.set("alice", "1").set("bob", "2");
@@ -233,9 +239,9 @@ test("revalidation never syncs profiles, and one actor's logins share a room loo
233
239
  const audiences = createAudienceContributors();
234
240
  audiences.register({
235
241
  id: "test.memberships",
236
- resolveActorScopes() {
242
+ resolveActorsScopes(actorIds) {
237
243
  roomLookups += 1;
238
- return [{ kind: "workspace", id: 7 }];
244
+ return scopesByActor(actorIds, () => [{ kind: "workspace", id: 7 }]);
239
245
  }
240
246
  });
241
247
  const f = await signedInSockets(t, { audiences });
@@ -253,6 +259,63 @@ test("revalidation never syncs profiles, and one actor's logins share a room loo
253
259
  assert.equal(roomLookups, 1, "Both logins are Alice, so one publish looks up her rooms once");
254
260
  });
255
261
 
262
+ test("a workspace event checks only its members' logins, with one room lookup among 10 or 200 other sockets", async (t) => {
263
+ const members = new Set(["1", "2"]);
264
+ const lookups = [];
265
+ const audiences = createAudienceContributors();
266
+ audiences.register({
267
+ id: "test.memberships",
268
+ resolveActorsScopes(actorIds) {
269
+ lookups.push(actorIds.length);
270
+ return scopesByActor(actorIds, (actorId) => [{ kind: "workspace", id: members.has(actorId) ? 7 : 8 }]);
271
+ }
272
+ });
273
+ const f = await signedInSockets(t, { audiences });
274
+ f.sessions.set("alice", "1").set("bob", "2");
275
+ const alice = await f.connect("alice");
276
+ const bob = await f.connect("bob");
277
+ const outsiders = [];
278
+ const outsiderIds = [];
279
+
280
+ const publishes = [];
281
+ for (const count of [10, 200]) {
282
+ const connecting = [];
283
+ for (let index = outsiders.length; index < count; index += 1) {
284
+ f.sessions.set(`outsider-${index}`, String(100 + index));
285
+ outsiderIds.push(100 + index);
286
+ connecting.push(f.connect(`outsider-${index}`));
287
+ }
288
+ outsiders.push(...await Promise.all(connecting));
289
+
290
+ f.checks.length = 0;
291
+ lookups.length = 0;
292
+ const reached = [arrival(alice.client, "item.changed"), arrival(bob.client, "item.changed")];
293
+ await f.publish({ workspaceId: 7 });
294
+ await Promise.all(reached);
295
+ publishes.push({ checks: [...f.checks].sort(), lookups: [...lookups] });
296
+ }
297
+ assert.deepEqual(publishes, [
298
+ { checks: ["alice", "bob"], lookups: [12] },
299
+ { checks: ["alice", "bob"], lookups: [202] }
300
+ ], "Only the members' logins are checked, and one lookup answers for every online actor");
301
+
302
+ // Events on one connection arrive in order, so no outsider received the publishes.
303
+ const markers = outsiders.map(({ client }) => arrival(client, "marker"));
304
+ await f.publish({ userIds: outsiderIds }, "marker");
305
+ await Promise.all(markers);
306
+ assert.equal(outsiders.every(({ received }) => received.length === 0), true);
307
+
308
+ // Granted: an outsider joins the very next publish, through the same single lookup.
309
+ members.add("105");
310
+ f.checks.length = 0;
311
+ lookups.length = 0;
312
+ const granted = arrival(outsiders[5].client, "item.changed");
313
+ await f.publish({ workspaceId: 7 });
314
+ await granted;
315
+ assert.deepEqual(f.checks.sort(), ["alice", "bob", "outsider-5"]);
316
+ assert.deepEqual(lookups, [202]);
317
+ });
318
+
256
319
  test("a login whose session needs refreshing is dropped and refused until the client refreshes", async (t) => {
257
320
  const f = await signedInSockets(t, { requireAuthentication: false });
258
321
  f.sessions.set("alice", "1");
@@ -115,7 +115,10 @@ test("RealtimeProvider joins the rooms a registered audience contributor names",
115
115
  async authenticateRequest() { return { authenticated: true, actor: { id: "42" } }; }
116
116
  }, {
117
117
  id: "test.memberships",
118
- resolveActorScopes: (actorId) => [{ kind: "workspace_user", workspaceId: "7", userId: actorId }]
118
+ resolveActorsScopes: (actorIds) => new Map(actorIds.map((actorId) => [
119
+ actorId,
120
+ [{ kind: "workspace_user", workspaceId: "7", userId: actorId }]
121
+ ]))
119
122
  });
120
123
  const { connection } = await f.connect();
121
124
  assert.equal((await connection.readRequest()).user.id, "42");
@@ -374,12 +377,12 @@ test("socket audience bootstrap authenticates explicitly and joins contributed s
374
377
  const audiences = createAudienceContributors();
375
378
  audiences.register({
376
379
  id: "test.memberships",
377
- async resolveActorScopes(actorId) {
378
- assert.equal(actorId, "9");
379
- return [11, 12].flatMap((workspaceId) => [
380
+ async resolveActorsScopes(actorIds) {
381
+ assert.deepEqual(actorIds, ["9"]);
382
+ return new Map([["9", [11, 12].flatMap((workspaceId) => [
380
383
  { kind: "workspace", id: workspaceId },
381
- { kind: "workspace_user", workspaceId, userId: actorId }
382
- ]);
384
+ { kind: "workspace_user", workspaceId, userId: "9" }
385
+ ])]]);
383
386
  }
384
387
  });
385
388
  let connectionHandler = null;
@@ -438,10 +441,13 @@ test("socket revalidation leaves only the contributed rooms the actor lost", asy
438
441
  const audiences = createAudienceContributors();
439
442
  audiences.register({
440
443
  id: "test.memberships",
441
- resolveActorScopes: () => memberships.map((id) => ({ kind: "workspace", id }))
444
+ resolveActorsScopes: (actorIds) => new Map(actorIds.map((actorId) => [
445
+ actorId,
446
+ memberships.map((id) => ({ kind: "workspace", id }))
447
+ ]))
442
448
  });
443
- assert.throws(() => audiences.register({ id: "test.memberships", resolveActorScopes() {} }), /already registered/);
444
- assert.throws(() => audiences.register({ id: "test.other" }), /requires resolveActorScopes/);
449
+ assert.throws(() => audiences.register({ id: "test.memberships", resolveActorsScopes() {} }), /already registered/);
450
+ assert.throws(() => audiences.register({ id: "test.other" }), /requires resolveActorsScopes/);
445
451
  const rooms = new Set(["clients", "users", "user:9", "workspace:legacy-app-room"]);
446
452
  const socket = {
447
453
  data: {},
@@ -0,0 +1,28 @@
1
+ import assert from "node:assert/strict";
2
+ import { registerHooks } from "node:module";
3
+ import test from "node:test";
4
+
5
+ // Every module this process loads from here on; the realtime modules are imported after the hook.
6
+ const loadedUrls = [];
7
+ registerHooks({
8
+ load(url, context, nextLoad) {
9
+ loadedUrls.push(url);
10
+ return nextLoad(url, context);
11
+ }
12
+ });
13
+ const redisModules = () =>
14
+ loadedUrls.filter((url) => /\/node_modules\/(?:redis|@redis\/[^/]+|@socket\.io\/redis-adapter)\//u.test(url));
15
+
16
+ test("a realtime server without Redis loads none of Redis's modules", async () => {
17
+ const { RealtimeProvider } = await import("../src/server/RealtimeProvider.js");
18
+ const { configureSocketIoRedisAdapter } = await import("../src/server/runtime.js");
19
+ assert.equal(RealtimeProvider.provides.realtime, "runtime.realtime");
20
+
21
+ const memory = await configureSocketIoRedisAdapter({ adapter() {} }, { redisUrl: "", logger: { warn() {} } });
22
+ assert.equal(memory.enabled, false);
23
+ assert.deepEqual(redisModules(), []);
24
+
25
+ // The hook does see Redis when something loads it.
26
+ await import("redis");
27
+ assert.ok(redisModules().length > 0);
28
+ });