@jskit-ai/realtime 0.2.0 → 0.2.1
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/package.json +2 -2
- package/patterns/realtime-application/example/package.json +2 -2
- package/src/client/RealtimeClientProvider.js +43 -0
- package/src/server/RealtimeProvider.js +4 -1
- package/src/server/realtimeAudience.js +4 -1
- package/src/server/runtime.js +11 -14
- package/src/server/servedClientBuild.js +19 -0
- package/src/shared/servedClientBuild.js +5 -0
- package/test/authorization.test.js +6 -1
- package/test/providerRuntime.test.js +81 -2
- package/test/servedClientBuild.test.js +131 -0
- package/test/serverRuntime.test.js +14 -8
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jskit-ai/realtime",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"test": "node --test --test-concurrency=1"
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
"socket.io-client": "^4.8.3"
|
|
22
22
|
},
|
|
23
23
|
"peerDependencies": {
|
|
24
|
-
"@jskit-ai/kernel": "0.2.
|
|
24
|
+
"@jskit-ai/kernel": "0.2.1",
|
|
25
25
|
"vue": "^3.5.13"
|
|
26
26
|
},
|
|
27
27
|
"description": "Thin, generic realtime runtime wrappers for socket.io server and client.",
|
|
@@ -5,6 +5,7 @@ import { getClientAppConfig, resolveClientBootstrapDebugEnabled, resolveMobileCo
|
|
|
5
5
|
import RealtimeConnectionIndicator from "./components/RealtimeConnectionIndicator.js";
|
|
6
6
|
import { createSocketIoClient, disconnectSocketIoClient } from "./runtime.js";
|
|
7
7
|
import { attachSocketConnectionRecovery } from "./connectionRecovery.js";
|
|
8
|
+
import { SERVED_CLIENT_BUILD_EVENT } from "../shared/servedClientBuild.js";
|
|
8
9
|
|
|
9
10
|
function resolveRealtimeClientConfig({ env = {}, mobile = null } = {}) {
|
|
10
11
|
const appConfig = normalizeObject(getClientAppConfig());
|
|
@@ -45,6 +46,7 @@ function createRealtimeClient({ config, loggerInput } = {}) {
|
|
|
45
46
|
url: config.url,
|
|
46
47
|
options: config.options
|
|
47
48
|
});
|
|
49
|
+
const servedClientBuild = trackServedClientBuild(socket, logger);
|
|
48
50
|
const detach = [];
|
|
49
51
|
let initialized = false;
|
|
50
52
|
|
|
@@ -101,6 +103,7 @@ function createRealtimeClient({ config, loggerInput } = {}) {
|
|
|
101
103
|
release();
|
|
102
104
|
} catch {}
|
|
103
105
|
}
|
|
106
|
+
servedClientBuild.dispose();
|
|
104
107
|
disconnectSocketIoClient(socket);
|
|
105
108
|
initialized = false;
|
|
106
109
|
}
|
|
@@ -109,10 +112,50 @@ function createRealtimeClient({ config, loggerInput } = {}) {
|
|
|
109
112
|
config,
|
|
110
113
|
dispose,
|
|
111
114
|
initialize,
|
|
115
|
+
onServedClientBuild: servedClientBuild.subscribe,
|
|
112
116
|
socket
|
|
113
117
|
});
|
|
114
118
|
}
|
|
115
119
|
|
|
120
|
+
// The server names the client build it serves on every connection. Listening
|
|
121
|
+
// from the socket's creation keeps the first announcement even when it arrives
|
|
122
|
+
// before anything subscribes; a subscriber receives the latest one at once.
|
|
123
|
+
function trackServedClientBuild(socket, logger) {
|
|
124
|
+
const listeners = new Set();
|
|
125
|
+
let buildId = "";
|
|
126
|
+
|
|
127
|
+
function notify(listener) {
|
|
128
|
+
try {
|
|
129
|
+
listener(buildId);
|
|
130
|
+
} catch (error) {
|
|
131
|
+
logger.warn({ error: String(error?.message || error) }, "Served client build listener failed.");
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function onServedClientBuild(payload) {
|
|
136
|
+
buildId = normalizeText(payload?.buildId);
|
|
137
|
+
if (buildId) {
|
|
138
|
+
for (const listener of [...listeners]) notify(listener);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
socket.on?.(SERVED_CLIENT_BUILD_EVENT, onServedClientBuild);
|
|
143
|
+
return Object.freeze({
|
|
144
|
+
subscribe(listener) {
|
|
145
|
+
if (typeof listener !== "function") {
|
|
146
|
+
throw new TypeError("onServedClientBuild requires a listener function.");
|
|
147
|
+
}
|
|
148
|
+
listeners.add(listener);
|
|
149
|
+
if (buildId) notify(listener);
|
|
150
|
+
return () => listeners.delete(listener);
|
|
151
|
+
},
|
|
152
|
+
dispose() {
|
|
153
|
+
socket.off?.(SERVED_CLIENT_BUILD_EVENT, onServedClientBuild);
|
|
154
|
+
listeners.clear();
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
|
|
116
159
|
const RealtimeClientProvider = defineProvider({
|
|
117
160
|
id: "runtime.realtime.client",
|
|
118
161
|
requires: {
|
|
@@ -2,6 +2,7 @@ import { defineProvider } from "@jskit-ai/kernel/shared/capabilities";
|
|
|
2
2
|
import { createProviderLogger } from "@jskit-ai/kernel/shared/support/providerLogger";
|
|
3
3
|
import { normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
|
|
4
4
|
import { createRealtimeDelivery } from "./realtimeDelivery.js";
|
|
5
|
+
import { announceServedClientBuild } from "./servedClientBuild.js";
|
|
5
6
|
import {
|
|
6
7
|
createAudienceContributors,
|
|
7
8
|
createSocketRequest,
|
|
@@ -130,6 +131,7 @@ const RealtimeProvider = defineProvider({
|
|
|
130
131
|
logger: "runtime.logger"
|
|
131
132
|
},
|
|
132
133
|
optional: {
|
|
134
|
+
appRoot: "runtime.app-root",
|
|
133
135
|
authService: "auth.service",
|
|
134
136
|
database: "runtime.database"
|
|
135
137
|
},
|
|
@@ -152,7 +154,7 @@ const RealtimeProvider = defineProvider({
|
|
|
152
154
|
});
|
|
153
155
|
return { realtime };
|
|
154
156
|
},
|
|
155
|
-
async boot({ authService, database, env, events }, { outputs }) {
|
|
157
|
+
async boot({ appRoot, authService, database, env, events }, { outputs }) {
|
|
156
158
|
const state = stateByCapability.get(outputs.realtime);
|
|
157
159
|
if (!state) throw new Error("Realtime runtime state is unavailable.");
|
|
158
160
|
state.authService = authService;
|
|
@@ -166,6 +168,7 @@ const RealtimeProvider = defineProvider({
|
|
|
166
168
|
authService,
|
|
167
169
|
audiences: state.audiences
|
|
168
170
|
});
|
|
171
|
+
announceServedClientBuild({ io: state.io, appRoot, logger: state.providerLogger });
|
|
169
172
|
state.redisConnection = await configureSocketIoRedisAdapter(state.io, {
|
|
170
173
|
logger: state.providerLogger,
|
|
171
174
|
redisUrl: resolveRealtimeRedisUrl(env),
|
|
@@ -105,7 +105,10 @@ function applyAudiencePreset(preset, { event, rooms, flags, logger }) {
|
|
|
105
105
|
return;
|
|
106
106
|
}
|
|
107
107
|
if (normalized === "event_scope") {
|
|
108
|
-
|
|
108
|
+
// An event without a deliverable scope reaches nobody; broadcasting needs all_users.
|
|
109
|
+
const room = roomForScope(event?.scope);
|
|
110
|
+
if (room) rooms.add(room);
|
|
111
|
+
else logger.warn({ audience: normalized, scope: event?.scope || null }, "Realtime event_scope audience has no deliverable scope.");
|
|
109
112
|
return;
|
|
110
113
|
}
|
|
111
114
|
logger.warn({ audience: normalized }, "Realtime ignored an unknown audience preset.");
|
package/src/server/runtime.js
CHANGED
|
@@ -63,23 +63,20 @@ function createSocketIoServer({
|
|
|
63
63
|
return new ServerCtor(server, normalizedOptions);
|
|
64
64
|
}
|
|
65
65
|
|
|
66
|
+
// Socket.IO runs on an HTTP server its caller owns (Fastify's, for the
|
|
67
|
+
// provider), which also carries other routes' WebSockets and streams.
|
|
68
|
+
// Server#close() would close that server and wait for every one of them, so
|
|
69
|
+
// close only Socket.IO's part: refuse its new requests, then close its engine
|
|
70
|
+
// and adapter. The server's owner closes the server. Closing the engine ends
|
|
71
|
+
// each client's transport, as Server#close() does, so browsers reconnect to
|
|
72
|
+
// the next server through Socket.IO's own reconnection.
|
|
66
73
|
async function closeSocketIoServer(io) {
|
|
67
|
-
if (!io
|
|
74
|
+
if (!io?.engine) {
|
|
68
75
|
return;
|
|
69
76
|
}
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
if (error.code === "ERR_SERVER_NOT_RUNNING") {
|
|
74
|
-
resolve();
|
|
75
|
-
return;
|
|
76
|
-
}
|
|
77
|
-
reject(error);
|
|
78
|
-
return;
|
|
79
|
-
}
|
|
80
|
-
resolve();
|
|
81
|
-
});
|
|
82
|
-
});
|
|
77
|
+
io.engine.use((_request, _response, next) => next(new Error("Realtime has shut down.")));
|
|
78
|
+
io.engine.close();
|
|
79
|
+
await io.sockets.adapter.close();
|
|
83
80
|
}
|
|
84
81
|
|
|
85
82
|
function resolveRealtimeRedisUrl(env = {}) {
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { readServedClientBuildId } from "@jskit-ai/kernel/server/support";
|
|
2
|
+
import { SERVED_CLIENT_BUILD_EVENT } from "../shared/servedClientBuild.js";
|
|
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.
|
|
7
|
+
function announceServedClientBuild({ io, appRoot, logger }) {
|
|
8
|
+
if (!appRoot || typeof io?.on !== "function") return;
|
|
9
|
+
io.on("connection", async (socket) => {
|
|
10
|
+
try {
|
|
11
|
+
const buildId = await readServedClientBuildId({ appRoot });
|
|
12
|
+
if (buildId && socket.connected) socket.emit(SERVED_CLIENT_BUILD_EVENT, { buildId });
|
|
13
|
+
} catch (error) {
|
|
14
|
+
logger.warn({ error: String(error?.message || error) }, "Realtime could not read the served client build.");
|
|
15
|
+
}
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export { announceServedClientBuild };
|
|
@@ -45,7 +45,12 @@ test("real sockets authorize each conversation delivery and disconnect a revoked
|
|
|
45
45
|
registerSocketAudienceBootstrap({ io, authService, logger });
|
|
46
46
|
const delivery = createRealtimeDelivery({ io, authService, logger });
|
|
47
47
|
delivery.start();
|
|
48
|
-
t.after(async () => {
|
|
48
|
+
t.after(async () => {
|
|
49
|
+
delivery.stop();
|
|
50
|
+
await closeSocketIoServer(io);
|
|
51
|
+
httpServer.closeAllConnections();
|
|
52
|
+
await new Promise((resolve) => httpServer.close(resolve));
|
|
53
|
+
});
|
|
49
54
|
httpServer.listen(0, "127.0.0.1");
|
|
50
55
|
await once(httpServer, "listening");
|
|
51
56
|
const url = `http://127.0.0.1:${httpServer.address().port}`;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import assert from "node:assert/strict";
|
|
2
|
-
import { createServer } from "node:http";
|
|
2
|
+
import { createServer, get } from "node:http";
|
|
3
3
|
import { once } from "node:events";
|
|
4
4
|
import test from "node:test";
|
|
5
5
|
import { createCapabilityRuntime, defineProvider } from "@jskit-ai/kernel/shared/capabilities";
|
|
@@ -39,6 +39,9 @@ async function connectionRequestFixture(t, authService = null, audienceContribut
|
|
|
39
39
|
for (const client of clients) client.disconnect();
|
|
40
40
|
release();
|
|
41
41
|
await runtime.shutdown();
|
|
42
|
+
// The HTTP server belongs to this fixture, as Fastify's belongs to Fastify.
|
|
43
|
+
http.closeAllConnections();
|
|
44
|
+
await new Promise((resolve) => http.close(resolve));
|
|
42
45
|
});
|
|
43
46
|
http.listen(0, "127.0.0.1");
|
|
44
47
|
await once(http, "listening");
|
|
@@ -147,6 +150,61 @@ test("RealtimeProvider waits for authentication boot before accessing the auth s
|
|
|
147
150
|
}
|
|
148
151
|
});
|
|
149
152
|
|
|
153
|
+
test("RealtimeProvider shutdown closes only Socket.IO and leaves the shared HTTP server to its owner", async (t) => {
|
|
154
|
+
const http = createServer();
|
|
155
|
+
const held = new Set();
|
|
156
|
+
// Another route's open WebSocket on the same server (a terminal or Preview).
|
|
157
|
+
http.on("upgrade", (request, socket) => {
|
|
158
|
+
if (request.url.startsWith("/socket.io/")) return;
|
|
159
|
+
held.add(socket);
|
|
160
|
+
socket.write("HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n");
|
|
161
|
+
});
|
|
162
|
+
const runtime = createCapabilityRuntime({ providers: [EventProvider, RealtimeProvider], inputs: {
|
|
163
|
+
"runtime.config": {}, "runtime.env": {}, "runtime.fastify": { server: http }, "runtime.logger": logger
|
|
164
|
+
} });
|
|
165
|
+
await runtime.start();
|
|
166
|
+
http.listen(0, "127.0.0.1");
|
|
167
|
+
await once(http, "listening");
|
|
168
|
+
const clients = [];
|
|
169
|
+
let stopping = null;
|
|
170
|
+
t.after(async () => {
|
|
171
|
+
for (const client of clients) client.disconnect();
|
|
172
|
+
for (const socket of held) socket.destroy();
|
|
173
|
+
await stopping;
|
|
174
|
+
http.closeAllConnections();
|
|
175
|
+
await new Promise((resolve) => http.close(resolve));
|
|
176
|
+
});
|
|
177
|
+
const url = `http://127.0.0.1:${http.address().port}`;
|
|
178
|
+
const other = await new Promise((resolve, reject) => {
|
|
179
|
+
const request = get(`${url}/terminal`, { headers: { Connection: "Upgrade", Upgrade: "websocket" } });
|
|
180
|
+
request.on("error", reject);
|
|
181
|
+
request.on("upgrade", (_response, socket) => resolve(socket));
|
|
182
|
+
});
|
|
183
|
+
const client = createSocketIoClient({ url, options: { transports: ["websocket"], reconnection: false } });
|
|
184
|
+
clients.push(client);
|
|
185
|
+
await once(client, "connect", { signal: AbortSignal.timeout(5_000) });
|
|
186
|
+
const disconnected = once(client, "disconnect", { signal: AbortSignal.timeout(5_000) });
|
|
187
|
+
|
|
188
|
+
stopping = runtime.shutdown();
|
|
189
|
+
const outcome = await Promise.race([
|
|
190
|
+
stopping.then(() => "stopped"),
|
|
191
|
+
new Promise((resolve) => setTimeout(() => resolve("waiting for the HTTP server"), 1_000))
|
|
192
|
+
]);
|
|
193
|
+
assert.equal(outcome, "stopped", "another route's open connection must not hold realtime shutdown");
|
|
194
|
+
// A stopping server ends the transport, as Server#close() does, so the
|
|
195
|
+
// browser's own Socket.IO reconnection reaches the next server. A server
|
|
196
|
+
// disconnect ("io server disconnect") would switch that reconnection off.
|
|
197
|
+
assert.equal((await disconnected)[0], "transport close");
|
|
198
|
+
assert.equal(http.listening, true, "the HTTP server's owner closes it");
|
|
199
|
+
assert.equal(other.destroyed, false, "realtime leaves other routes' connections to their owners");
|
|
200
|
+
|
|
201
|
+
// Socket.IO refuses new connections until the owner closes the server.
|
|
202
|
+
const late = createSocketIoClient({ url, options: { reconnection: false } });
|
|
203
|
+
clients.push(late);
|
|
204
|
+
await once(late, "connect_error", { signal: AbortSignal.timeout(5_000) });
|
|
205
|
+
assert.equal(late.connected, false);
|
|
206
|
+
});
|
|
207
|
+
|
|
150
208
|
function createIoDouble() {
|
|
151
209
|
const emitted = [];
|
|
152
210
|
return {
|
|
@@ -223,6 +281,27 @@ test("realtime delivery sends explicit action events to their selected rooms", a
|
|
|
223
281
|
assert.equal(Object.hasOwn(io.emitted[0].payload, "realtime"), false);
|
|
224
282
|
});
|
|
225
283
|
|
|
284
|
+
test("realtime event_scope delivery never widens an undeliverable scope to every user", async () => {
|
|
285
|
+
const io = createIoDouble();
|
|
286
|
+
const warnings = [];
|
|
287
|
+
const delivery = createRealtimeDelivery({ io, logger: { ...logger, warn: (details) => warnings.push(details) } });
|
|
288
|
+
const scopes = [undefined, { kind: "scope", id: "11" }, { kind: "public" }, { kind: "user" }];
|
|
289
|
+
for (const scope of scopes) {
|
|
290
|
+
await delivery.handle({
|
|
291
|
+
type: "entity.changed",
|
|
292
|
+
source: "crud",
|
|
293
|
+
entity: "record",
|
|
294
|
+
operation: "updated",
|
|
295
|
+
entityId: "5",
|
|
296
|
+
...(scope ? { scope } : {}),
|
|
297
|
+
realtime: { event: "things.record.changed", audience: "event_scope" }
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
assert.deepEqual(io.emitted, []);
|
|
302
|
+
assert.deepEqual(warnings, scopes.map((scope) => ({ audience: "event_scope", scope: scope || null })));
|
|
303
|
+
});
|
|
304
|
+
|
|
226
305
|
test("realtime delivery resolves an explicit database-backed audience without exposing query controls", async () => {
|
|
227
306
|
const io = createIoDouble();
|
|
228
307
|
const delivery = createRealtimeDelivery({
|
|
@@ -437,7 +516,7 @@ async function startRealtimeClient({ mobile = null } = {}) {
|
|
|
437
516
|
|
|
438
517
|
test("RealtimeClientProvider publishes one explicit client capability", async () => {
|
|
439
518
|
const fixture = await startRealtimeClient();
|
|
440
|
-
assert.deepEqual(Object.keys(fixture.realtime).sort(), ["config", "dispose", "initialize", "socket"]);
|
|
519
|
+
assert.deepEqual(Object.keys(fixture.realtime).sort(), ["config", "dispose", "initialize", "onServedClientBuild", "socket"]);
|
|
441
520
|
assert.equal(fixture.realtime.config.url, "");
|
|
442
521
|
assert.equal(fixture.registrations.has("realtime.web.connection.indicator"), true);
|
|
443
522
|
assert.equal(
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { createServer } from "node:http";
|
|
3
|
+
import { once } from "node:events";
|
|
4
|
+
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import test from "node:test";
|
|
8
|
+
import { createCapabilityRuntime, defineProvider } from "@jskit-ai/kernel/shared/capabilities";
|
|
9
|
+
import { EventProvider } from "@jskit-ai/kernel/server/runtime";
|
|
10
|
+
import { CLIENT_APP_CONFIG_GLOBAL_KEY, setClientAppConfig } from "../../kernel/client/appConfig.js";
|
|
11
|
+
import { RealtimeClientProvider } from "../src/client/RealtimeClientProvider.js";
|
|
12
|
+
import { RealtimeProvider } from "../src/server/RealtimeProvider.js";
|
|
13
|
+
import { announceServedClientBuild } from "../src/server/servedClientBuild.js";
|
|
14
|
+
|
|
15
|
+
const logger = Object.freeze({ debug() {}, info() {}, warn() {}, error() {} });
|
|
16
|
+
const FIRST_BUILD = "1111111111111111";
|
|
17
|
+
const SECOND_BUILD = "2222222222222222";
|
|
18
|
+
|
|
19
|
+
async function writeServedPage(appRoot, buildId) {
|
|
20
|
+
await mkdir(path.join(appRoot, "dist"), { recursive: true });
|
|
21
|
+
await writeFile(path.join(appRoot, "dist", "index.html"),
|
|
22
|
+
`<!doctype html><html><head><meta name="jskit-client-build" content="${buildId}"></head></html>`);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// One server process: its own HTTP server and realtime runtime on a fixed port.
|
|
26
|
+
async function startServer({ appRoot, port = 0 }) {
|
|
27
|
+
const http = createServer();
|
|
28
|
+
const runtime = createCapabilityRuntime({ providers: [EventProvider, RealtimeProvider], inputs: {
|
|
29
|
+
"runtime.app-root": appRoot, "runtime.config": {}, "runtime.env": {},
|
|
30
|
+
"runtime.fastify": { server: http }, "runtime.logger": logger
|
|
31
|
+
} });
|
|
32
|
+
await runtime.start();
|
|
33
|
+
http.listen(port, "127.0.0.1");
|
|
34
|
+
await once(http, "listening");
|
|
35
|
+
return {
|
|
36
|
+
port: http.address().port,
|
|
37
|
+
async stop() {
|
|
38
|
+
await runtime.shutdown();
|
|
39
|
+
http.closeAllConnections();
|
|
40
|
+
await new Promise((resolve) => http.close(resolve));
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function startClient(url) {
|
|
46
|
+
let realtime = null;
|
|
47
|
+
const probe = defineProvider({
|
|
48
|
+
id: "test.realtime.client.probe",
|
|
49
|
+
requires: { value: "client.realtime" },
|
|
50
|
+
setup({ value }) {
|
|
51
|
+
realtime = value;
|
|
52
|
+
return {};
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
setClientAppConfig({ realtimeClient: { url, options: {
|
|
56
|
+
transports: ["websocket"], reconnectionDelay: 50, reconnectionDelayMax: 100, randomizationFactor: 0
|
|
57
|
+
} } });
|
|
58
|
+
const runtime = createCapabilityRuntime({ providers: [RealtimeClientProvider, probe], inputs: {
|
|
59
|
+
"client.components": { register() {} }, "client.env": {}, "client.logger": logger, "client.vue": { provide() {} }
|
|
60
|
+
} });
|
|
61
|
+
await runtime.start();
|
|
62
|
+
return { realtime, runtime };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function waitFor(predicate, label) {
|
|
66
|
+
const deadline = Date.now() + 8_000;
|
|
67
|
+
while (!predicate()) {
|
|
68
|
+
if (Date.now() > deadline) throw new Error(`Timed out waiting until ${label}.`);
|
|
69
|
+
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
test("every connection, including one to a restarted server, learns the client build that server serves", async (t) => {
|
|
74
|
+
const appRoot = await mkdtemp(path.join(os.tmpdir(), "jskit-realtime-served-build-"));
|
|
75
|
+
const previousAppConfig = globalThis[CLIENT_APP_CONFIG_GLOBAL_KEY];
|
|
76
|
+
let server = null;
|
|
77
|
+
let client = null;
|
|
78
|
+
t.after(async () => {
|
|
79
|
+
await client?.runtime.shutdown();
|
|
80
|
+
await server?.stop();
|
|
81
|
+
if (previousAppConfig === undefined) delete globalThis[CLIENT_APP_CONFIG_GLOBAL_KEY];
|
|
82
|
+
else globalThis[CLIENT_APP_CONFIG_GLOBAL_KEY] = previousAppConfig;
|
|
83
|
+
await rm(appRoot, { recursive: true, force: true });
|
|
84
|
+
});
|
|
85
|
+
await writeServedPage(appRoot, FIRST_BUILD);
|
|
86
|
+
server = await startServer({ appRoot });
|
|
87
|
+
const { port } = server;
|
|
88
|
+
client = await startClient(`http://127.0.0.1:${port}`);
|
|
89
|
+
|
|
90
|
+
const seen = [];
|
|
91
|
+
client.realtime.onServedClientBuild((buildId) => seen.push(buildId));
|
|
92
|
+
await waitFor(() => seen.length === 1, "the first connection names its build");
|
|
93
|
+
assert.deepEqual(seen, [FIRST_BUILD]);
|
|
94
|
+
const late = [];
|
|
95
|
+
client.realtime.onServedClientBuild((buildId) => late.push(buildId));
|
|
96
|
+
assert.deepEqual(late, [FIRST_BUILD], "a later subscriber receives the latest build at once");
|
|
97
|
+
|
|
98
|
+
// An update: the server stops, its built page changes, and a new server starts on the same port.
|
|
99
|
+
await server.stop();
|
|
100
|
+
server = null;
|
|
101
|
+
await writeServedPage(appRoot, SECOND_BUILD);
|
|
102
|
+
server = await startServer({ appRoot, port });
|
|
103
|
+
await waitFor(() => seen.length === 2, "the reconnection names the new build");
|
|
104
|
+
assert.deepEqual(seen, [FIRST_BUILD, SECOND_BUILD]);
|
|
105
|
+
assert.deepEqual(late, [FIRST_BUILD, SECOND_BUILD]);
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
test("a server announces only a build it actually serves, and only to a connected socket", async (t) => {
|
|
109
|
+
const appRoot = await mkdtemp(path.join(os.tmpdir(), "jskit-realtime-served-build-"));
|
|
110
|
+
t.after(() => rm(appRoot, { recursive: true, force: true }));
|
|
111
|
+
const handlers = [];
|
|
112
|
+
const io = { on(eventName, handler) { assert.equal(eventName, "connection"); handlers.push(handler); } };
|
|
113
|
+
const warnings = [];
|
|
114
|
+
announceServedClientBuild({ io, appRoot, logger: { warn: (...args) => warnings.push(args) } });
|
|
115
|
+
announceServedClientBuild({ io, appRoot: "", logger });
|
|
116
|
+
assert.equal(handlers.length, 1, "without an app root there is no built page to name");
|
|
117
|
+
|
|
118
|
+
const socket = (connected = true) => ({ connected, emitted: [], emit(...args) { this.emitted.push(args); } });
|
|
119
|
+
const withoutBuild = socket();
|
|
120
|
+
await handlers[0](withoutBuild);
|
|
121
|
+
assert.deepEqual(withoutBuild.emitted, [], "development serves no built page");
|
|
122
|
+
|
|
123
|
+
await writeServedPage(appRoot, FIRST_BUILD);
|
|
124
|
+
const connected = socket();
|
|
125
|
+
await handlers[0](connected);
|
|
126
|
+
assert.deepEqual(connected.emitted, [["realtime.served-client-build", { buildId: FIRST_BUILD }]]);
|
|
127
|
+
const gone = socket(false);
|
|
128
|
+
await handlers[0](gone);
|
|
129
|
+
assert.deepEqual(gone.emitted, []);
|
|
130
|
+
assert.deepEqual(warnings, []);
|
|
131
|
+
});
|
|
@@ -111,6 +111,7 @@ test("realtime leaves slow application upgrades and access denials to their rout
|
|
|
111
111
|
for (const timer of timers) clearTimeout(timer);
|
|
112
112
|
for (const socket of sockets) socket.destroy();
|
|
113
113
|
await closeSocketIoServer(realtime);
|
|
114
|
+
await new Promise((resolve) => server.close(resolve));
|
|
114
115
|
});
|
|
115
116
|
server.listen(0, "127.0.0.1");
|
|
116
117
|
await once(server, "listening");
|
|
@@ -160,20 +161,25 @@ test("createSocketIoServer throws when no server target is provided", () => {
|
|
|
160
161
|
);
|
|
161
162
|
});
|
|
162
163
|
|
|
163
|
-
test("closeSocketIoServer
|
|
164
|
-
|
|
164
|
+
test("closeSocketIoServer closes Socket.IO's own part and never the HTTP server", async () => {
|
|
165
|
+
const calls = [];
|
|
165
166
|
const io = {
|
|
166
|
-
close(
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
167
|
+
close() { calls.push("server.close"); },
|
|
168
|
+
engine: {
|
|
169
|
+
use(middleware) {
|
|
170
|
+
middleware({}, {}, (error) => calls.push(`refuse:${error.message}`));
|
|
171
|
+
},
|
|
172
|
+
close() { calls.push("engine.close"); }
|
|
173
|
+
},
|
|
174
|
+
local: { disconnectSockets() { calls.push("disconnectSockets"); } },
|
|
175
|
+
sockets: { adapter: { async close() { calls.push("adapter.close"); } } }
|
|
170
176
|
};
|
|
171
177
|
|
|
172
178
|
await closeSocketIoServer(io);
|
|
173
|
-
assert.
|
|
179
|
+
assert.deepEqual(calls, ["refuse:Realtime has shut down.", "engine.close", "adapter.close"]);
|
|
174
180
|
});
|
|
175
181
|
|
|
176
|
-
test("closeSocketIoServer is a no-op without
|
|
182
|
+
test("closeSocketIoServer is a no-op without a Socket.IO engine", async () => {
|
|
177
183
|
await closeSocketIoServer(null);
|
|
178
184
|
await closeSocketIoServer({});
|
|
179
185
|
assert.equal(true, true);
|