@jskit-ai/realtime 0.2.18 → 0.2.20
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 +14 -0
- package/package.json +7 -2
- package/patterns/realtime-application/PATTERN.md +7 -0
- package/patterns/realtime-application/example/package.json +2 -2
- package/src/server/RealtimeAudienceScopeFeature.js +38 -0
- package/src/server/RealtimeProvider.js +22 -7
- package/src/server/realtimeAudience.js +84 -17
- package/src/server/realtimeCapability.js +4 -4
- package/src/server/realtimeDelivery.js +4 -3
- package/src/server/types.js +9 -0
- package/test/providerRuntime.test.js +118 -20
- package/test/realtimeAudience.mysql.test.js +181 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,10 +2,24 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- **Security.** An event written on a customer's or a public surface (scoped globally) reads its audience's `audienceUsers` in the workspace the request resolved, which the kernel adds to its global scope as `workspaceId` (`forWorkspace` of `realtime.audience-scope`), and `all_workspace_users` reaches that workspace. The payload never chooses the scope: an app's payload may copy an input id, and reading in a workspace the payload named let one event read in, and reach, another workspace. Before, such an event read with no context, so an audience over an owned table reached no customer. A scope that names a workspace or a user keeps it, and an event with neither reads with no context.
|
|
6
|
+
- **Breaking.** An audience given as a function of the execution, which the boot check cannot see, is checked when its event is published: without `realtime.audience-scope`, an entry that reads in the event's scope (an `audienceUsers` without `publicTablesOnly: true`) is logged as an error naming the socket event and entity, and skipped; the event still reaches the audience's other rooms. Before, it read with no context and silently missed the users of an owned table.
|
|
7
|
+
- An audience entry whose `audienceUsers` fails no longer loses the whole event: the failure is logged as an error naming the socket event and entity, the entry is skipped, and the event still reaches the audience's presets, rooms, users and other entries. Before, one failing read dropped the event for everybody, logged only as a warning.
|
|
8
|
+
- **Breaking.** `RealtimeProvider` refuses to boot when an action's event declares an audience whose `audienceUsers` reads in the event's scope and no feature provides `realtime.audience-scope`, naming those actions; before, each delivery read with no context and missed the users of an owned table. It reads the declared events through the optional `runtime.actions`. An audience that reads public tables only says `publicTablesOnly: true` and still needs no scope; an audience given as a function of the execution is not checked.
|
|
9
|
+
|
|
5
10
|
- 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.
|
|
6
11
|
- `SESSION_REFRESH_REQUIRED` has its English in the catalog, so it translates.
|
|
7
12
|
- 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
13
|
- 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.
|
|
14
|
+
- **Breaking (data-access redesign).** An audience entry reaches users that a record's owner knows through `audienceUsers({ event, options })`, which answers, or resolves to, a list of user ids. It is asked once per event, however many sockets receive it. With `RealtimeAudienceScopeFeature` registered, `options.context` is a system job context scoped to the event's workspace, its user in its workspace, or its user (`forWorkspace`, `forWorkspaceUser` or `forUser` of `realtime.audience-scope`), so the owners' APIs it calls answer for that scope; without it, `options` carries no context, which reaches public tables only. `userQuery({ knex, event })` is removed, and realtime no longer takes the optional `runtime.database`; `createRealtimeDelivery` no longer takes `database`.
|
|
15
|
+
|
|
16
|
+
- New `RealtimeAudienceScopeFeature` (`@jskit-ai/realtime/server/RealtimeAudienceScopeFeature`) provides `realtime.audience-scope`: it declares the system scope that reads the users an event's audience reaches and derives the event's scoped contexts from it. `RealtimeProvider` takes it as an optional capability, so a server without a database keeps realtime; an app whose audiences read owned tables registers the feature.
|
|
17
|
+
|
|
18
|
+
### Upgrading
|
|
19
|
+
|
|
20
|
+
- An app whose action events declare an `audienceUsers` audience registers `RealtimeAudienceScopeFeature`, or marks an audience that reads only public tables `publicTablesOnly: true`; otherwise it no longer boots.
|
|
21
|
+
- An app whose audiences call owners' APIs on owned tables registers `RealtimeAudienceScopeFeature` beside `RealtimeProvider`.
|
|
22
|
+
- An audience that provided `userQuery({ knex, event })` provides `audienceUsers({ event, options })` instead, asking the record's owner for the users (for example `activeMemberIds(workspaceId, options)` of `workspaces.memberships`) and answering their ids rather than rows.
|
|
9
23
|
|
|
10
24
|
### New codes (1)
|
|
11
25
|
|
package/package.json
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jskit-ai/realtime",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.20",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"test": "jskit test"
|
|
7
7
|
},
|
|
8
8
|
"exports": {
|
|
9
9
|
"./server/RealtimeProvider": "./src/server/RealtimeProvider.js",
|
|
10
|
+
"./server/RealtimeAudienceScopeFeature": "./src/server/RealtimeAudienceScopeFeature.js",
|
|
10
11
|
"./server/runtime": "./src/server/runtime.js",
|
|
11
12
|
"./server/types": "./src/server/types.js",
|
|
12
13
|
"./client": "./src/client/RealtimeClientProvider.js",
|
|
@@ -23,7 +24,7 @@
|
|
|
23
24
|
"socket.io-client": "^4.8.3"
|
|
24
25
|
},
|
|
25
26
|
"peerDependencies": {
|
|
26
|
-
"@jskit-ai/kernel": "0.2.
|
|
27
|
+
"@jskit-ai/kernel": "0.2.14",
|
|
27
28
|
"vue": "^3.5.13"
|
|
28
29
|
},
|
|
29
30
|
"description": "Thin, generic realtime runtime wrappers for socket.io server and client.",
|
|
@@ -75,6 +76,10 @@
|
|
|
75
76
|
"subpath": "./server/RealtimeProvider",
|
|
76
77
|
"summary": "Exports the explicit RealtimeProvider capability provider."
|
|
77
78
|
},
|
|
79
|
+
{
|
|
80
|
+
"subpath": "./server/RealtimeAudienceScopeFeature",
|
|
81
|
+
"summary": "Exports RealtimeAudienceScopeFeature, which provides realtime.audience-scope: the contexts scoped to an event's workspace, user or workspace user that an audience's audienceUsers reads in. Applications whose audiences read owned tables register it."
|
|
82
|
+
},
|
|
78
83
|
{
|
|
79
84
|
"subpath": "./server/runtime",
|
|
80
85
|
"summary": "Exports the Socket.IO server and Redis adapter runtime helpers."
|
|
@@ -43,6 +43,13 @@ name and audience. Client features use `RealtimeClientProvider` and the public
|
|
|
43
43
|
listener registration helpers from `@jskit-ai/realtime`. Use the normal shell
|
|
44
44
|
placement registry for the optional status component.
|
|
45
45
|
|
|
46
|
+
An audience's `audienceUsers({ event, options })` reads in a context scoped to
|
|
47
|
+
the event's workspace, user or workspace user. An application whose action
|
|
48
|
+
events declare such an audience registers `RealtimeAudienceScopeFeature` from
|
|
49
|
+
`@jskit-ai/realtime/server/RealtimeAudienceScopeFeature`, which provides those
|
|
50
|
+
contexts, or realtime refuses to boot. An audience that reads only public
|
|
51
|
+
tables marks itself `publicTablesOnly: true` and reads with no context.
|
|
52
|
+
|
|
46
53
|
## Example files
|
|
47
54
|
|
|
48
55
|
`example/package.json` declares realtime and shell runtime packages.
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { defineFeature } from "@jskit-ai/kernel/server/features";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* A feature's system context, as this feature derives scoped contexts from it.
|
|
5
|
+
* @typedef {(reason: string) => import("./types.js").RealtimeAudienceScope} SystemContextFactory
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The contexts an audience's audienceUsers reads in, scoped to the event's own
|
|
10
|
+
* workspace, user, or user in a workspace.
|
|
11
|
+
* @param {SystemContextFactory} systemContext
|
|
12
|
+
* @returns {import("./types.js").RealtimeAudienceScope}
|
|
13
|
+
*/
|
|
14
|
+
function audienceScopeFor(systemContext) {
|
|
15
|
+
const reading = () => systemContext("read the users a realtime event's audience reaches, in the event's scope");
|
|
16
|
+
return Object.freeze({
|
|
17
|
+
forWorkspace: (workspaceId) => reading().forWorkspace(workspaceId),
|
|
18
|
+
forUser: (userId) => reading().forUser(userId),
|
|
19
|
+
forWorkspaceUser: (workspaceId, userId) => reading().forWorkspaceUser(workspaceId, userId)
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// An application whose realtime audiences read owned tables registers this
|
|
24
|
+
// feature, so each audience reads in its event's scope. Realtime itself needs no
|
|
25
|
+
// database: without it, audiences read with no context.
|
|
26
|
+
const RealtimeAudienceScopeFeature = defineFeature({
|
|
27
|
+
id: "realtime.audience-scope",
|
|
28
|
+
systemScope: "read the users a realtime event's audience reaches, scoped to the event's workspace or user",
|
|
29
|
+
provides: {
|
|
30
|
+
audienceScope: "realtime.audience-scope"
|
|
31
|
+
},
|
|
32
|
+
/** @param {{ systemContext: SystemContextFactory }} capabilities */
|
|
33
|
+
setup({ systemContext }) {
|
|
34
|
+
return { audienceScope: audienceScopeFor(systemContext) };
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
export { RealtimeAudienceScopeFeature };
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { defineProvider } from "@jskit-ai/kernel/shared/capabilities";
|
|
2
2
|
import { normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
|
|
3
3
|
import { createProviderLogger } from "@jskit-ai/kernel/shared/support/providerLogger";
|
|
4
|
+
import { actionsNeedingAudienceScope } from "./realtimeAudience.js";
|
|
4
5
|
import { createRealtimeCapability } from "./realtimeCapability.js";
|
|
5
6
|
import {
|
|
6
7
|
createSocketIoServer,
|
|
@@ -31,9 +32,10 @@ const RealtimeProvider = defineProvider({
|
|
|
31
32
|
logger: "runtime.logger"
|
|
32
33
|
},
|
|
33
34
|
optional: {
|
|
35
|
+
actions: "runtime.actions",
|
|
34
36
|
appRoot: "runtime.app-root",
|
|
35
|
-
|
|
36
|
-
|
|
37
|
+
audienceScope: "realtime.audience-scope",
|
|
38
|
+
authService: "auth.service"
|
|
37
39
|
},
|
|
38
40
|
provides: {
|
|
39
41
|
realtime: "runtime.realtime"
|
|
@@ -41,31 +43,44 @@ const RealtimeProvider = defineProvider({
|
|
|
41
43
|
/**
|
|
42
44
|
* @param {object} dependencies
|
|
43
45
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeAppRoot | null} dependencies.appRoot
|
|
46
|
+
* @param {import("./types.js").RealtimeAudienceScope | null} dependencies.audienceScope The contexts
|
|
47
|
+
* audiences read in, from RealtimeAudienceScopeFeature when the application registers it.
|
|
44
48
|
* @param {import("@jskit-ai/auth-core/server/types").AuthService | null} dependencies.authService
|
|
45
49
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeConfig} dependencies.config
|
|
46
|
-
* @param {import("@jskit-ai/database-runtime/server/types").RuntimeDatabase | null} dependencies.database
|
|
47
50
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} dependencies.env
|
|
48
51
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeEvents} dependencies.events
|
|
49
52
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeFastify} dependencies.fastify
|
|
50
53
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
|
|
51
54
|
*/
|
|
52
|
-
setup({ appRoot, authService, config,
|
|
55
|
+
setup({ appRoot, audienceScope, authService, config, env, events, fastify, logger }) {
|
|
53
56
|
const realtime = createRealtimeCapability({
|
|
54
57
|
io: createSocketIoServer({ fastify }),
|
|
55
58
|
logger: createProviderLogger(logger, { debugEnabled: debugEnabled(config, env) }),
|
|
56
59
|
authService,
|
|
57
|
-
database,
|
|
58
60
|
events,
|
|
59
61
|
appRoot,
|
|
62
|
+
audienceScope,
|
|
60
63
|
redis: { redisUrl: resolveRealtimeRedisUrl(env), redisNamespace: resolveRealtimeRedisNamespace(env) }
|
|
61
64
|
});
|
|
62
65
|
return { realtime };
|
|
63
66
|
},
|
|
64
67
|
/**
|
|
65
|
-
*
|
|
68
|
+
* Refuses to start when an action's events read their audience in the event's scope and no feature provides
|
|
69
|
+
* `realtime.audience-scope`: each delivery would read with no context and miss the users.
|
|
70
|
+
* @param {{ actions: import("@jskit-ai/kernel/server/types").ActionCatalogue | null,
|
|
71
|
+
* audienceScope: import("./types.js").RealtimeAudienceScope | null }} capabilities
|
|
66
72
|
* @param {{ outputs: { realtime: import("./types.js").RuntimeRealtime } }} lifecycle
|
|
67
73
|
*/
|
|
68
|
-
async boot(
|
|
74
|
+
async boot({ actions, audienceScope }, { outputs }) {
|
|
75
|
+
const needing = audienceScope ? [] : actionsNeedingAudienceScope(actions);
|
|
76
|
+
if (needing.length > 0) {
|
|
77
|
+
throw new Error(
|
|
78
|
+
`Realtime events of ${needing.join(", ")} read their audience with audienceUsers in the event's scope, ` +
|
|
79
|
+
"which needs realtime.audience-scope: register RealtimeAudienceScopeFeature " +
|
|
80
|
+
"(@jskit-ai/realtime/server/RealtimeAudienceScopeFeature), or mark an audience that reads public tables only " +
|
|
81
|
+
"with publicTablesOnly: true."
|
|
82
|
+
);
|
|
83
|
+
}
|
|
69
84
|
await outputs.realtime.start();
|
|
70
85
|
},
|
|
71
86
|
/**
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
|
|
2
|
-
import { normalizeRecordId, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
|
|
2
|
+
import { isRecord, normalizeRecordId, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
|
|
3
3
|
|
|
4
4
|
/** @typedef {import("@jskit-ai/auth-core/server/types").AuthService} AuthService */
|
|
5
|
-
/** @typedef {import("@jskit-ai/database-runtime/server/types").RuntimeDatabase} RuntimeDatabase */
|
|
6
5
|
/** @typedef {import("@jskit-ai/kernel/server/types").RuntimeLogger} RuntimeLogger */
|
|
7
6
|
/** @typedef {import("./types.js").ActorRoomsResolver} ActorRoomsResolver */
|
|
8
7
|
/** @typedef {import("./types.js").ActorsRoomsResolver} ActorsRoomsResolver */
|
|
9
8
|
/** @typedef {import("./types.js").AudienceContributors} AudienceContributors */
|
|
9
|
+
/** @typedef {import("./types.js").RealtimeAudienceScope} RealtimeAudienceScope */
|
|
10
10
|
|
|
11
11
|
const ALL_CLIENTS_ROOM = "clients";
|
|
12
12
|
const ALL_USERS_ROOM = "users";
|
|
@@ -209,24 +209,77 @@ function addAudienceRooms(selection, state) {
|
|
|
209
209
|
}
|
|
210
210
|
}
|
|
211
211
|
|
|
212
|
-
|
|
212
|
+
/**
|
|
213
|
+
* The options an audience's audienceUsers reads with: a context scoped to the
|
|
214
|
+
* event's own workspace, workspace user or user, so owner APIs answer for the
|
|
215
|
+
* event's scope and never for a request's. The scope is the one the framework
|
|
216
|
+
* built from the write's execution: an event written on a customer's or a public
|
|
217
|
+
* surface carries the workspace the request resolved as its global scope's
|
|
218
|
+
* `workspaceId`. The payload never chooses it: an app's payload may copy an
|
|
219
|
+
* input id. An event whose scope names no workspace and no user, or an
|
|
220
|
+
* application without `realtime.audience-scope`, reads with no context.
|
|
221
|
+
* @param {object} event
|
|
222
|
+
* @param {RealtimeAudienceScope | null | undefined} audienceScope
|
|
223
|
+
*/
|
|
224
|
+
function audienceReadOptions(event, audienceScope) {
|
|
225
|
+
if (!audienceScope) return Object.freeze({});
|
|
226
|
+
const scope = event?.scope;
|
|
227
|
+
const kind = normalizeText(scope?.kind).toLowerCase();
|
|
228
|
+
const userId = resolveScopeUserId(scope);
|
|
229
|
+
const workspaceId = kind === "user" ? null : resolveScopeWorkspaceId(scope);
|
|
230
|
+
if (workspaceId) {
|
|
231
|
+
return Object.freeze({
|
|
232
|
+
context: userId ? audienceScope.forWorkspaceUser(workspaceId, userId) : audienceScope.forWorkspace(workspaceId)
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
if (kind === "user" && userId) {
|
|
236
|
+
return Object.freeze({ context: audienceScope.forUser(userId) });
|
|
237
|
+
}
|
|
238
|
+
return Object.freeze({});
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Whether an audience entry reads its users with audienceUsers in a scope: every one does, unless it says it reads
|
|
243
|
+
* public tables only (`publicTablesOnly: true`), which need no context.
|
|
244
|
+
* @param {unknown} entry
|
|
245
|
+
*/
|
|
246
|
+
function readsInScope(entry) {
|
|
247
|
+
// readable-check: allow method-probe - data: an event's audience entry may name audienceUsers()
|
|
248
|
+
return isRecord(entry) && typeof entry.audienceUsers === "function" && entry.publicTablesOnly !== true;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* The actions whose events declare an audience that reads its users in the event's scope, which only
|
|
253
|
+
* `realtime.audience-scope` gives: an audience given as a function of the execution is not known before it runs.
|
|
254
|
+
* @param {{ listDefinitions: () => Array<{ id: string, events: readonly Function[] }> } | null} actions
|
|
255
|
+
* @returns {string[]}
|
|
256
|
+
*/
|
|
257
|
+
function actionsNeedingAudienceScope(actions) {
|
|
213
258
|
const ids = new Set();
|
|
214
|
-
for (const
|
|
215
|
-
const
|
|
216
|
-
|
|
217
|
-
|
|
259
|
+
for (const definition of actions?.listDefinitions() ?? []) {
|
|
260
|
+
for (const build of definition.events) {
|
|
261
|
+
const audience = build.realtime?.audience;
|
|
262
|
+
if (typeof audience !== "function" && flattenEntries(audience).some(readsInScope)) ids.add(definition.id);
|
|
263
|
+
}
|
|
218
264
|
}
|
|
219
265
|
return [...ids];
|
|
220
266
|
}
|
|
221
267
|
|
|
222
268
|
/**
|
|
269
|
+
* The rooms and flags an event's audience reaches. An audience entry's
|
|
270
|
+
* `audienceUsers({ event, options })` answers user ids through the owners'
|
|
271
|
+
* APIs, once for the event however many sockets receive it. An entry whose
|
|
272
|
+
* read fails, or that reads in the event's scope when no feature provides
|
|
273
|
+
* `realtime.audience-scope`, is logged as an error and skipped: the event still
|
|
274
|
+
* reaches the other entries' rooms.
|
|
223
275
|
* @param {unknown} audience
|
|
224
276
|
* @param {object} event
|
|
225
277
|
* @param {object} dependencies
|
|
226
|
-
* @param {RuntimeDatabase | null} dependencies.database Absent when no runtime.database is installed.
|
|
227
278
|
* @param {RuntimeLogger} dependencies.logger
|
|
279
|
+
* @param {RealtimeAudienceScope | null} [dependencies.audienceScope] The contexts audienceUsers reads in;
|
|
280
|
+
* absent when the application does not register RealtimeAudienceScopeFeature.
|
|
228
281
|
*/
|
|
229
|
-
async function resolveAudienceTargets(audience, event, {
|
|
282
|
+
async function resolveAudienceTargets(audience, event, { logger, audienceScope }) {
|
|
230
283
|
const rooms = new Set();
|
|
231
284
|
const flags = { broadcastAllClients: false };
|
|
232
285
|
const state = { event, rooms, flags, logger };
|
|
@@ -238,14 +291,27 @@ async function resolveAudienceTargets(audience, event, { database, logger }) {
|
|
|
238
291
|
}
|
|
239
292
|
if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
|
|
240
293
|
addAudienceRooms(entry, state);
|
|
241
|
-
// readable-check: allow method-probe - data: an event's audience entry may name
|
|
242
|
-
if (typeof entry.
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
294
|
+
// readable-check: allow method-probe - data: an event's audience entry may name audienceUsers()
|
|
295
|
+
if (typeof entry.audienceUsers !== "function") continue;
|
|
296
|
+
if (!audienceScope && readsInScope(entry)) {
|
|
297
|
+
// The boot check sees only audiences declared as they are; this one was built when the action ran.
|
|
298
|
+
logger.error({ socketEvent: event?.realtime?.event ?? null, entityId: event?.entityId ?? null },
|
|
299
|
+
"Realtime audience reads its users in the event's scope, which needs realtime.audience-scope: register " +
|
|
300
|
+
"RealtimeAudienceScopeFeature, or mark an audience that reads public tables only with publicTablesOnly: true. " +
|
|
301
|
+
"The event still reaches the audience's other rooms.");
|
|
302
|
+
continue;
|
|
303
|
+
}
|
|
304
|
+
let userIds;
|
|
305
|
+
try {
|
|
306
|
+
userIds = await entry.audienceUsers({ event, options: audienceReadOptions(event, audienceScope) });
|
|
307
|
+
} catch (error) {
|
|
308
|
+
logger.error({ socketEvent: event?.realtime?.event ?? null, entityId: event?.entityId ?? null, error: String(error?.message || error) },
|
|
309
|
+
"Realtime audienceUsers failed; the event still reaches the audience's other rooms.");
|
|
310
|
+
continue;
|
|
311
|
+
}
|
|
312
|
+
for (const rawUserId of flattenEntries(userIds)) {
|
|
313
|
+
const userId = normalizeRecordId(rawUserId, { fallback: null });
|
|
314
|
+
if (userId) rooms.add(roomForUser(userId));
|
|
249
315
|
}
|
|
250
316
|
}
|
|
251
317
|
|
|
@@ -452,6 +518,7 @@ async function revalidateSocket({ socket, authService, audiences, request, authe
|
|
|
452
518
|
}
|
|
453
519
|
|
|
454
520
|
export {
|
|
521
|
+
actionsNeedingAudienceScope,
|
|
455
522
|
authenticationRequiredError,
|
|
456
523
|
createAudienceContributors,
|
|
457
524
|
createSocketRequest,
|
|
@@ -16,7 +16,6 @@ import {
|
|
|
16
16
|
} from "./runtime.js";
|
|
17
17
|
|
|
18
18
|
/** @typedef {import("@jskit-ai/auth-core/server/types").AuthService} AuthService */
|
|
19
|
-
/** @typedef {import("@jskit-ai/database-runtime/server/types").RuntimeDatabase} RuntimeDatabase */
|
|
20
19
|
/** @typedef {import("@jskit-ai/kernel/server/types").RuntimeAppRoot} RuntimeAppRoot */
|
|
21
20
|
/** @typedef {import("@jskit-ai/kernel/server/types").RuntimeEvents} RuntimeEvents */
|
|
22
21
|
/** @typedef {import("@jskit-ai/kernel/server/types").RuntimeLogger} RuntimeLogger */
|
|
@@ -29,12 +28,13 @@ import {
|
|
|
29
28
|
* @param {import("socket.io").Server} dependencies.io
|
|
30
29
|
* @param {RuntimeLogger} dependencies.logger
|
|
31
30
|
* @param {AuthService | null} dependencies.authService
|
|
32
|
-
* @param {RuntimeDatabase | null} dependencies.database
|
|
33
31
|
* @param {RuntimeEvents} dependencies.events
|
|
34
32
|
* @param {RuntimeAppRoot | null} dependencies.appRoot
|
|
33
|
+
* @param {import("./types.js").RealtimeAudienceScope | null} dependencies.audienceScope The contexts an
|
|
34
|
+
* audience's audienceUsers reads in; absent when no feature provides `realtime.audience-scope`.
|
|
35
35
|
* @param {{ redisUrl: string, redisNamespace: string }} dependencies.redis
|
|
36
36
|
*/
|
|
37
|
-
function createRealtimeCapability({ io, logger, authService,
|
|
37
|
+
function createRealtimeCapability({ io, logger, authService, events, appRoot, audienceScope, redis }) {
|
|
38
38
|
const audiences = createAudienceContributors();
|
|
39
39
|
const connectionListeners = new Set();
|
|
40
40
|
let authenticationRequired = false;
|
|
@@ -123,7 +123,7 @@ function createRealtimeCapability({ io, logger, authService, database, events, a
|
|
|
123
123
|
* event, to the other servers too when Redis is configured.
|
|
124
124
|
*/
|
|
125
125
|
async function start() {
|
|
126
|
-
delivery = createRealtimeDelivery({ io,
|
|
126
|
+
delivery = createRealtimeDelivery({ io, logger, authService, audiences, audienceScope });
|
|
127
127
|
authenticationRequired = realtimeAuthenticationRequired(authService);
|
|
128
128
|
registerSocketAudienceBootstrap({ io, logger, authService, audiences });
|
|
129
129
|
announceServedClientBuild({ io, appRoot, logger });
|
|
@@ -89,13 +89,14 @@ function rememberedActorId(socket) {
|
|
|
89
89
|
/**
|
|
90
90
|
* @param {object} dependencies
|
|
91
91
|
* @param {import("socket.io").Server} dependencies.io
|
|
92
|
-
* @param {import("@jskit-ai/database-runtime/server/types").RuntimeDatabase | null} dependencies.database Absent when no runtime.database is installed.
|
|
93
92
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} dependencies.logger
|
|
94
93
|
* @param {AuthService | null} dependencies.authService Absent when no auth.service is installed.
|
|
95
94
|
* @param {AudienceContributors} dependencies.audiences The rooms revalidation may make a socket join.
|
|
96
95
|
* With no contributors registered, a socket stays in the rooms it already has.
|
|
96
|
+
* @param {import("./types.js").RealtimeAudienceScope | null} dependencies.audienceScope The contexts an
|
|
97
|
+
* audience's audienceUsers reads in; absent when no feature provides `realtime.audience-scope`.
|
|
97
98
|
*/
|
|
98
|
-
function createRealtimeDelivery({ io,
|
|
99
|
+
function createRealtimeDelivery({ io, logger, authService, audiences: { mayContribute, resolveActorsRooms }, audienceScope }) {
|
|
99
100
|
// With an auth.service, each socket is revalidated before it receives an event;
|
|
100
101
|
// without one, events go straight to their rooms.
|
|
101
102
|
const guarded = Boolean(authService);
|
|
@@ -219,7 +220,7 @@ function createRealtimeDelivery({ io, database, logger, authService, audiences:
|
|
|
219
220
|
async function handle(event) {
|
|
220
221
|
try {
|
|
221
222
|
const eventName = normalizeText(event.realtime.event);
|
|
222
|
-
const targets = await resolveAudienceTargets(event.realtime.audience, event, {
|
|
223
|
+
const targets = await resolveAudienceTargets(event.realtime.audience, event, { logger, audienceScope });
|
|
223
224
|
const payload = publicRealtimePayload(event);
|
|
224
225
|
if (guarded) {
|
|
225
226
|
const envelope = { eventName, payload, targets };
|
package/src/server/types.js
CHANGED
|
@@ -11,6 +11,15 @@
|
|
|
11
11
|
* @typedef {(actorIds: string[]) => Promise<Map<string, Set<string>>>} ActorsRoomsResolver
|
|
12
12
|
*/
|
|
13
13
|
/** @typedef {ReturnType<typeof import("./realtimeAudience.js").createAudienceContributors>} AudienceContributors */
|
|
14
|
+
/**
|
|
15
|
+
* The `realtime.audience-scope` capability: the contexts an audience's
|
|
16
|
+
* audienceUsers reads in, one per kind of event scope, derived from
|
|
17
|
+
* RealtimeAudienceScopeFeature's system context.
|
|
18
|
+
* @typedef {object} RealtimeAudienceScope
|
|
19
|
+
* @property {(workspaceId: string) => object} forWorkspace
|
|
20
|
+
* @property {(userId: string) => object} forUser
|
|
21
|
+
* @property {(workspaceId: string, userId: string) => object} forWorkspaceUser
|
|
22
|
+
*/
|
|
14
23
|
|
|
15
24
|
/**
|
|
16
25
|
* A package that knows which scopes actors belong to. It answers for many
|
|
@@ -4,6 +4,7 @@ import { once } from "node:events";
|
|
|
4
4
|
import test from "node:test";
|
|
5
5
|
import { createCapabilityRuntime, defineProvider } from "@jskit-ai/kernel/shared/capabilities";
|
|
6
6
|
import { EventProvider } from "@jskit-ai/kernel/server/runtime";
|
|
7
|
+
import { createEntityChangedActionEvent } from "@jskit-ai/kernel/server/actions";
|
|
7
8
|
import { CLIENT_APP_CONFIG_GLOBAL_KEY, setClientAppConfig } from "../../kernel/client/appConfig.js";
|
|
8
9
|
import { RealtimeClientProvider } from "../src/client/RealtimeClientProvider.js";
|
|
9
10
|
import { RealtimeProvider } from "../src/server/RealtimeProvider.js";
|
|
@@ -14,6 +15,8 @@ import {
|
|
|
14
15
|
revalidateSocket
|
|
15
16
|
} from "../src/server/realtimeAudience.js";
|
|
16
17
|
import { createRealtimeDelivery } from "../src/server/realtimeDelivery.js";
|
|
18
|
+
import { RealtimeAudienceScopeFeature } from "../src/server/RealtimeAudienceScopeFeature.js";
|
|
19
|
+
import { createSystemContext, isJobContext } from "../../resource-runtime/src/server/contexts.js";
|
|
17
20
|
import { attachDeferredAuthService, createDeferredAuthService } from "../../auth-core/src/server/deferredAuthService.js";
|
|
18
21
|
|
|
19
22
|
const logger = Object.freeze({ debug() {}, info() {}, warn() {}, error() {} });
|
|
@@ -340,37 +343,132 @@ test("realtime delivery warns and continues when an event's scope is null", asyn
|
|
|
340
343
|
assert.deepEqual(io.emitted.map((entry) => entry.room), [["users"]]);
|
|
341
344
|
});
|
|
342
345
|
|
|
343
|
-
test("realtime delivery
|
|
346
|
+
test("realtime delivery reaches an audience's users, read once per event in the event's own scope", async () => {
|
|
344
347
|
const io = createIoDouble();
|
|
345
|
-
const
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
348
|
+
const { audienceScope } = await RealtimeAudienceScopeFeature.setup({
|
|
349
|
+
actionCatalogue: { register() {} },
|
|
350
|
+
resourceRuntime: { declareSystemScope: (feature, systemScope) => (reason) => createSystemContext({ feature, systemScope, reason }) }
|
|
351
|
+
}, {});
|
|
352
|
+
const delivery = createRealtimeDelivery({ io, logger, audiences: createAudienceContributors(), audienceScope });
|
|
353
|
+
const reads = [];
|
|
354
|
+
const audience = {
|
|
355
|
+
preset: "none",
|
|
356
|
+
async audienceUsers({ event, options }) {
|
|
357
|
+
reads.push({ entityId: event.entityId, options });
|
|
358
|
+
return ["55", 56, null, "55"];
|
|
351
359
|
}
|
|
352
|
-
}
|
|
360
|
+
};
|
|
353
361
|
await delivery.handle({
|
|
354
362
|
type: "entity.changed",
|
|
355
363
|
source: "workspace",
|
|
356
364
|
entity: "invite",
|
|
357
365
|
operation: "created",
|
|
358
366
|
entityId: "91",
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
audience: {
|
|
362
|
-
preset: "none",
|
|
363
|
-
async userQuery({ knex, event }) {
|
|
364
|
-
assert.equal(typeof knex, "function");
|
|
365
|
-
assert.equal(event.entityId, "91");
|
|
366
|
-
return [{ user_id: 55 }];
|
|
367
|
-
}
|
|
368
|
-
}
|
|
369
|
-
}
|
|
367
|
+
scope: { kind: "workspace", id: "11" },
|
|
368
|
+
realtime: { event: "users.bootstrap.changed", audience }
|
|
370
369
|
});
|
|
371
370
|
assert.equal(io.emitted.length, 1);
|
|
372
|
-
assert.deepEqual(io.emitted[0].room, ["user:55"]);
|
|
371
|
+
assert.deepEqual(io.emitted[0].room, ["user:55", "user:56"]);
|
|
373
372
|
assert.equal(Object.hasOwn(io.emitted[0].payload, "realtime"), false);
|
|
373
|
+
assert.equal(reads.length, 1);
|
|
374
|
+
assert.equal(reads[0].entityId, "91");
|
|
375
|
+
assert.deepEqual(reads[0].options.context.scopeValues, { workspaceId: "11" });
|
|
376
|
+
assert.equal(isJobContext(reads[0].options.context), true, "a context derived from the feature's system scope");
|
|
377
|
+
assert.match(reads[0].options.context.jobReason, /^realtime\.audience-scope: /u);
|
|
378
|
+
|
|
379
|
+
const scopes = [
|
|
380
|
+
[{ kind: "workspace_user", workspaceId: "11", userId: "7" }, { workspaceId: "11", userId: "7" }],
|
|
381
|
+
[{ kind: "workspace", id: "11", userId: "7" }, { workspaceId: "11", userId: "7" }],
|
|
382
|
+
[{ kind: "user", id: "7" }, { userId: "7" }]
|
|
383
|
+
];
|
|
384
|
+
for (const [scope, scopeValues] of scopes) {
|
|
385
|
+
await delivery.handle({ type: "entity.changed", entityId: "91", scope, realtime: { event: "users.bootstrap.changed", audience } });
|
|
386
|
+
assert.deepEqual(reads.at(-1).options.context.scopeValues, scopeValues);
|
|
387
|
+
}
|
|
388
|
+
await delivery.handle({ type: "entity.changed", entityId: "91", realtime: { event: "users.bootstrap.changed", audience } });
|
|
389
|
+
assert.deepEqual(reads.at(-1).options, {}, "An event without a scope reads with no context");
|
|
390
|
+
|
|
391
|
+
// A customer's or a public surface's event is scoped globally, with the workspace the request resolved as the
|
|
392
|
+
// scope's workspaceId, which the framework sets: it reads there. The payload never chooses the scope: one naming
|
|
393
|
+
// another workspace (an input id it copied) neither widens nor moves the read.
|
|
394
|
+
const payloadScopes = [
|
|
395
|
+
[{ kind: "global", id: null, workspaceId: "11" }, { workspaceId: "11" }],
|
|
396
|
+
[{ kind: "global", id: null }, null],
|
|
397
|
+
[null, null],
|
|
398
|
+
[{ kind: "workspace", id: "11" }, { workspaceId: "11" }],
|
|
399
|
+
[{ kind: "user", id: "7" }, { userId: "7" }]
|
|
400
|
+
];
|
|
401
|
+
for (const [scope, scopeValues] of payloadScopes) {
|
|
402
|
+
await delivery.handle({ type: "entity.changed", entityId: "91", ...(scope ? { scope } : {}),
|
|
403
|
+
realtime: { event: "users.bootstrap.changed", audience, payload: { workspaceId: "12" } } });
|
|
404
|
+
assert.deepEqual(reads.at(-1).options.context?.scopeValues ?? null, scopeValues);
|
|
405
|
+
}
|
|
406
|
+
assert.equal(reads.some(({ options }) => options.context?.scopeValues?.workspaceId === "12"), false);
|
|
407
|
+
const delivered = io.emitted.length;
|
|
408
|
+
await delivery.handle({ type: "entity.changed", entityId: "91", scope: { kind: "global", id: null },
|
|
409
|
+
realtime: { event: "users.bootstrap.changed", audience: "all_workspace_users", payload: { workspaceId: "12" } } });
|
|
410
|
+
assert.equal(io.emitted.slice(delivered).some(({ room }) => [room].flat().includes("workspace:12")), false);
|
|
411
|
+
});
|
|
412
|
+
|
|
413
|
+
test("without realtime.audience-scope an audience built when its action ran is refused at publish, and logged", async () => {
|
|
414
|
+
const io = createIoDouble();
|
|
415
|
+
const errors = [];
|
|
416
|
+
const delivery = createRealtimeDelivery({
|
|
417
|
+
io,
|
|
418
|
+
logger: { ...logger, error: (details, message) => errors.push({ details, message }) },
|
|
419
|
+
audiences: createAudienceContributors(),
|
|
420
|
+
audienceScope: null
|
|
421
|
+
});
|
|
422
|
+
let reads = 0;
|
|
423
|
+
const scoped = { preset: "event_scope", async audienceUsers() { reads += 1; return ["55"]; } };
|
|
424
|
+
const publicOnly = { publicTablesOnly: true, async audienceUsers() { reads += 1; return ["56"]; } };
|
|
425
|
+
await delivery.handle({ type: "entity.changed", entityId: "91", scope: { kind: "workspace", id: "11" },
|
|
426
|
+
realtime: { event: "users.bootstrap.changed", audience: [scoped, publicOnly] } });
|
|
427
|
+
assert.equal(reads, 1, "only the audience that reads public tables reads");
|
|
428
|
+
assert.deepEqual(io.emitted.map((entry) => entry.room), [["workspace:11", "user:56"]]);
|
|
429
|
+
assert.equal(errors.length, 1);
|
|
430
|
+
assert.deepEqual(errors[0].details, { socketEvent: "users.bootstrap.changed", entityId: "91" });
|
|
431
|
+
assert.match(errors[0].message, /needs realtime\.audience-scope: register RealtimeAudienceScopeFeature/u);
|
|
432
|
+
});
|
|
433
|
+
|
|
434
|
+
test("an audience entry whose read fails is logged as an error and skipped; the event still reaches the other rooms", async () => {
|
|
435
|
+
const io = createIoDouble();
|
|
436
|
+
const errors = [];
|
|
437
|
+
const delivery = createRealtimeDelivery({
|
|
438
|
+
io,
|
|
439
|
+
logger: { ...logger, error: (details, message) => errors.push({ details, message }) },
|
|
440
|
+
audiences: createAudienceContributors()
|
|
441
|
+
});
|
|
442
|
+
const failing = { preset: "event_scope", publicTablesOnly: true, async audienceUsers() { throw new Error("owner API down"); } };
|
|
443
|
+
const reading = { publicTablesOnly: true, async audienceUsers() { return ["55"]; } };
|
|
444
|
+
await delivery.handle({ type: "entity.changed", entityId: "91", scope: { kind: "workspace", id: "11" },
|
|
445
|
+
realtime: { event: "users.bootstrap.changed", audience: [failing, reading, { userId: "56" }] } });
|
|
446
|
+
assert.deepEqual(io.emitted.map((entry) => entry.room), [["workspace:11", "user:55", "user:56"]]);
|
|
447
|
+
assert.deepEqual(errors, [{
|
|
448
|
+
details: { socketEvent: "users.bootstrap.changed", entityId: "91", error: "owner API down" },
|
|
449
|
+
message: "Realtime audienceUsers failed; the event still reaches the audience's other rooms."
|
|
450
|
+
}]);
|
|
451
|
+
});
|
|
452
|
+
|
|
453
|
+
test("realtime refuses to boot when an action's events read their audience in a scope no feature provides", async (t) => {
|
|
454
|
+
const audienceUsers = async () => [];
|
|
455
|
+
const actionsWith = (audience) => ({ listDefinitions: () => [{ id: "notes.create", events: [createEntityChangedActionEvent({
|
|
456
|
+
source: "notes", entity: "note", operation: "created", entityId: 1, realtime: { event: "notes.changed", audience }
|
|
457
|
+
})] }] });
|
|
458
|
+
const boot = async (inputs) => {
|
|
459
|
+
const http = createServer();
|
|
460
|
+
t.after(() => new Promise((resolve) => http.close(() => resolve())));
|
|
461
|
+
const runtime = createCapabilityRuntime({ providers: [EventProvider, RealtimeProvider], inputs: {
|
|
462
|
+
"runtime.config": {}, "runtime.env": {}, "runtime.fastify": { server: http }, "runtime.logger": logger, ...inputs
|
|
463
|
+
} });
|
|
464
|
+
await runtime.start();
|
|
465
|
+
await runtime.shutdown();
|
|
466
|
+
};
|
|
467
|
+
await assert.rejects(boot({ "runtime.actions": actionsWith(["event_scope", { audienceUsers }]) }),
|
|
468
|
+
/Realtime events of notes\.create read their audience with audienceUsers .*register RealtimeAudienceScopeFeature/u);
|
|
469
|
+
await boot({ "runtime.actions": actionsWith({ audienceUsers, publicTablesOnly: true }) });
|
|
470
|
+
await boot({ "runtime.actions": actionsWith(() => ({ audienceUsers })) });
|
|
471
|
+
await boot({ "runtime.actions": actionsWith({ audienceUsers }), "realtime.audience-scope": {} });
|
|
374
472
|
});
|
|
375
473
|
|
|
376
474
|
test("socket audience bootstrap authenticates explicitly and joins contributed scope rooms", async () => {
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import { requireTestDatabase } from "@jskit-ai/database-runtime/server/testDatabases";
|
|
4
|
+
import { createAudienceContributors, resolveAudienceTargets, revalidateSocket } from "../src/server/realtimeAudience.js";
|
|
5
|
+
import { WorkspacesIntegrationsProvider } from "../../workspaces-core/src/server/WorkspacesIntegrationsProvider.js";
|
|
6
|
+
import { createInviteRecipientBootstrapAudience } from "../../workspaces-core/src/server/common/support/realtimeServiceEvents.js";
|
|
7
|
+
import { createWorkspacesServerI18n } from "../../workspaces-core/src/server/i18n.js";
|
|
8
|
+
import { renderDefaultWorkspaceInviteEmail } from "../../workspaces-core/src/server/workspaceMembers/defaultWorkspaceInviteEmail.js";
|
|
9
|
+
import { unconfiguredWorkspaceInviteMailer } from "../../workspaces-core/src/server/workspaceMembers/unconfiguredWorkspaceInviteMailer.js";
|
|
10
|
+
import { createWorkspaceInviteUrlBuilder } from "../../workspaces-core/src/server/workspaceMembers/workspaceInviteUrls.js";
|
|
11
|
+
import { createService as createMembersService } from "../../workspaces-core/src/server/workspaceMembers/workspaceMembersService.js";
|
|
12
|
+
import { workspacesDatabase } from "../../workspaces-core/test/support/mysqlWorkspaces.js";
|
|
13
|
+
|
|
14
|
+
// Characterization of the realtime audience against the tables it reaches through its contributors and audiences, on
|
|
15
|
+
// MariaDB/MySQL, before the workspace stores under them move onto table resources and before realtime builds the
|
|
16
|
+
// scope it reads with from the event differently: which rooms an actor's sockets join (their active workspace
|
|
17
|
+
// memberships, one read for many actors), how a revalidation follows a membership change, and which users an invite's
|
|
18
|
+
// bootstrap audience reaches, read in the event's own scope.
|
|
19
|
+
const database = workspacesDatabase("da_rt_audience");
|
|
20
|
+
|
|
21
|
+
function audiencesOf(db) {
|
|
22
|
+
const audiences = createAudienceContributors();
|
|
23
|
+
const noop = () => {};
|
|
24
|
+
WorkspacesIntegrationsProvider.setup({
|
|
25
|
+
actions: { registerContextContributor: noop },
|
|
26
|
+
authExtensions: { registerPolicyContextResolver: noop },
|
|
27
|
+
config: {
|
|
28
|
+
tenancyMode: "workspaces",
|
|
29
|
+
surfaceDefaultId: "customer",
|
|
30
|
+
surfaceDefinitions: { customer: { id: "customer", requiresWorkspace: true, accessPolicyId: "workspace_member" } },
|
|
31
|
+
surfaceAccessPolicies: { workspace_member: { requireWorkspaceMembership: true } }
|
|
32
|
+
},
|
|
33
|
+
http: { registerVisibilityResolver: noop },
|
|
34
|
+
realtime: { registerAudienceContributor: (contributor) => audiences.register(contributor) },
|
|
35
|
+
usersExtensions: { registerProfileSyncLifecycleContributor: noop },
|
|
36
|
+
workspaceMemberships: db.memberships,
|
|
37
|
+
workspaces: {
|
|
38
|
+
invitationsEnabled: false,
|
|
39
|
+
services: { directory: { async resolveWorkspaceContextForUserBySlug() { return null; } } }
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
return audiences;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function membersService(db) {
|
|
46
|
+
return createMembersService({
|
|
47
|
+
workspaceMembershipsRepository: db.memberships,
|
|
48
|
+
workspaceInvitesRepository: db.invites,
|
|
49
|
+
inviteExpiresInMs: 86400000,
|
|
50
|
+
roleCatalog: db.roleCatalog,
|
|
51
|
+
workspaceInvitationsEnabled: true,
|
|
52
|
+
inviteUrlBuilder: createWorkspaceInviteUrlBuilder({ appConfig: {}, env: {} }),
|
|
53
|
+
workspaceInviteMailer: unconfiguredWorkspaceInviteMailer,
|
|
54
|
+
workspaceInviteEmailTemplate: renderDefaultWorkspaceInviteEmail,
|
|
55
|
+
i18n: createWorkspacesServerI18n(),
|
|
56
|
+
userProfilesRepository: db.profiles,
|
|
57
|
+
userSettingsRepository: db.userSettings
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function workspaceOf(db, slug, owner) {
|
|
62
|
+
const workspace = await db.workspaces.insert({ slug, name: slug, ownerUserId: owner.id });
|
|
63
|
+
await db.memberships.ensureOwnerMembership(workspace.id, owner.id);
|
|
64
|
+
return workspace;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const roomsOf = (workspaceId, userId) => [`workspace:${workspaceId}`, `workspace:${workspaceId}:user:${userId}`];
|
|
68
|
+
|
|
69
|
+
test("an actor's contributed rooms are their active workspace memberships, read at the same cost for many actors as for one", async () => {
|
|
70
|
+
requireTestDatabase(process.env);
|
|
71
|
+
const db = await database.open();
|
|
72
|
+
const audiences = audiencesOf(db);
|
|
73
|
+
const owner = await db.createProfile("rooms-owner");
|
|
74
|
+
const member = await db.createProfile("rooms-member");
|
|
75
|
+
const outsider = await db.createProfile("rooms-outsider");
|
|
76
|
+
const first = await workspaceOf(db, "rooms-first", owner);
|
|
77
|
+
const second = await workspaceOf(db, "rooms-second", owner);
|
|
78
|
+
const left = await workspaceOf(db, "rooms-left", owner);
|
|
79
|
+
await db.memberships.addMember({ workspaceId: second.id, userId: member.id });
|
|
80
|
+
await db.memberships.upsertMembership(left.id, member.id, { roleSid: "member", status: "revoked" });
|
|
81
|
+
|
|
82
|
+
const statementsOf = async (work) => {
|
|
83
|
+
let count = 0;
|
|
84
|
+
const onQuery = () => {
|
|
85
|
+
count += 1;
|
|
86
|
+
};
|
|
87
|
+
db.knex.on("query", onQuery);
|
|
88
|
+
try {
|
|
89
|
+
return { result: await work(), count };
|
|
90
|
+
} finally {
|
|
91
|
+
db.knex.removeListener("query", onQuery);
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
const one = await statementsOf(() => audiences.resolveActorsRooms([owner.id]));
|
|
95
|
+
const { result: rooms, count } = await statementsOf(() => audiences.resolveActorsRooms([owner.id, member.id, outsider.id]));
|
|
96
|
+
assert.deepEqual([...rooms.keys()], [owner.id, member.id, outsider.id]);
|
|
97
|
+
assert.deepEqual([...rooms.get(owner.id)].sort(), [...roomsOf(first.id, owner.id), ...roomsOf(second.id, owner.id),
|
|
98
|
+
...roomsOf(left.id, owner.id)].sort());
|
|
99
|
+
assert.deepEqual([...rooms.get(member.id)].sort(), roomsOf(second.id, member.id).sort(), "a revoked membership gives no room");
|
|
100
|
+
assert.deepEqual([...rooms.get(outsider.id)], [], "an actor without memberships is answered with no rooms");
|
|
101
|
+
assert.equal(count, one.count, `the same reads for three actors as for one (${one.count} and ${count} statements)`);
|
|
102
|
+
assert.deepEqual([...(await audiences.resolveActorRooms(member.id))].sort(), roomsOf(second.id, member.id).sort());
|
|
103
|
+
assert.deepEqual(await audiences.resolveActorsRooms([]), new Map());
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
test("a revalidated socket joins the rooms of a new membership and leaves those of a removed one", async () => {
|
|
107
|
+
requireTestDatabase(process.env);
|
|
108
|
+
const db = await database.open();
|
|
109
|
+
const audiences = audiencesOf(db);
|
|
110
|
+
const owner = await db.createProfile("socket-owner");
|
|
111
|
+
const member = await db.createProfile("socket-member");
|
|
112
|
+
const workspace = await workspaceOf(db, "socket-team", owner);
|
|
113
|
+
const joined = new Set(["clients", "users", `user:${member.id}`]);
|
|
114
|
+
const socket = {
|
|
115
|
+
data: { actorId: member.id },
|
|
116
|
+
disconnected: false,
|
|
117
|
+
async join(room) { joined.add(room); },
|
|
118
|
+
async leave(room) { joined.delete(room); },
|
|
119
|
+
disconnect() { this.disconnected = true; }
|
|
120
|
+
};
|
|
121
|
+
const authService = { realtime: { requireAuthentication: true } };
|
|
122
|
+
const revalidate = () => revalidateSocket({
|
|
123
|
+
socket,
|
|
124
|
+
authService,
|
|
125
|
+
audiences,
|
|
126
|
+
request: {},
|
|
127
|
+
authenticateRequest: async () => ({ authenticated: true, actor: { id: member.id } })
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
assert.deepEqual(await revalidate(), { id: member.id });
|
|
131
|
+
assert.deepEqual([...joined].sort(), ["clients", "users", `user:${member.id}`].sort(), "no membership yet: no workspace room");
|
|
132
|
+
await db.memberships.addMember({ workspaceId: workspace.id, userId: member.id });
|
|
133
|
+
await revalidate();
|
|
134
|
+
assert.deepEqual([...joined].sort(), ["clients", "users", `user:${member.id}`, ...roomsOf(workspace.id, member.id)].sort());
|
|
135
|
+
assert.deepEqual([...socket.data.contributedRooms].sort(), roomsOf(workspace.id, member.id).sort());
|
|
136
|
+
await db.memberships.upsertMembership(workspace.id, member.id, { roleSid: "member", status: "revoked" });
|
|
137
|
+
await revalidate();
|
|
138
|
+
assert.deepEqual([...joined].sort(), ["clients", "users", `user:${member.id}`].sort(), "a removed member leaves the rooms");
|
|
139
|
+
assert.deepEqual(socket.data.contributedRooms, []);
|
|
140
|
+
assert.equal(socket.disconnected, false);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
test("an invite's bootstrap audience reaches the event's scope room and the user the invite's email belongs to", async () => {
|
|
144
|
+
requireTestDatabase(process.env);
|
|
145
|
+
const db = await database.open();
|
|
146
|
+
const members = membersService(db);
|
|
147
|
+
const audience = createInviteRecipientBootstrapAudience({ inviteRecipientUserIds: members.inviteRecipientUserIds });
|
|
148
|
+
const warnings = [];
|
|
149
|
+
const logger = { warn: (details, message) => warnings.push({ details, message }) };
|
|
150
|
+
const owner = await db.createProfile("invite-owner");
|
|
151
|
+
const workspace = await workspaceOf(db, "invite-team", owner);
|
|
152
|
+
const other = await workspaceOf(db, "invite-other", owner);
|
|
153
|
+
const invited = (await members.createInvite(workspace, owner, { email: "invite-reader@example.test" })).value.createdInviteId;
|
|
154
|
+
const event = (scope) => ({ type: "entity.changed", entityId: invited, ...(scope ? { scope } : {}) });
|
|
155
|
+
const targets = (scope) => resolveAudienceTargets(audience, event(scope), { logger });
|
|
156
|
+
|
|
157
|
+
assert.deepEqual(await targets({ kind: "workspace", id: workspace.id }), {
|
|
158
|
+
broadcastAllClients: false,
|
|
159
|
+
rooms: [`workspace:${workspace.id}`]
|
|
160
|
+
}, "before the person signs up, only the scope's room");
|
|
161
|
+
const reader = await db.createProfile("invite-reader");
|
|
162
|
+
assert.deepEqual(await targets({ kind: "workspace", id: workspace.id }), {
|
|
163
|
+
broadcastAllClients: false,
|
|
164
|
+
rooms: [`workspace:${workspace.id}`, `user:${reader.id}`]
|
|
165
|
+
});
|
|
166
|
+
assert.deepEqual((await targets({ kind: "user", id: reader.id })).rooms, [`user:${reader.id}`]);
|
|
167
|
+
assert.deepEqual((await targets({ kind: "workspace_user", workspaceId: workspace.id, userId: owner.id })).rooms,
|
|
168
|
+
[`workspace:${workspace.id}:user:${owner.id}`, `user:${reader.id}`]);
|
|
169
|
+
// Pinned as it is: the scope the read gets names the event's workspace, but the invite read does not narrow to it,
|
|
170
|
+
// so an event scoped to another workspace still reaches the invite's recipient.
|
|
171
|
+
assert.deepEqual((await targets({ kind: "workspace", id: other.id })).rooms, [`workspace:${other.id}`, `user:${reader.id}`]);
|
|
172
|
+
assert.deepEqual((await targets(null)).rooms, [`user:${reader.id}`], "an event without a scope reaches the recipient only");
|
|
173
|
+
assert.deepEqual(warnings.map(({ message }) => message), ["Realtime event_scope audience has no deliverable scope."]);
|
|
174
|
+
|
|
175
|
+
await members.revokeInvite(workspace, invited);
|
|
176
|
+
assert.deepEqual((await targets({ kind: "workspace", id: workspace.id })).rooms, [`workspace:${workspace.id}`, `user:${reader.id}`],
|
|
177
|
+
"a revoked invite still reaches its recipient, so their pending list refreshes");
|
|
178
|
+
const missing = await resolveAudienceTargets(audience, { type: "entity.changed", entityId: "999999999",
|
|
179
|
+
scope: { kind: "workspace", id: workspace.id } }, { logger });
|
|
180
|
+
assert.deepEqual(missing.rooms, [`workspace:${workspace.id}`]);
|
|
181
|
+
});
|