@jskit-ai/realtime 0.2.6 → 0.2.8

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.
@@ -0,0 +1,160 @@
1
+ import {
2
+ authenticationRequiredError,
3
+ createAudienceContributors,
4
+ createSocketRequest,
5
+ realtimeAuthenticationRequired,
6
+ registerSocketAudienceBootstrap,
7
+ revalidateSocket
8
+ } from "./realtimeAudience.js";
9
+ import { createRealtimeDelivery, matchesRealtimeEvent } from "./realtimeDelivery.js";
10
+ import { announceServedClientBuild } from "./servedClientBuild.js";
11
+ import {
12
+ closeSocketIoRedisConnections,
13
+ closeSocketIoServer,
14
+ configureSocketIoRedisAdapter,
15
+ countConnectedClients
16
+ } from "./runtime.js";
17
+
18
+ /** @typedef {import("@jskit-ai/auth-core/server/types").AuthService} AuthService */
19
+ /** @typedef {import("@jskit-ai/database-runtime/server/types").RuntimeDatabase} RuntimeDatabase */
20
+ /** @typedef {import("@jskit-ai/kernel/server/types").RuntimeAppRoot} RuntimeAppRoot */
21
+ /** @typedef {import("@jskit-ai/kernel/server/types").RuntimeEvents} RuntimeEvents */
22
+ /** @typedef {import("@jskit-ai/kernel/server/types").RuntimeLogger} RuntimeLogger */
23
+
24
+ /**
25
+ * The `runtime.realtime` capability over one Socket.IO server. It starts
26
+ * delivering once every provider has booted, because the auth service may be
27
+ * ready only then, and stops with the runtime.
28
+ * @param {object} dependencies
29
+ * @param {import("socket.io").Server} dependencies.io
30
+ * @param {RuntimeLogger} dependencies.logger
31
+ * @param {AuthService | null} dependencies.authService
32
+ * @param {RuntimeDatabase | null} dependencies.database
33
+ * @param {RuntimeEvents} dependencies.events
34
+ * @param {RuntimeAppRoot | null} dependencies.appRoot
35
+ * @param {{ redisUrl: string, redisNamespace: string }} dependencies.redis
36
+ */
37
+ function createRealtimeCapability({ io, logger, authService, database, events, appRoot, redis }) {
38
+ const audiences = createAudienceContributors();
39
+ const connectionListeners = new Set();
40
+ let authenticationRequired = false;
41
+ /** @type {ReturnType<typeof createRealtimeDelivery> | null} */
42
+ let delivery = null;
43
+ /** @type {Awaited<ReturnType<typeof configureSocketIoRedisAdapter>> | null} */
44
+ let redisConnection = null;
45
+
46
+ function onConnection(listener) {
47
+ // readable-check: allow method-probe - input validation: an application hands over its connection listener
48
+ if (typeof listener !== "function") throw new TypeError("Realtime connection listener must be a function.");
49
+ const releases = new Map();
50
+ function attach(socket) {
51
+ if (releases.has(socket)) return;
52
+ let detach;
53
+ async function readRequest() {
54
+ const request = createSocketRequest(socket);
55
+ const actor = await revalidateSocket({ socket, request, authService, audiences });
56
+ if (!socket.connected || (!actor && realtimeAuthenticationRequired(authService))) {
57
+ throw authenticationRequiredError();
58
+ }
59
+ if (actor) request.user = actor;
60
+ return request;
61
+ }
62
+ function release() {
63
+ socket.off("disconnect", release);
64
+ releases.delete(socket);
65
+ try { detach?.(); }
66
+ catch (error) {
67
+ logger.warn({ error: String(error?.message || error) }, "Realtime connection cleanup failed.");
68
+ }
69
+ }
70
+ try {
71
+ detach = listener({
72
+ socket,
73
+ // Hosts authorize this real connection request through their own
74
+ // action boundary. Reading it alone does not grant local access.
75
+ readRequest,
76
+ async authenticate() {
77
+ const request = await readRequest();
78
+ if (!request.user) throw authenticationRequiredError();
79
+ return request;
80
+ }
81
+ });
82
+ // readable-check: allow method-probe - input validation: an application's listener returns its cleanup
83
+ if (detach != null && typeof detach !== "function") {
84
+ throw new TypeError("Realtime connection listeners must return a cleanup function or undefined.");
85
+ }
86
+ releases.set(socket, release);
87
+ socket.on("disconnect", release);
88
+ } catch (error) {
89
+ logger.warn({ error: String(error?.message || error) }, "Realtime connection listener failed.");
90
+ }
91
+ }
92
+ function stopListening() {
93
+ io.off("connection", attach);
94
+ for (const release of [...releases.values()]) release();
95
+ connectionListeners.delete(stopListening);
96
+ }
97
+ connectionListeners.add(stopListening);
98
+ io.on("connection", attach);
99
+ for (const socket of io.sockets.sockets.values()) attach(socket);
100
+ return stopListening;
101
+ }
102
+
103
+ /**
104
+ * A package that knows which scopes (kind "user", "workspace" or
105
+ * "workspace_user") an actor belongs to registers them during setup; sockets
106
+ * join, and on revalidation leave, exactly the rooms its scopes name.
107
+ * @param {import("./types.js").RealtimeAudienceContributor} contributor
108
+ */
109
+ function registerAudienceContributor(contributor) {
110
+ audiences.register(contributor);
111
+ }
112
+
113
+ function diagnostics() {
114
+ return Object.freeze({
115
+ authenticationRequired,
116
+ connectedClients: countConnectedClients(io),
117
+ redisConfigured: redisConnection?.enabled === true
118
+ });
119
+ }
120
+
121
+ /**
122
+ * Authenticates each socket and delivers every event that names a socket
123
+ * event, to the other servers too when Redis is configured.
124
+ */
125
+ async function start() {
126
+ delivery = createRealtimeDelivery({ io, database, logger, authService, audiences });
127
+ authenticationRequired = realtimeAuthenticationRequired(authService);
128
+ registerSocketAudienceBootstrap({ io, logger, authService, audiences });
129
+ announceServedClientBuild({ io, appRoot, logger });
130
+ redisConnection = await configureSocketIoRedisAdapter(io, { logger, ...redis });
131
+ delivery.start({ redisConfigured: redisConnection.enabled });
132
+ events.register({
133
+ id: "runtime.realtime.delivery",
134
+ matches: matchesRealtimeEvent,
135
+ handle: delivery.handle
136
+ });
137
+ }
138
+
139
+ /**
140
+ * Closes Socket.IO's part of the HTTP server; the server's owner closes the server.
141
+ */
142
+ async function stop() {
143
+ for (const release of [...connectionListeners]) release();
144
+ if (delivery) delivery.stop();
145
+ await closeSocketIoServer(io);
146
+ if (redisConnection) await closeSocketIoRedisConnections(redisConnection);
147
+ authenticationRequired = false;
148
+ redisConnection = null;
149
+ }
150
+
151
+ return Object.freeze({
152
+ onConnection,
153
+ registerAudienceContributor,
154
+ diagnostics,
155
+ start,
156
+ stop
157
+ });
158
+ }
159
+
160
+ export { createRealtimeCapability };
@@ -1,10 +1,15 @@
1
1
  import { normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
2
2
  import { resolveAudienceTargets, revalidateSocket } from "./realtimeAudience.js";
3
+ import { countConnectedClients } from "./runtime.js";
4
+
5
+ /** @typedef {import("@jskit-ai/auth-core/server/types").AuthService} AuthService */
6
+ /** @typedef {import("./types.js").ActorRoomsResolver} ActorRoomsResolver */
7
+ /** @typedef {import("./types.js").AudienceContributors} AudienceContributors */
3
8
 
4
9
  const DELIVERY_EVENT = "jskit:realtime:delivery";
5
10
 
6
11
  function publicRealtimePayload(event) {
7
- const { realtime } = event && typeof event === "object" ? event : {};
12
+ const { realtime } = event;
8
13
  const canonical = {};
9
14
  for (const key of [
10
15
  "type", "source", "entity", "operation", "entityId", "scope", "actorId",
@@ -16,11 +21,22 @@ function publicRealtimePayload(event) {
16
21
  if (payload != null && (typeof payload !== "object" || Array.isArray(payload))) {
17
22
  throw new TypeError("Realtime event payload must be an object when provided.");
18
23
  }
19
- return Object.freeze({ ...(payload || {}), ...canonical });
24
+ return Object.freeze({
25
+ ...(payload || {}),
26
+ ...canonical
27
+ });
20
28
  }
21
29
 
22
- // One answer per question within one pass.
23
- function sharedWithinPass(load, keyOf = (value) => value) {
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
+ /** One answer per question within one pass. */
39
+ function sharedWithinPass(load, keyOf = valueAsKey) {
24
40
  const answers = new Map();
25
41
  return (value) => {
26
42
  const key = keyOf(value);
@@ -29,36 +45,43 @@ function sharedWithinPass(load, keyOf = (value) => value) {
29
45
  };
30
46
  }
31
47
 
32
- // The checks of one publish or 30-second pass. Identical socket requests share
33
- // one authentication (the auth service sees only the request), and sockets of
34
- // one actor share its contributed rooms. Revalidation asks only who is signed
35
- // in, so the provider reads the app profile instead of synchronizing it, and
36
- // never refreshes a session the socket could not store.
37
- function createPassChecks(authService, audiences) {
48
+ /**
49
+ * The checks of one publish or 30-second pass. Identical socket requests share
50
+ * 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.
54
+ * @param {AuthService} authService
55
+ * @param {ActorRoomsResolver} resolveActorRooms
56
+ */
57
+ function createPassChecks(authService, resolveActorRooms) {
38
58
  return {
39
59
  authenticateRequest: sharedWithinPass(
40
60
  (request) => authService.authenticateRequest(request, { syncProfile: false, refreshSession: false }),
41
61
  JSON.stringify
42
62
  ),
43
- audiences: audiences && { resolveActorRooms: sharedWithinPass((actorId) => audiences.resolveActorRooms(actorId)) }
63
+ audiences: { resolveActorRooms: sharedWithinPass(resolveActorRooms) }
44
64
  };
45
65
  }
46
66
 
47
- function createRealtimeDelivery({ io, database = null, logger, authService = null, audiences = null }) {
48
- if (!io || typeof io.emit !== "function" || typeof io.to !== "function") {
49
- throw new TypeError("Realtime delivery requires a Socket.IO server.");
50
- }
51
- if (!logger || typeof logger.warn !== "function") {
52
- throw new TypeError("Realtime delivery requires a logger.");
53
- }
54
-
55
- const guarded = typeof authService?.authenticateRequest === "function";
56
- if (authService?.realtime?.authorizeEvent != null && typeof authService.realtime.authorizeEvent !== "function") {
67
+ /**
68
+ * @param {object} dependencies
69
+ * @param {import("socket.io").Server} dependencies.io
70
+ * @param {import("@jskit-ai/database-runtime/server/types").RuntimeDatabase | null} dependencies.database Absent when no runtime.database is installed.
71
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
72
+ * @param {AuthService | null} dependencies.authService Absent when no auth.service is installed.
73
+ * @param {AudienceContributors} dependencies.audiences The rooms revalidation may make a socket join.
74
+ * With no contributors registered, a socket stays in the rooms it already has.
75
+ */
76
+ function createRealtimeDelivery({ io, database, logger, authService, audiences: { mayContribute, resolveActorRooms } }) {
77
+ // With an auth.service, each socket is revalidated before it receives an event;
78
+ // without one, events go straight to their rooms.
79
+ const guarded = Boolean(authService);
80
+ const authorizeEvent = authService?.realtime?.authorizeEvent ?? null;
81
+ // readable-check: allow method-probe - input validation: an auth provider's realtime policy may name authorizeEvent()
82
+ if (authorizeEvent !== null && typeof authorizeEvent !== "function") {
57
83
  throw new TypeError("Realtime authorizeEvent must be a function.");
58
84
  }
59
- if ((authService?.realtime?.requireAuthentication === true || authService?.realtime?.authorizeEvent) && !guarded) {
60
- throw new TypeError("Realtime authorization requires auth.service.authenticateRequest().");
61
- }
62
85
  let redisEnabled = false;
63
86
  let revalidationTimer = null;
64
87
  let stopped = false;
@@ -78,22 +101,24 @@ function createRealtimeDelivery({ io, database = null, logger, authService = nul
78
101
  }
79
102
  }
80
103
 
81
- // A socket outside every target room can enter one only by revalidation
82
- // joining a contributed room; otherwise checking it cannot change delivery.
104
+ /**
105
+ * A socket outside every target room can enter one only by revalidation
106
+ * joining a contributed room; otherwise checking it cannot change delivery.
107
+ */
83
108
  function candidateSockets(targets) {
84
109
  const sockets = [...io.sockets.sockets.values()];
85
- if (targets.broadcastAllClients || targets.rooms.some((room) => audiences?.mayContribute(room))) return sockets;
110
+ if (targets.broadcastAllClients || targets.rooms.some((room) => mayContribute(room))) return sockets;
86
111
  return sockets.filter((socket) => targets.rooms.some((room) => socket.rooms.has(room)));
87
112
  }
88
113
 
89
114
  async function deliverLocal({ eventName, payload, targets }) {
90
- const checks = createPassChecks(authService, audiences);
115
+ const checks = createPassChecks(authService, resolveActorRooms);
91
116
  await Promise.all(candidateSockets(targets).map(async (socket) => {
92
117
  try {
93
118
  const actor = await revalidate(socket, checks);
94
119
  if (!socket.connected) return;
95
120
  if (!targets.broadcastAllClients && !targets.rooms.some((room) => socket.rooms.has(room))) return;
96
- if (typeof authService.realtime?.authorizeEvent === "function") {
121
+ if (authorizeEvent) {
97
122
  const authorized = await authService.realtime.authorizeEvent({
98
123
  actor,
99
124
  event: { name: eventName, payload }
@@ -118,60 +143,72 @@ function createRealtimeDelivery({ io, database = null, logger, authService = nul
118
143
  function scheduleRevalidation() {
119
144
  if (stopped) return;
120
145
  revalidationTimer = setTimeout(async () => {
121
- const checks = createPassChecks(authService, audiences);
146
+ const checks = createPassChecks(authService, resolveActorRooms);
122
147
  await Promise.all([...io.sockets.sockets.values()].map((socket) => revalidate(socket, checks)));
123
148
  scheduleRevalidation();
124
149
  }, 30_000);
125
150
  revalidationTimer.unref();
126
151
  }
127
152
 
128
- return Object.freeze({
129
- start({ redisConfigured = false } = {}) {
130
- redisEnabled = redisConfigured;
153
+ function start({ redisConfigured = false } = {}) {
154
+ redisEnabled = redisConfigured;
155
+ if (guarded) {
156
+ io.on(DELIVERY_EVENT, receive);
157
+ scheduleRevalidation();
158
+ }
159
+ }
160
+
161
+ function stop() {
162
+ stopped = true;
163
+ clearTimeout(revalidationTimer);
164
+ if (guarded) io.off(DELIVERY_EVENT, receive);
165
+ }
166
+
167
+ /** @param {object} event A published runtime event whose realtime part names a socket event (see matchesRealtimeEvent). */
168
+ async function handle(event) {
169
+ try {
170
+ const eventName = normalizeText(event.realtime.event);
171
+ const targets = await resolveAudienceTargets(event.realtime.audience, event, { database, logger });
172
+ const payload = publicRealtimePayload(event);
131
173
  if (guarded) {
132
- io.on(DELIVERY_EVENT, receive);
133
- scheduleRevalidation();
134
- }
135
- },
136
- stop() {
137
- stopped = true;
138
- clearTimeout(revalidationTimer);
139
- if (guarded) io.off(DELIVERY_EVENT, receive);
140
- },
141
- async handle(event = {}) {
142
- try {
143
- const eventName = normalizeText(event?.realtime?.event);
144
- if (!eventName) return;
145
- const targets = await resolveAudienceTargets(event.realtime.audience, event, { database, logger });
146
- const payload = publicRealtimePayload(event);
147
- if (guarded) {
148
- const envelope = { eventName, payload, targets };
149
- if (redisEnabled) {
150
- try {
151
- io.serverSideEmit(DELIVERY_EVENT, envelope);
152
- } catch (error) {
153
- logger.warn({ socketEvent: eventName, error: String(error?.message || error) }, "Realtime peer publication failed.");
154
- }
174
+ const envelope = { eventName, payload, targets };
175
+ if (redisEnabled) {
176
+ try {
177
+ io.serverSideEmit(DELIVERY_EVENT, envelope);
178
+ } catch (error) {
179
+ logger.warn({ socketEvent: eventName, error: String(error?.message || error) }, "Realtime peer publication failed.");
155
180
  }
156
- await deliverLocal(envelope);
157
- } else if (targets.broadcastAllClients) {
158
- io.emit(eventName, payload);
159
- } else if (targets.rooms.length) {
160
- io.to(targets.rooms).emit(eventName, payload);
161
181
  }
162
- logger.debug({
163
- socketEvent: eventName,
164
- rooms: targets.rooms,
165
- broadcastAllClients: targets.broadcastAllClients,
166
- connectedClients: Number.isInteger(Number(io?.engine?.clientsCount))
167
- ? Number(io.engine.clientsCount)
168
- : null
169
- }, "Realtime delivered an action event.");
170
- } catch (error) {
171
- logger.warn({ socketEvent: event?.realtime?.event, error: String(error?.message || error) }, "Realtime delivery failed; the domain mutation remains successful.");
182
+ await deliverLocal(envelope);
183
+ } else if (targets.broadcastAllClients) {
184
+ io.emit(eventName, payload);
185
+ } else if (targets.rooms.length) {
186
+ io.to(targets.rooms).emit(eventName, payload);
172
187
  }
188
+ logger.debug({
189
+ socketEvent: eventName,
190
+ rooms: targets.rooms,
191
+ broadcastAllClients: targets.broadcastAllClients,
192
+ connectedClients: countConnectedClients(io)
193
+ }, "Realtime delivered an action event.");
194
+ } catch (error) {
195
+ logger.warn({ socketEvent: event.realtime?.event, error: String(error?.message || error) }, "Realtime delivery failed; the domain mutation remains successful.");
173
196
  }
197
+ }
198
+
199
+ return Object.freeze({
200
+ start,
201
+ stop,
202
+ handle
174
203
  });
175
204
  }
176
205
 
177
- export { createRealtimeDelivery };
206
+ /**
207
+ * Whether a published runtime event names a socket event for realtime to deliver.
208
+ * @param {object} event
209
+ */
210
+ function matchesRealtimeEvent(event) {
211
+ return Boolean(normalizeText(event.realtime?.event));
212
+ }
213
+
214
+ export { createRealtimeDelivery, matchesRealtimeEvent };
@@ -2,22 +2,15 @@ import { Server as SocketIoServer } from "socket.io";
2
2
  import { createAdapter as createSocketIoRedisAdapter } from "@socket.io/redis-adapter";
3
3
  import { createClient as createRedisClient } from "redis";
4
4
  import { normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
5
- import { normalizePathname } from "@jskit-ai/kernel/shared/surface/paths";
5
+ import { toRequestPathname } from "@jskit-ai/kernel/shared/surface/paths";
6
6
 
7
7
  const SOCKET_IO_PATH = "/socket.io";
8
8
  const REDIS_URL_ENV_KEY = "REDIS_URL";
9
9
  const REDIS_NAMESPACE_ENV_KEY = "REDIS_NAMESPACE";
10
10
 
11
- function toRequestPathname(urlValue) {
12
- const rawUrl = String(urlValue || "").trim() || "/";
13
- try {
14
- return normalizePathname(new URL(rawUrl, "http://localhost").pathname || "/");
15
- } catch {
16
- return normalizePathname(rawUrl.split("?")[0] || "/");
17
- }
18
- }
19
-
11
+ /** @param {import("@jskit-ai/kernel/server/types").RuntimeFastify | null} fastify */
20
12
  function registerSocketIoUpgradeHandoff(fastify) {
13
+ // readable-check: allow method-probe - input validation: a host that hands over only its HTTP server ({ server }) has no addHook()
21
14
  if (typeof fastify?.addHook !== "function") return;
22
15
  fastify.addHook("onRequest", async (request, reply) => {
23
16
  if (request?.ws !== true) return;
@@ -38,12 +31,20 @@ function resolveHttpServer({ httpServer = null, fastify = null } = {}) {
38
31
  throw new Error("createSocketIoServer requires httpServer or fastify.server.");
39
32
  }
40
33
 
34
+ /**
35
+ * @param {object} [options]
36
+ * @param {import("node:http").Server | null} [options.httpServer] The HTTP server to attach to; Fastify's when absent.
37
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeFastify | null} [options.fastify]
38
+ * @param {Partial<import("socket.io").ServerOptions>} [options.options]
39
+ * @param {typeof SocketIoServer} [options.ServerCtor]
40
+ */
41
41
  function createSocketIoServer({
42
42
  httpServer = null,
43
43
  fastify = null,
44
44
  options = {},
45
45
  ServerCtor = SocketIoServer
46
46
  } = {}) {
47
+ // readable-check: allow method-probe - input validation: a caller may pass its own Socket.IO Server class
47
48
  if (typeof ServerCtor !== "function") {
48
49
  throw new Error("createSocketIoServer requires a valid socket.io Server constructor.");
49
50
  }
@@ -52,11 +53,10 @@ function createSocketIoServer({
52
53
  httpServer,
53
54
  fastify
54
55
  });
55
- const source = options && typeof options === "object" && !Array.isArray(options) ? options : {};
56
56
  const normalizedOptions = {
57
57
  // Application WebSocket routes may still be authorizing their upgrades.
58
58
  destroyUpgrade: false,
59
- ...source,
59
+ ...options,
60
60
  path: SOCKET_IO_PATH
61
61
  };
62
62
  registerSocketIoUpgradeHandoff(fastify);
@@ -79,14 +79,22 @@ async function closeSocketIoServer(io) {
79
79
  await io.sockets.adapter.close();
80
80
  }
81
81
 
82
- function resolveRealtimeRedisUrl(env = {}) {
83
- const source = env && typeof env === "object" && !Array.isArray(env) ? env : {};
84
- return normalizeText(source[REDIS_URL_ENV_KEY]);
82
+ /** @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env */
83
+ function resolveRealtimeRedisUrl(env) {
84
+ return normalizeText(env[REDIS_URL_ENV_KEY]);
85
85
  }
86
86
 
87
- function resolveRealtimeRedisNamespace(env = {}) {
88
- const source = env && typeof env === "object" && !Array.isArray(env) ? env : {};
89
- return normalizeText(source[REDIS_NAMESPACE_ENV_KEY]);
87
+ /** @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env */
88
+ function resolveRealtimeRedisNamespace(env) {
89
+ return normalizeText(env[REDIS_NAMESPACE_ENV_KEY]);
90
+ }
91
+
92
+ /**
93
+ * How many clients the Socket.IO engine holds, or null before it is attached.
94
+ * @param {import("socket.io").Server} io
95
+ */
96
+ function countConnectedClients(io) {
97
+ return Number.isInteger(Number(io.engine?.clientsCount)) ? Number(io.engine.clientsCount) : null;
90
98
  }
91
99
 
92
100
  function buildSocketIoRedisAdapterKey(redisNamespace = "") {
@@ -97,15 +105,24 @@ function buildSocketIoRedisAdapterKey(redisNamespace = "") {
97
105
  return `${normalizedRedisNamespace}:socket.io`;
98
106
  }
99
107
 
108
+ /**
109
+ * @param {import("socket.io").Server} io
110
+ * @param {object} options
111
+ * @param {string} [options.redisUrl]
112
+ * @param {string} [options.redisNamespace]
113
+ * @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]
116
+ */
100
117
  async function configureSocketIoRedisAdapter(
101
118
  io,
102
119
  {
103
120
  redisUrl = "",
104
121
  redisNamespace = "",
105
- logger = console,
122
+ logger,
106
123
  createRedisAdapter = createSocketIoRedisAdapter,
107
124
  createRedisConnection = createRedisClient
108
- } = {}
125
+ }
109
126
  ) {
110
127
  const normalizedRedisUrl = normalizeText(redisUrl);
111
128
  const adapterKey = buildSocketIoRedisAdapterKey(redisNamespace);
@@ -119,10 +136,6 @@ async function configureSocketIoRedisAdapter(
119
136
  subClient: null
120
137
  });
121
138
  }
122
- if (!io || typeof io.adapter !== "function") {
123
- throw new Error("configureSocketIoRedisAdapter requires socket.io server instance with adapter().");
124
- }
125
-
126
139
  const pubClient = createRedisConnection({
127
140
  url: normalizedRedisUrl
128
141
  });
@@ -164,18 +177,25 @@ async function configureSocketIoRedisAdapter(
164
177
  });
165
178
  }
166
179
 
167
- async function closeSocketIoRedisConnections({ pubClient = null, subClient = null } = {}) {
180
+ /**
181
+ * @param {object} connections
182
+ * @param {object | null} connections.pubClient
183
+ * @param {object | null} connections.subClient
184
+ */
185
+ async function closeSocketIoRedisConnections({ pubClient, subClient }) {
168
186
  const connections = [subClient, pubClient];
169
187
  for (const connection of connections) {
170
188
  if (!connection) {
171
189
  continue;
172
190
  }
191
+ // readable-check: allow method-probe - platform object: a Redis client closes with quit(), or with disconnect() where it has no quit()
173
192
  if (typeof connection.quit === "function") {
174
193
  try {
175
194
  await connection.quit();
176
195
  } catch {}
177
196
  continue;
178
197
  }
198
+ // readable-check: allow method-probe - platform object: a Redis client closes with quit(), or with disconnect() where it has no quit()
179
199
  if (typeof connection.disconnect === "function") {
180
200
  try {
181
201
  await connection.disconnect();
@@ -192,5 +212,6 @@ export {
192
212
  resolveRealtimeRedisUrl,
193
213
  resolveRealtimeRedisNamespace,
194
214
  configureSocketIoRedisAdapter,
195
- closeSocketIoRedisConnections
215
+ closeSocketIoRedisConnections,
216
+ countConnectedClients
196
217
  };
@@ -1,11 +1,17 @@
1
1
  import { readServedClientBuildId } from "@jskit-ai/kernel/server/support";
2
2
  import { SERVED_CLIENT_BUILD_EVENT } from "../shared/servedClientBuild.js";
3
3
 
4
- // Each connection, including a reconnection to a restarted server, learns the
5
- // client build this server serves now. A page running an older build can then
6
- // offer a reload without polling.
4
+ /**
5
+ * Each connection, including a reconnection to a restarted server, learns the
6
+ * client build this server serves now. A page running an older build can then
7
+ * offer a reload without polling.
8
+ * @param {object} dependencies
9
+ * @param {import("socket.io").Server} dependencies.io
10
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeAppRoot | null} dependencies.appRoot Absent when no runtime.app-root is installed.
11
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
12
+ */
7
13
  function announceServedClientBuild({ io, appRoot, logger }) {
8
- if (!appRoot || typeof io?.on !== "function") return;
14
+ if (!appRoot) return;
9
15
  io.on("connection", async (socket) => {
10
16
  try {
11
17
  const buildId = await readServedClientBuildId({ appRoot });
@@ -0,0 +1,18 @@
1
+ // The type of the `runtime.realtime` capability, for features that require it, and the
2
+ // types realtime's modules share.
3
+
4
+ /** @typedef {ReturnType<typeof import("./realtimeCapability.js").createRealtimeCapability>} RuntimeRealtime */
5
+ /**
6
+ * The rooms an actor's contributed scopes name.
7
+ * @typedef {(actorId: string) => Promise<Set<string>>} ActorRoomsResolver
8
+ */
9
+ /** @typedef {ReturnType<typeof import("./realtimeAudience.js").createAudienceContributors>} AudienceContributors */
10
+
11
+ /**
12
+ * A package that knows which scopes an actor belongs to.
13
+ * @typedef {object} RealtimeAudienceContributor
14
+ * @property {string} id
15
+ * @property {(actorId: string) => unknown} resolveActorScopes Returns, or resolves to, the actor's scopes.
16
+ */
17
+
18
+ export {};