@terreno/api 57.20.0 → 58.0.0-beta.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/CHANGELOG.md +93 -0
- package/README.md +1 -1
- package/biome.jsonc +3 -2
- package/dist/api.d.ts +3 -16
- package/dist/api.js +0 -9
- package/dist/auth.d.ts +3 -2
- package/dist/auth.js +95 -5
- package/dist/authRecovery.d.ts +2 -1
- package/dist/authRecovery.js +35 -17
- package/dist/collectionRegistry.d.ts +3 -4
- package/dist/collectionRegistry.js +0 -1
- package/dist/consentApp.d.ts +1 -1
- package/dist/consentApp.js +58 -2
- package/dist/frameworkModelNames.d.ts +4 -0
- package/dist/frameworkModelNames.js +4 -0
- package/dist/index.d.ts +8 -5
- package/dist/index.js +14 -20
- package/dist/mcp/adminTracking.d.ts +28 -0
- package/dist/mcp/adminTracking.js +80 -0
- package/dist/mcp/auth.d.ts +6 -0
- package/dist/mcp/auth.js +12 -2
- package/dist/mcp/server.d.ts +8 -0
- package/dist/mcp/server.js +48 -4
- package/dist/mcp/serviceTokens.d.ts +21 -1
- package/dist/mcp/serviceTokens.js +159 -183
- package/dist/migrations/builtin/mcpServiceTokenStringIds.d.ts +18 -0
- package/dist/migrations/builtin/mcpServiceTokenStringIds.js +67 -0
- package/dist/models/mcpOAuthToken.js +27 -0
- package/dist/models/mcpRequestLog.d.ts +2 -0
- package/dist/models/mcpRequestLog.js +73 -0
- package/dist/models/mcpServiceToken.js +40 -4
- package/dist/models/mcpToolSetting.d.ts +2 -0
- package/dist/models/mcpToolSetting.js +119 -0
- package/dist/models/versionConfig.d.ts +2 -0
- package/dist/openApiBuilder.d.ts +4 -0
- package/dist/openApiBuilder.js +2 -0
- package/dist/rbac/auditModel.d.ts +2 -1
- package/dist/rbac/realtimeAccess.d.ts +5 -4
- package/dist/rbac/realtimeAccess.js +17 -64
- package/dist/realtime/changeStreamWatcher.d.ts +8 -63
- package/dist/realtime/changeStreamWatcher.js +32 -391
- package/dist/realtime/realtimeApp.d.ts +14 -27
- package/dist/realtime/realtimeApp.js +14 -220
- package/dist/realtime/types.d.ts +0 -64
- package/dist/sync/executors.js +14 -2
- package/dist/sync/socketHandlers.d.ts +1 -1
- package/dist/sync/socketHandlers.js +1 -1
- package/dist/terrenoApp.d.ts +19 -5
- package/dist/terrenoApp.js +21 -14
- package/dist/tests/models.d.ts +17 -22
- package/dist/tests/models.js +7 -1
- package/dist/tests/openApiResponseSchema.d.ts +39 -0
- package/dist/tests/openApiResponseSchema.js +56 -0
- package/dist/tests/testHelper.d.ts +6 -12
- package/dist/tests.d.ts +2 -0
- package/dist/tests.js +6 -1
- package/dist/types/mcpAdmin.d.ts +58 -0
- package/dist/types/mcpAdmin.js +2 -0
- package/dist/types/mcpOAuth.d.ts +2 -0
- package/dist/types/mcpServiceToken.d.ts +9 -4
- package/dist/versionCheckPlugin.d.ts +1 -1
- package/dist/versionCheckPlugin.js +25 -2
- package/e2e/smoke.ts +193 -0
- package/package.json +14 -8
- package/src/__snapshots__/openApi.test.ts.snap +4986 -2478
- package/src/__snapshots__/openApiBuilder.test.ts.snap +836 -0
- package/src/__tests__/openApiResponseSchema.test.ts +148 -0
- package/src/__tests__/versionCheckPlugin.test.ts +72 -0
- package/src/adminModelRouter.test.ts +8 -6
- package/src/api.arrayOperations.test.ts +31 -22
- package/src/api.hooks.test.ts +12 -11
- package/src/api.query.test.ts +2 -2
- package/src/api.test.ts +17 -14
- package/src/api.ts +3 -27
- package/src/audit/auditApp.test.ts +1 -1
- package/src/audit/cloudTasksEnqueue.test.ts +19 -14
- package/src/auth.test.ts +21 -7
- package/src/auth.ts +116 -5
- package/src/authOpenApi.test.ts +316 -0
- package/src/authRecovery.test.ts +10 -10
- package/src/authRecovery.ts +47 -19
- package/src/authVerification.test.ts +7 -7
- package/src/betterAuthFeatures.test.ts +3 -2
- package/src/betterAuthLinking.test.ts +3 -1
- package/src/betterAuthOAuthHandoff.test.ts +13 -5
- package/src/betterAuthSetup.test.ts +77 -51
- package/src/collectionRegistry.test.ts +4 -4
- package/src/collectionRegistry.ts +3 -5
- package/src/consentApp.test.ts +98 -0
- package/src/consentApp.ts +67 -2
- package/src/frameworkModelNames.test.ts +8 -0
- package/src/frameworkModelNames.ts +4 -0
- package/src/githubAuth.test.ts +11 -11
- package/src/index.ts +14 -28
- package/src/isolated/migrateCliConnect.isolated.ts +3 -2
- package/src/mcp/actionTools.test.ts +13 -7
- package/src/mcp/adminTracking.test.ts +272 -0
- package/src/mcp/adminTracking.ts +104 -0
- package/src/mcp/auth.test.ts +7 -3
- package/src/mcp/auth.ts +18 -2
- package/src/mcp/oauth.test.ts +13 -13
- package/src/mcp/server.ts +67 -4
- package/src/mcp/serviceTokens.sync.test.ts +230 -0
- package/src/mcp/serviceTokens.test.ts +114 -62
- package/src/mcp/serviceTokens.ts +193 -212
- package/src/mcp/toolGenerator.test.ts +9 -5
- package/src/migrations/builtin/mcpServiceTokenStringIds.test.ts +194 -0
- package/src/migrations/builtin/mcpServiceTokenStringIds.ts +121 -0
- package/src/migrations/cli.test.ts +15 -14
- package/src/migrations/cli.ts +1 -1
- package/src/migrations/generate.test.ts +2 -2
- package/src/migrations/load.test.ts +1 -1
- package/src/migrations/lock.test.ts +8 -3
- package/src/migrations/runner.test.ts +16 -5
- package/src/migrations/schemaCatalog.test.ts +4 -1
- package/src/models/mcpOAuthToken.test.ts +42 -0
- package/src/models/mcpOAuthToken.ts +32 -0
- package/src/models/mcpRequestLog.ts +81 -0
- package/src/models/mcpServiceToken.test.ts +75 -5
- package/src/models/mcpServiceToken.ts +61 -14
- package/src/models/mcpToolSetting.test.ts +69 -0
- package/src/models/mcpToolSetting.ts +138 -0
- package/src/models/versionConfig.ts +2 -0
- package/src/notifications/notificationsApp.test.ts +5 -8
- package/src/notifiers/slackWebApi.test.ts +30 -8
- package/src/openApi.test.ts +4 -4
- package/src/openApiBuilder.test.ts +34 -1
- package/src/openApiBuilder.ts +5 -0
- package/src/openApiValidator.test.ts +3 -3
- package/src/orgs/orgPermissions.test.ts +2 -2
- package/src/orgs/orgPlugin.test.ts +4 -3
- package/src/orgs/orgSecurityDefects.test.ts +3 -1
- package/src/orgs/organizationSettings.test.ts +1 -1
- package/src/orgs/orgsApp.test.ts +5 -3
- package/src/permissions.test.ts +2 -2
- package/src/rateLimit/rateLimit.test.ts +25 -10
- package/src/rateLimit/redisStore.ioredis.test.ts +3 -2
- package/src/rbac/assertAllowed.test.ts +1 -1
- package/src/rbac/auditModel.ts +10 -2
- package/src/rbac/realtimeAccess.test.ts +20 -171
- package/src/rbac/realtimeAccess.ts +17 -82
- package/src/rbac/routes.test.ts +1 -1
- package/src/rbac/userWriteGuards.test.ts +8 -5
- package/src/realtime/changeStreamWatcher.ts +43 -506
- package/src/realtime/realtime.test.ts +211 -2547
- package/src/realtime/realtimeApp.ts +16 -295
- package/src/realtime/types.ts +0 -72
- package/src/scrubAdminFields.test.ts +1 -1
- package/src/sync/adminWindowMutation.test.ts +4 -3
- package/src/sync/executors.test.ts +29 -1
- package/src/sync/executors.ts +23 -2
- package/src/sync/scripts/compactTombstones.test.ts +4 -3
- package/src/sync/socketHandlers.ts +1 -1
- package/src/sync/sync.test.ts +1 -1
- package/src/sync/syncPhaseC.test.ts +14 -11
- package/src/sync/syncRoutes.test.ts +8 -8
- package/src/sync/syncSeqPlugin.test.ts +1 -2
- package/src/sync/syncSocket.test.ts +78 -113
- package/src/terrenoApp.mcpServiceTokens.test.ts +16 -8
- package/src/terrenoApp.migrations.test.ts +8 -7
- package/src/terrenoApp.ts +38 -18
- package/src/tests/betterAuthStubs.ts +3 -2
- package/src/tests/bunSetup.ts +1 -1
- package/src/tests/models.ts +10 -0
- package/src/tests/openApiResponseSchema.ts +104 -0
- package/src/tests/testEnv.ts +7 -0
- package/src/tests.ts +8 -0
- package/src/types/mcpAdmin.ts +80 -0
- package/src/types/mcpOAuth.ts +5 -0
- package/src/types/mcpServiceToken.ts +12 -4
- package/src/versionCheckPlugin.ts +41 -2
- package/src/webhooks/verifiers/hmac.test.ts +1 -1
- package/tsconfig.typecheck.json +14 -0
- package/dist/realtime/deprecation.d.ts +0 -13
- package/dist/realtime/deprecation.js +0 -31
- package/dist/realtime/queryStore.d.ts +0 -37
- package/dist/realtime/queryStore.js +0 -103
- package/dist/realtime/registry.d.ts +0 -15
- package/dist/realtime/registry.js +0 -52
- package/src/realtime/deprecation.test.ts +0 -60
- package/src/realtime/deprecation.ts +0 -33
- package/src/realtime/queryStore.ts +0 -122
- package/src/realtime/registry.ts +0 -84
|
@@ -1,84 +1,45 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Tests for the realtime module's pure functions and classes:
|
|
3
3
|
* - queryMatcher.ts (matchesQuery)
|
|
4
|
-
* - queryStore.ts (addQuerySubscription, removeQuerySubscription, etc.)
|
|
5
|
-
* - registry.ts (registerRealtime, getRealtimeRegistry, etc.)
|
|
6
4
|
* - realtimeApp.ts (RealtimeApp class — register, getIo, close)
|
|
7
|
-
* - realtimeApp.ts (installRealtimeSocketHandlers —
|
|
8
|
-
* - changeStreamWatcher.ts (
|
|
5
|
+
* - realtimeApp.ts (installRealtimeSocketHandlers — per-user room joins)
|
|
6
|
+
* - changeStreamWatcher.ts (authorized room emitter, watcher lifecycle)
|
|
9
7
|
*/
|
|
10
8
|
|
|
11
|
-
import {afterEach,
|
|
12
|
-
import {assert} from "chai";
|
|
9
|
+
import {afterEach, beforeEach, describe, expect, it, mock} from "bun:test";
|
|
13
10
|
import express from "express";
|
|
14
|
-
import mongoose
|
|
11
|
+
import mongoose from "mongoose";
|
|
15
12
|
import type {Server} from "socket.io";
|
|
16
13
|
|
|
17
|
-
import type {JSONValue, ModelRouterOptions} from "../api";
|
|
18
|
-
|
|
19
14
|
import {clearAdminBroadcastScopes, registerAdminBroadcastScope} from "../sync/adminBroadcastScope";
|
|
20
15
|
import {
|
|
21
|
-
|
|
22
|
-
|
|
16
|
+
type AuthorizedEmitEntry,
|
|
17
|
+
emitPayloadToAuthorizedRoom,
|
|
23
18
|
ensureApiId,
|
|
24
19
|
mapOperationType,
|
|
25
|
-
resolveRooms,
|
|
26
|
-
serializeDoc,
|
|
27
20
|
startChangeStreamWatcher,
|
|
28
21
|
stopChangeStreamWatcher,
|
|
29
22
|
} from "./changeStreamWatcher";
|
|
30
23
|
import {matchesQuery} from "./queryMatcher";
|
|
31
|
-
import {
|
|
32
|
-
addQuerySubscription,
|
|
33
|
-
clearQueryStore,
|
|
34
|
-
computeQueryId,
|
|
35
|
-
getQuerySubscriptionsForCollection,
|
|
36
|
-
removeAllSocketQueries,
|
|
37
|
-
removeQuerySubscription,
|
|
38
|
-
} from "./queryStore";
|
|
39
24
|
import {
|
|
40
25
|
installRealtimeSocketHandlers,
|
|
41
|
-
MAX_MODEL_SUBSCRIPTIONS,
|
|
42
|
-
MAX_QUERY_SUBSCRIPTIONS,
|
|
43
26
|
RealtimeApp,
|
|
44
27
|
type RealtimeSocketLike,
|
|
45
28
|
redactCredentials,
|
|
46
29
|
} from "./realtimeApp";
|
|
47
|
-
import {
|
|
48
|
-
clearRealtimeRegistry,
|
|
49
|
-
findRegistryEntryByCollection,
|
|
50
|
-
findRegistryEntryByRoutePath,
|
|
51
|
-
getRealtimeRegistry,
|
|
52
|
-
type RealtimeRegistryEntry,
|
|
53
|
-
registerRealtime,
|
|
54
|
-
updateRealtimeRegistryOptions,
|
|
55
|
-
} from "./registry";
|
|
56
30
|
import type {DecodedRealtimeToken} from "./socketUser";
|
|
57
|
-
import type {RealtimeConfig, RealtimeEvent} from "./types";
|
|
58
31
|
|
|
59
32
|
type ChangeStreamDoc = Parameters<typeof mapOperationType>[1];
|
|
60
33
|
|
|
61
34
|
const asChange = (change: Record<string, unknown>): ChangeStreamDoc =>
|
|
62
35
|
change as unknown as ChangeStreamDoc;
|
|
63
36
|
|
|
64
|
-
type ResponseHandler = NonNullable<ModelRouterOptions<unknown>["responseHandler"]>;
|
|
65
|
-
|
|
66
37
|
interface MockRoomSocket {
|
|
67
38
|
decodedToken?: DecodedRealtimeToken;
|
|
68
39
|
emit: (event: string, payload: unknown) => void;
|
|
69
40
|
id: string;
|
|
70
41
|
}
|
|
71
42
|
|
|
72
|
-
const permissiveOptions: ModelRouterOptions<unknown> = {
|
|
73
|
-
permissions: {
|
|
74
|
-
create: [() => true],
|
|
75
|
-
delete: [() => true],
|
|
76
|
-
list: [() => true],
|
|
77
|
-
read: [() => true],
|
|
78
|
-
update: [() => true],
|
|
79
|
-
},
|
|
80
|
-
};
|
|
81
|
-
|
|
82
43
|
const setConnectionDb = (db: unknown): void => {
|
|
83
44
|
(mongoose.connection as unknown as {db: unknown}).db = db;
|
|
84
45
|
};
|
|
@@ -370,287 +331,6 @@ describe("matchesQuery", () => {
|
|
|
370
331
|
});
|
|
371
332
|
});
|
|
372
333
|
|
|
373
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
374
|
-
// queryStore tests
|
|
375
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
376
|
-
|
|
377
|
-
describe("queryStore", () => {
|
|
378
|
-
beforeEach(() => {
|
|
379
|
-
clearQueryStore();
|
|
380
|
-
clearAdminBroadcastScopes();
|
|
381
|
-
});
|
|
382
|
-
|
|
383
|
-
afterEach(() => {
|
|
384
|
-
clearQueryStore();
|
|
385
|
-
clearAdminBroadcastScopes();
|
|
386
|
-
});
|
|
387
|
-
|
|
388
|
-
describe("computeQueryId", () => {
|
|
389
|
-
it("produces a deterministic id from collection and query", () => {
|
|
390
|
-
const id1 = computeQueryId("todos", {completed: false});
|
|
391
|
-
const id2 = computeQueryId("todos", {completed: false});
|
|
392
|
-
expect(id1).toBe(id2);
|
|
393
|
-
});
|
|
394
|
-
|
|
395
|
-
it("normalizes key order before computing id", () => {
|
|
396
|
-
const id1 = computeQueryId("todos", {completed: false, ownerId: "abc"});
|
|
397
|
-
const id2 = computeQueryId("todos", {completed: false, ownerId: "abc"});
|
|
398
|
-
expect(id1).toBe(id2);
|
|
399
|
-
});
|
|
400
|
-
|
|
401
|
-
it("includes the collection name in the id", () => {
|
|
402
|
-
const id = computeQueryId("todos", {completed: false});
|
|
403
|
-
expect(id.startsWith("todos:")).toBe(true);
|
|
404
|
-
});
|
|
405
|
-
|
|
406
|
-
it("produces different ids for different collections", () => {
|
|
407
|
-
const id1 = computeQueryId("todos", {completed: false});
|
|
408
|
-
const id2 = computeQueryId("items", {completed: false});
|
|
409
|
-
expect(id1).not.toBe(id2);
|
|
410
|
-
});
|
|
411
|
-
|
|
412
|
-
it("produces different ids for different queries", () => {
|
|
413
|
-
const id1 = computeQueryId("todos", {completed: false});
|
|
414
|
-
const id2 = computeQueryId("todos", {completed: true});
|
|
415
|
-
expect(id1).not.toBe(id2);
|
|
416
|
-
});
|
|
417
|
-
});
|
|
418
|
-
|
|
419
|
-
describe("addQuerySubscription", () => {
|
|
420
|
-
it("stores a subscription and makes it retrievable", () => {
|
|
421
|
-
addQuerySubscription("socket1", "todos", {completed: false}, "todos:q1");
|
|
422
|
-
const subs = getQuerySubscriptionsForCollection("todos");
|
|
423
|
-
expect(subs).toHaveLength(1);
|
|
424
|
-
expect(subs[0].queryId).toBe("todos:q1");
|
|
425
|
-
});
|
|
426
|
-
|
|
427
|
-
it("allows the same socket to subscribe to multiple queries", () => {
|
|
428
|
-
addQuerySubscription("socket1", "todos", {completed: false}, "todos:q1");
|
|
429
|
-
addQuerySubscription("socket1", "todos", {completed: true}, "todos:q2");
|
|
430
|
-
const subs = getQuerySubscriptionsForCollection("todos");
|
|
431
|
-
expect(subs).toHaveLength(2);
|
|
432
|
-
});
|
|
433
|
-
|
|
434
|
-
it("allows multiple sockets to subscribe to the same query", () => {
|
|
435
|
-
addQuerySubscription("socket1", "todos", {completed: false}, "todos:q1");
|
|
436
|
-
addQuerySubscription("socket2", "todos", {completed: false}, "todos:q1");
|
|
437
|
-
const subs = getQuerySubscriptionsForCollection("todos");
|
|
438
|
-
// Same queryId — deduplicated in the store
|
|
439
|
-
expect(subs).toHaveLength(1);
|
|
440
|
-
});
|
|
441
|
-
});
|
|
442
|
-
|
|
443
|
-
describe("removeQuerySubscription", () => {
|
|
444
|
-
it("removes a specific query for a socket", () => {
|
|
445
|
-
addQuerySubscription("socket1", "todos", {completed: false}, "todos:q1");
|
|
446
|
-
removeQuerySubscription("socket1", "todos:q1");
|
|
447
|
-
const subs = getQuerySubscriptionsForCollection("todos");
|
|
448
|
-
expect(subs).toHaveLength(0);
|
|
449
|
-
});
|
|
450
|
-
|
|
451
|
-
it("does not remove a query if another socket still uses it", () => {
|
|
452
|
-
addQuerySubscription("socket1", "todos", {completed: false}, "todos:q1");
|
|
453
|
-
addQuerySubscription("socket2", "todos", {completed: false}, "todos:q1");
|
|
454
|
-
removeQuerySubscription("socket1", "todos:q1");
|
|
455
|
-
const subs = getQuerySubscriptionsForCollection("todos");
|
|
456
|
-
expect(subs).toHaveLength(1);
|
|
457
|
-
});
|
|
458
|
-
|
|
459
|
-
it("is safe to call for a socket that has no subscriptions", () => {
|
|
460
|
-
expect(() => removeQuerySubscription("nonexistent", "todos:q1")).not.toThrow();
|
|
461
|
-
});
|
|
462
|
-
});
|
|
463
|
-
|
|
464
|
-
describe("removeAllSocketQueries", () => {
|
|
465
|
-
it("removes all subscriptions for a socket", () => {
|
|
466
|
-
addQuerySubscription("socket1", "todos", {completed: false}, "todos:q1");
|
|
467
|
-
addQuerySubscription("socket1", "todos", {completed: true}, "todos:q2");
|
|
468
|
-
removeAllSocketQueries("socket1");
|
|
469
|
-
const subs = getQuerySubscriptionsForCollection("todos");
|
|
470
|
-
expect(subs).toHaveLength(0);
|
|
471
|
-
});
|
|
472
|
-
|
|
473
|
-
it("preserves subscriptions for other sockets", () => {
|
|
474
|
-
addQuerySubscription("socket1", "todos", {completed: false}, "todos:q1");
|
|
475
|
-
addQuerySubscription("socket2", "todos", {completed: true}, "todos:q2");
|
|
476
|
-
removeAllSocketQueries("socket1");
|
|
477
|
-
const subs = getQuerySubscriptionsForCollection("todos");
|
|
478
|
-
expect(subs).toHaveLength(1);
|
|
479
|
-
expect(subs[0].queryId).toBe("todos:q2");
|
|
480
|
-
});
|
|
481
|
-
|
|
482
|
-
it("is safe to call for a socket that has no subscriptions", () => {
|
|
483
|
-
expect(() => removeAllSocketQueries("nonexistent")).not.toThrow();
|
|
484
|
-
});
|
|
485
|
-
|
|
486
|
-
it("only removes a shared query if no other sockets use it", () => {
|
|
487
|
-
addQuerySubscription("socket1", "todos", {completed: false}, "todos:q1");
|
|
488
|
-
addQuerySubscription("socket2", "todos", {completed: false}, "todos:q1");
|
|
489
|
-
removeAllSocketQueries("socket1");
|
|
490
|
-
// socket2 still subscribes — query should remain
|
|
491
|
-
const subs = getQuerySubscriptionsForCollection("todos");
|
|
492
|
-
expect(subs).toHaveLength(1);
|
|
493
|
-
});
|
|
494
|
-
});
|
|
495
|
-
|
|
496
|
-
describe("getQuerySubscriptionsForCollection", () => {
|
|
497
|
-
it("returns only subscriptions for the given collection", () => {
|
|
498
|
-
addQuerySubscription("socket1", "todos", {completed: false}, "todos:q1");
|
|
499
|
-
addQuerySubscription("socket2", "items", {status: "active"}, "items:q1");
|
|
500
|
-
const todoSubs = getQuerySubscriptionsForCollection("todos");
|
|
501
|
-
expect(todoSubs).toHaveLength(1);
|
|
502
|
-
expect(todoSubs[0].queryId).toBe("todos:q1");
|
|
503
|
-
});
|
|
504
|
-
|
|
505
|
-
it("returns an empty array when no subscriptions exist for collection", () => {
|
|
506
|
-
const subs = getQuerySubscriptionsForCollection("nonexistent");
|
|
507
|
-
expect(subs).toHaveLength(0);
|
|
508
|
-
});
|
|
509
|
-
|
|
510
|
-
it("returns query data for each subscription", () => {
|
|
511
|
-
const query = {completed: false, ownerId: "user1"};
|
|
512
|
-
addQuerySubscription("socket1", "todos", query, "todos:q1");
|
|
513
|
-
const subs = getQuerySubscriptionsForCollection("todos");
|
|
514
|
-
expect(subs[0].query).toEqual(query);
|
|
515
|
-
});
|
|
516
|
-
});
|
|
517
|
-
|
|
518
|
-
describe("clearQueryStore", () => {
|
|
519
|
-
it("removes all subscriptions", () => {
|
|
520
|
-
addQuerySubscription("socket1", "todos", {completed: false}, "todos:q1");
|
|
521
|
-
addQuerySubscription("socket2", "items", {status: "active"}, "items:q1");
|
|
522
|
-
clearQueryStore();
|
|
523
|
-
expect(getQuerySubscriptionsForCollection("todos")).toHaveLength(0);
|
|
524
|
-
expect(getQuerySubscriptionsForCollection("items")).toHaveLength(0);
|
|
525
|
-
});
|
|
526
|
-
});
|
|
527
|
-
});
|
|
528
|
-
|
|
529
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
530
|
-
// registry tests
|
|
531
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
532
|
-
|
|
533
|
-
describe("realtimeRegistry", () => {
|
|
534
|
-
const makeEntry = (overrides: Partial<RealtimeRegistryEntry> = {}): RealtimeRegistryEntry => ({
|
|
535
|
-
collectionName: "todos",
|
|
536
|
-
config: {
|
|
537
|
-
methods: ["create" as const, "update" as const, "delete" as const],
|
|
538
|
-
roomStrategy: "owner" as const,
|
|
539
|
-
},
|
|
540
|
-
modelName: "Todo",
|
|
541
|
-
options: permissiveOptions,
|
|
542
|
-
routePath: "/todos",
|
|
543
|
-
...overrides,
|
|
544
|
-
});
|
|
545
|
-
|
|
546
|
-
beforeEach(() => {
|
|
547
|
-
clearRealtimeRegistry();
|
|
548
|
-
});
|
|
549
|
-
|
|
550
|
-
afterEach(() => {
|
|
551
|
-
clearRealtimeRegistry();
|
|
552
|
-
});
|
|
553
|
-
|
|
554
|
-
describe("registerRealtime", () => {
|
|
555
|
-
it("adds an entry to the registry", () => {
|
|
556
|
-
registerRealtime(makeEntry());
|
|
557
|
-
expect(getRealtimeRegistry()).toHaveLength(1);
|
|
558
|
-
});
|
|
559
|
-
|
|
560
|
-
it("allows multiple entries", () => {
|
|
561
|
-
registerRealtime(makeEntry({modelName: "Todo", routePath: "/todos"}));
|
|
562
|
-
registerRealtime(
|
|
563
|
-
makeEntry({collectionName: "items", modelName: "Item", routePath: "/items"})
|
|
564
|
-
);
|
|
565
|
-
expect(getRealtimeRegistry()).toHaveLength(2);
|
|
566
|
-
});
|
|
567
|
-
});
|
|
568
|
-
|
|
569
|
-
describe("getRealtimeRegistry", () => {
|
|
570
|
-
it("returns all registered entries", () => {
|
|
571
|
-
registerRealtime(makeEntry({modelName: "Todo"}));
|
|
572
|
-
registerRealtime(
|
|
573
|
-
makeEntry({collectionName: "items", modelName: "Item", routePath: "/items"})
|
|
574
|
-
);
|
|
575
|
-
const registry = getRealtimeRegistry();
|
|
576
|
-
expect(registry).toHaveLength(2);
|
|
577
|
-
expect(registry.map((e) => e.modelName)).toEqual(["Todo", "Item"]);
|
|
578
|
-
});
|
|
579
|
-
|
|
580
|
-
it("returns empty array when nothing is registered", () => {
|
|
581
|
-
expect(getRealtimeRegistry()).toHaveLength(0);
|
|
582
|
-
});
|
|
583
|
-
});
|
|
584
|
-
|
|
585
|
-
describe("findRegistryEntryByCollection", () => {
|
|
586
|
-
it("finds an entry by collection name", () => {
|
|
587
|
-
registerRealtime(makeEntry({collectionName: "todos"}));
|
|
588
|
-
const entry = findRegistryEntryByCollection("todos");
|
|
589
|
-
expect(entry).toBeDefined();
|
|
590
|
-
expect(entry?.collectionName).toBe("todos");
|
|
591
|
-
});
|
|
592
|
-
|
|
593
|
-
it("returns undefined for unknown collection", () => {
|
|
594
|
-
const entry = findRegistryEntryByCollection("nonexistent");
|
|
595
|
-
expect(entry).toBeUndefined();
|
|
596
|
-
});
|
|
597
|
-
|
|
598
|
-
it("returns first match when multiple entries exist", () => {
|
|
599
|
-
registerRealtime(makeEntry({collectionName: "todos", modelName: "Todo1"}));
|
|
600
|
-
registerRealtime(makeEntry({collectionName: "todos", modelName: "Todo2"}));
|
|
601
|
-
const entry = findRegistryEntryByCollection("todos");
|
|
602
|
-
expect(entry?.modelName).toBe("Todo1");
|
|
603
|
-
});
|
|
604
|
-
});
|
|
605
|
-
|
|
606
|
-
describe("findRegistryEntryByRoutePath", () => {
|
|
607
|
-
it("finds an entry by exact route path with leading slash", () => {
|
|
608
|
-
registerRealtime(makeEntry({routePath: "/todos"}));
|
|
609
|
-
const entry = findRegistryEntryByRoutePath("todos");
|
|
610
|
-
expect(entry).toBeDefined();
|
|
611
|
-
expect(entry?.routePath).toBe("/todos");
|
|
612
|
-
});
|
|
613
|
-
|
|
614
|
-
it("finds an entry when collection matches routePath exactly", () => {
|
|
615
|
-
registerRealtime(makeEntry({routePath: "todos"}));
|
|
616
|
-
const entry = findRegistryEntryByRoutePath("todos");
|
|
617
|
-
expect(entry).toBeDefined();
|
|
618
|
-
});
|
|
619
|
-
|
|
620
|
-
it("returns undefined for unknown route path", () => {
|
|
621
|
-
registerRealtime(makeEntry({routePath: "/todos"}));
|
|
622
|
-
const entry = findRegistryEntryByRoutePath("items");
|
|
623
|
-
expect(entry).toBeUndefined();
|
|
624
|
-
});
|
|
625
|
-
});
|
|
626
|
-
|
|
627
|
-
describe("clearRealtimeRegistry", () => {
|
|
628
|
-
it("removes all entries", () => {
|
|
629
|
-
registerRealtime(makeEntry());
|
|
630
|
-
clearRealtimeRegistry();
|
|
631
|
-
expect(getRealtimeRegistry()).toHaveLength(0);
|
|
632
|
-
});
|
|
633
|
-
});
|
|
634
|
-
|
|
635
|
-
describe("updateRealtimeRegistryOptions", () => {
|
|
636
|
-
it("replaces options on an existing entry by route path", () => {
|
|
637
|
-
registerRealtime(makeEntry({routePath: "/todos"}));
|
|
638
|
-
const updatedOptions = {permissions: {list: []}} as ModelRouterOptions<unknown>;
|
|
639
|
-
updateRealtimeRegistryOptions("/todos", updatedOptions);
|
|
640
|
-
|
|
641
|
-
expect(getRealtimeRegistry()[0]?.options).toBe(updatedOptions);
|
|
642
|
-
});
|
|
643
|
-
|
|
644
|
-
it("no-ops when the route path is not registered", () => {
|
|
645
|
-
registerRealtime(makeEntry({routePath: "/todos"}));
|
|
646
|
-
const originalOptions = getRealtimeRegistry()[0]?.options;
|
|
647
|
-
updateRealtimeRegistryOptions("/missing", {permissions: {}} as ModelRouterOptions<unknown>);
|
|
648
|
-
|
|
649
|
-
expect(getRealtimeRegistry()[0]?.options).toBe(originalOptions);
|
|
650
|
-
});
|
|
651
|
-
});
|
|
652
|
-
});
|
|
653
|
-
|
|
654
334
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
655
335
|
// RealtimeApp tests
|
|
656
336
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
@@ -744,648 +424,63 @@ const createMockSocket = (decodedToken?: DecodedRealtimeToken): MockSocket => {
|
|
|
744
424
|
};
|
|
745
425
|
|
|
746
426
|
describe("installRealtimeSocketHandlers", () => {
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
afterEach(() => {
|
|
753
|
-
clearRealtimeRegistry();
|
|
754
|
-
clearQueryStore();
|
|
755
|
-
});
|
|
756
|
-
|
|
757
|
-
const registerOwnerCollection = (): void => {
|
|
758
|
-
registerRealtime({
|
|
759
|
-
collectionName: "todos",
|
|
760
|
-
config: {methods: ["create", "update", "delete"], roomStrategy: "owner"},
|
|
761
|
-
modelName: "Todo",
|
|
762
|
-
options: {
|
|
763
|
-
permissions: {
|
|
764
|
-
create: [() => true],
|
|
765
|
-
delete: [() => true],
|
|
766
|
-
list: [() => true],
|
|
767
|
-
read: [() => true],
|
|
768
|
-
update: [() => true],
|
|
769
|
-
},
|
|
770
|
-
queryFields: ["completed", "priority"],
|
|
771
|
-
},
|
|
772
|
-
routePath: "/todos",
|
|
773
|
-
});
|
|
427
|
+
// joinUserRooms is fire-and-forget — give microtasks a chance to flush.
|
|
428
|
+
const flushJoins = async (): Promise<void> => {
|
|
429
|
+
await Promise.resolve();
|
|
430
|
+
await Promise.resolve();
|
|
774
431
|
};
|
|
775
432
|
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
});
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
await Promise.resolve();
|
|
820
|
-
await Promise.resolve();
|
|
821
|
-
expect(socket.rooms.has("user:user1")).toBe(true);
|
|
822
|
-
expect(socket.rooms.has("authenticated")).toBe(true);
|
|
823
|
-
});
|
|
824
|
-
|
|
825
|
-
it("joins admin room for admin tokens", async () => {
|
|
826
|
-
const socket = createMockSocket({admin: true, id: "admin1"});
|
|
827
|
-
installRealtimeSocketHandlers(socket);
|
|
828
|
-
await Promise.resolve();
|
|
829
|
-
await Promise.resolve();
|
|
830
|
-
expect(socket.rooms.has("admin")).toBe(true);
|
|
831
|
-
});
|
|
832
|
-
|
|
833
|
-
it("does not join admin room for non-admin tokens", async () => {
|
|
834
|
-
const socket = createMockSocket({admin: false, id: "user1"});
|
|
835
|
-
installRealtimeSocketHandlers(socket);
|
|
836
|
-
await Promise.resolve();
|
|
837
|
-
await Promise.resolve();
|
|
838
|
-
expect(socket.rooms.has("admin")).toBe(false);
|
|
839
|
-
});
|
|
840
|
-
});
|
|
841
|
-
|
|
842
|
-
describe("subscribe:model permission", () => {
|
|
843
|
-
it("denies unregistered collections", async () => {
|
|
844
|
-
const socket = createMockSocket({id: "user1"});
|
|
845
|
-
installRealtimeSocketHandlers(socket);
|
|
846
|
-
await socket.trigger("subscribe:model", "nonexistent");
|
|
847
|
-
expect(socket.rooms.has("model:nonexistent")).toBe(false);
|
|
848
|
-
});
|
|
849
|
-
|
|
850
|
-
it("denies owner-strategy model room for non-admin users", async () => {
|
|
851
|
-
registerOwnerCollection();
|
|
852
|
-
const socket = createMockSocket({admin: false, id: "user1"});
|
|
853
|
-
installRealtimeSocketHandlers(socket);
|
|
854
|
-
await socket.trigger("subscribe:model", "todos");
|
|
855
|
-
expect(socket.rooms.has("model:todos")).toBe(false);
|
|
856
|
-
});
|
|
857
|
-
|
|
858
|
-
it("allows owner-strategy model room for admins", async () => {
|
|
859
|
-
registerOwnerCollection();
|
|
860
|
-
const socket = createMockSocket({admin: true, id: "admin1"});
|
|
861
|
-
installRealtimeSocketHandlers(socket);
|
|
862
|
-
await socket.trigger("subscribe:model", "todos");
|
|
863
|
-
expect(socket.rooms.has("model:todos")).toBe(true);
|
|
864
|
-
});
|
|
865
|
-
|
|
866
|
-
it("allows non-admins to subscribe to model-strategy collections", async () => {
|
|
867
|
-
registerModelCollection();
|
|
868
|
-
const socket = createMockSocket({admin: false, id: "user1"});
|
|
869
|
-
installRealtimeSocketHandlers(socket);
|
|
870
|
-
await socket.trigger("subscribe:model", "broadcasts");
|
|
871
|
-
expect(socket.rooms.has("model:broadcasts")).toBe(true);
|
|
872
|
-
});
|
|
873
|
-
|
|
874
|
-
it("denies model-strategy collections when modelRouter list permission fails", async () => {
|
|
875
|
-
registerAdminOnlyCollection();
|
|
876
|
-
const socket = createMockSocket({admin: false, id: "user1"});
|
|
877
|
-
installRealtimeSocketHandlers(socket);
|
|
878
|
-
await socket.trigger("subscribe:model", "secrets");
|
|
879
|
-
expect(socket.rooms.has("model:secrets")).toBe(false);
|
|
880
|
-
});
|
|
881
|
-
|
|
882
|
-
it("allows model-strategy collections when modelRouter list permission passes", async () => {
|
|
883
|
-
registerAdminOnlyCollection();
|
|
884
|
-
const socket = createMockSocket({admin: true, id: "admin1"});
|
|
885
|
-
installRealtimeSocketHandlers(socket);
|
|
886
|
-
await socket.trigger("subscribe:model", "secrets");
|
|
887
|
-
expect(socket.rooms.has("model:secrets")).toBe(true);
|
|
888
|
-
});
|
|
889
|
-
|
|
890
|
-
it("ignores empty or non-string model names", async () => {
|
|
891
|
-
registerModelCollection();
|
|
892
|
-
const socket = createMockSocket({id: "user1"});
|
|
893
|
-
installRealtimeSocketHandlers(socket);
|
|
894
|
-
await socket.trigger("subscribe:model", "");
|
|
895
|
-
await socket.trigger("subscribe:model", 123);
|
|
896
|
-
await socket.trigger("subscribe:model", null);
|
|
897
|
-
const modelRooms = Array.from(socket.rooms).filter((r) => r.startsWith("model:"));
|
|
898
|
-
expect(modelRooms).toHaveLength(0);
|
|
899
|
-
});
|
|
900
|
-
|
|
901
|
-
it("enforces MAX_MODEL_SUBSCRIPTIONS cap", async () => {
|
|
902
|
-
// Register MAX + 5 model-strategy collections.
|
|
903
|
-
for (let i = 0; i < MAX_MODEL_SUBSCRIPTIONS + 5; i++) {
|
|
904
|
-
registerRealtime({
|
|
905
|
-
collectionName: `coll${i}`,
|
|
906
|
-
config: {methods: ["create"], roomStrategy: "model"},
|
|
907
|
-
modelName: `Coll${i}`,
|
|
908
|
-
options: {
|
|
909
|
-
permissions: {
|
|
910
|
-
create: [() => true],
|
|
911
|
-
delete: [() => true],
|
|
912
|
-
list: [() => true],
|
|
913
|
-
read: [() => true],
|
|
914
|
-
update: [() => true],
|
|
915
|
-
},
|
|
916
|
-
},
|
|
917
|
-
routePath: `/coll${i}`,
|
|
918
|
-
});
|
|
919
|
-
}
|
|
920
|
-
const socket = createMockSocket({id: "user1"});
|
|
921
|
-
installRealtimeSocketHandlers(socket);
|
|
922
|
-
for (let i = 0; i < MAX_MODEL_SUBSCRIPTIONS + 5; i++) {
|
|
923
|
-
await socket.trigger("subscribe:model", `coll${i}`);
|
|
924
|
-
}
|
|
925
|
-
const modelRooms = Array.from(socket.rooms).filter((r) => r.startsWith("model:"));
|
|
926
|
-
expect(modelRooms.length).toBe(MAX_MODEL_SUBSCRIPTIONS);
|
|
927
|
-
});
|
|
928
|
-
});
|
|
929
|
-
|
|
930
|
-
describe("subscribe:document permission", () => {
|
|
931
|
-
it("denies unregistered collections", async () => {
|
|
932
|
-
const socket = createMockSocket({id: "user1"});
|
|
933
|
-
installRealtimeSocketHandlers(socket);
|
|
934
|
-
await socket.trigger("subscribe:document", {collection: "nonexistent", id: "abc"});
|
|
935
|
-
const docRooms = Array.from(socket.rooms).filter((r) => r.startsWith("document:"));
|
|
936
|
-
expect(docRooms).toHaveLength(0);
|
|
937
|
-
});
|
|
938
|
-
|
|
939
|
-
it("denies owner-strategy document subscription for non-admin", async () => {
|
|
940
|
-
registerOwnerCollection();
|
|
941
|
-
const socket = createMockSocket({admin: false, id: "user1"});
|
|
942
|
-
installRealtimeSocketHandlers(socket);
|
|
943
|
-
await socket.trigger("subscribe:document", {collection: "todos", id: "doc1"});
|
|
944
|
-
expect(socket.rooms.has("document:todos:doc1")).toBe(false);
|
|
945
|
-
});
|
|
946
|
-
|
|
947
|
-
it("allows owner-strategy document subscription for admins", async () => {
|
|
948
|
-
registerOwnerCollection();
|
|
949
|
-
const socket = createMockSocket({admin: true, id: "admin1"});
|
|
950
|
-
installRealtimeSocketHandlers(socket);
|
|
951
|
-
await socket.trigger("subscribe:document", {collection: "todos", id: "doc1"});
|
|
952
|
-
expect(socket.rooms.has("document:todos:doc1")).toBe(true);
|
|
953
|
-
});
|
|
954
|
-
|
|
955
|
-
it("allows model-strategy document subscription for non-admin", async () => {
|
|
956
|
-
registerModelCollection();
|
|
957
|
-
const socket = createMockSocket({admin: false, id: "user1"});
|
|
958
|
-
installRealtimeSocketHandlers(socket);
|
|
959
|
-
await socket.trigger("subscribe:document", {collection: "broadcasts", id: "doc1"});
|
|
960
|
-
expect(socket.rooms.has("document:broadcasts:doc1")).toBe(true);
|
|
961
|
-
});
|
|
962
|
-
|
|
963
|
-
it("denies document subscriptions when modelRouter read permission fails", async () => {
|
|
964
|
-
registerAdminOnlyCollection();
|
|
965
|
-
const socket = createMockSocket({admin: false, id: "user1"});
|
|
966
|
-
installRealtimeSocketHandlers(socket);
|
|
967
|
-
await socket.trigger("subscribe:document", {collection: "secrets", id: "doc1"});
|
|
968
|
-
expect(socket.rooms.has("document:secrets:doc1")).toBe(false);
|
|
969
|
-
});
|
|
970
|
-
|
|
971
|
-
it("ignores malformed payloads", async () => {
|
|
972
|
-
registerModelCollection();
|
|
973
|
-
const socket = createMockSocket({id: "user1"});
|
|
974
|
-
installRealtimeSocketHandlers(socket);
|
|
975
|
-
await socket.trigger("subscribe:document", null);
|
|
976
|
-
await socket.trigger("subscribe:document", {});
|
|
977
|
-
await socket.trigger("subscribe:document", {collection: "broadcasts"});
|
|
978
|
-
await socket.trigger("subscribe:document", {id: "doc1"});
|
|
979
|
-
await socket.trigger("subscribe:document", {collection: 123, id: "doc1"});
|
|
980
|
-
const docRooms = Array.from(socket.rooms).filter((r) => r.startsWith("document:"));
|
|
981
|
-
expect(docRooms).toHaveLength(0);
|
|
982
|
-
});
|
|
983
|
-
});
|
|
984
|
-
|
|
985
|
-
describe("subscribe:query permission", () => {
|
|
986
|
-
it("denies unregistered collections", async () => {
|
|
987
|
-
const socket = createMockSocket({id: "user1"});
|
|
988
|
-
installRealtimeSocketHandlers(socket);
|
|
989
|
-
await socket.trigger("subscribe:query", {collection: "nope", query: {a: 1}});
|
|
990
|
-
const queryRooms = Array.from(socket.rooms).filter((r) => r.startsWith("query:"));
|
|
991
|
-
expect(queryRooms).toHaveLength(0);
|
|
992
|
-
});
|
|
993
|
-
|
|
994
|
-
it("injects ownerId for owner-strategy non-admin subscribers", async () => {
|
|
995
|
-
registerOwnerCollection();
|
|
996
|
-
const socket = createMockSocket({admin: false, id: "user1"});
|
|
997
|
-
installRealtimeSocketHandlers(socket);
|
|
998
|
-
await socket.trigger("subscribe:query", {
|
|
999
|
-
collection: "todos",
|
|
1000
|
-
query: {completed: false},
|
|
1001
|
-
});
|
|
1002
|
-
|
|
1003
|
-
// queryId emitted back must encode the injected ownerId
|
|
1004
|
-
const subscribed = socket.emitted.find((e) => e.event === "query:subscribed");
|
|
1005
|
-
expect(subscribed).toBeDefined();
|
|
1006
|
-
if (!subscribed) {
|
|
1007
|
-
throw new Error("Expected a query subscription event");
|
|
1008
|
-
}
|
|
1009
|
-
expect((subscribed.payload as {queryId: string}).queryId).toContain("user1");
|
|
1010
|
-
});
|
|
1011
|
-
|
|
1012
|
-
it("does NOT inject ownerId for admins (admins see all)", async () => {
|
|
1013
|
-
registerOwnerCollection();
|
|
1014
|
-
const socket = createMockSocket({admin: true, id: "admin1"});
|
|
1015
|
-
installRealtimeSocketHandlers(socket);
|
|
1016
|
-
await socket.trigger("subscribe:query", {
|
|
1017
|
-
collection: "todos",
|
|
1018
|
-
query: {completed: false},
|
|
1019
|
-
});
|
|
1020
|
-
const subscribed = socket.emitted.find((e) => e.event === "query:subscribed");
|
|
1021
|
-
expect(subscribed).toBeDefined();
|
|
1022
|
-
if (!subscribed) {
|
|
1023
|
-
throw new Error("Expected a query subscription event");
|
|
1024
|
-
}
|
|
1025
|
-
expect((subscribed.payload as {queryId: string}).queryId).not.toContain("admin1");
|
|
1026
|
-
});
|
|
1027
|
-
|
|
1028
|
-
it("ignores subscriptions when user has no id (anonymous) for owner strategy", async () => {
|
|
1029
|
-
registerOwnerCollection();
|
|
1030
|
-
const socket = createMockSocket({admin: false}); // no id
|
|
1031
|
-
installRealtimeSocketHandlers(socket);
|
|
1032
|
-
await socket.trigger("subscribe:query", {
|
|
1033
|
-
collection: "todos",
|
|
1034
|
-
query: {completed: false},
|
|
1035
|
-
});
|
|
1036
|
-
const queryRooms = Array.from(socket.rooms).filter((r) => r.startsWith("query:"));
|
|
1037
|
-
expect(queryRooms).toHaveLength(0);
|
|
1038
|
-
});
|
|
1039
|
-
|
|
1040
|
-
it("computes the queryId server-side regardless of client-provided value", async () => {
|
|
1041
|
-
registerOwnerCollection();
|
|
1042
|
-
const socket = createMockSocket({admin: true, id: "admin1"});
|
|
1043
|
-
installRealtimeSocketHandlers(socket);
|
|
1044
|
-
await socket.trigger("subscribe:query", {
|
|
1045
|
-
collection: "todos",
|
|
1046
|
-
query: {completed: false},
|
|
1047
|
-
queryId: "EVIL_HIJACK", // client-provided is ignored
|
|
1048
|
-
});
|
|
1049
|
-
const subscribed = socket.emitted.find((e) => e.event === "query:subscribed");
|
|
1050
|
-
const payload = subscribed?.payload as {queryId: string};
|
|
1051
|
-
expect(payload.queryId).not.toBe("EVIL_HIJACK");
|
|
1052
|
-
// Must match what the server computes
|
|
1053
|
-
expect(payload.queryId).toBe(computeQueryId("todos", {completed: false}));
|
|
1054
|
-
});
|
|
1055
|
-
|
|
1056
|
-
it("denies query subscriptions when modelRouter list permission fails", async () => {
|
|
1057
|
-
registerAdminOnlyCollection();
|
|
1058
|
-
const socket = createMockSocket({admin: false, id: "user1"});
|
|
1059
|
-
installRealtimeSocketHandlers(socket);
|
|
1060
|
-
await socket.trigger("subscribe:query", {
|
|
1061
|
-
collection: "secrets",
|
|
1062
|
-
query: {classification: "restricted"},
|
|
1063
|
-
});
|
|
1064
|
-
const queryRooms = Array.from(socket.rooms).filter((r) => r.startsWith("query:"));
|
|
1065
|
-
expect(queryRooms).toHaveLength(0);
|
|
1066
|
-
expect(getQuerySubscriptionsForCollection("secrets")).toHaveLength(0);
|
|
1067
|
-
});
|
|
1068
|
-
|
|
1069
|
-
it("applies modelRouter queryFilter before storing a query subscription", async () => {
|
|
1070
|
-
registerRealtime({
|
|
1071
|
-
collectionName: "filtered",
|
|
1072
|
-
config: {methods: ["create"], roomStrategy: "model"},
|
|
1073
|
-
modelName: "Filtered",
|
|
1074
|
-
options: {
|
|
1075
|
-
permissions: {
|
|
1076
|
-
create: [() => true],
|
|
1077
|
-
delete: [() => true],
|
|
1078
|
-
list: [() => true],
|
|
1079
|
-
read: [() => true],
|
|
1080
|
-
update: [() => true],
|
|
1081
|
-
},
|
|
1082
|
-
queryFields: ["status"],
|
|
1083
|
-
queryFilter: () => ({tenantId: "tenant-1"}),
|
|
1084
|
-
},
|
|
1085
|
-
routePath: "/filtered",
|
|
1086
|
-
});
|
|
1087
|
-
const socket = createMockSocket({id: "user1"});
|
|
1088
|
-
installRealtimeSocketHandlers(socket);
|
|
1089
|
-
await socket.trigger("subscribe:query", {
|
|
1090
|
-
collection: "filtered",
|
|
1091
|
-
query: {status: "active"},
|
|
1092
|
-
});
|
|
1093
|
-
const subs = getQuerySubscriptionsForCollection("filtered");
|
|
1094
|
-
expect(subs).toHaveLength(1);
|
|
1095
|
-
expect(subs[0].query).toEqual({status: "active", tenantId: "tenant-1"});
|
|
1096
|
-
});
|
|
1097
|
-
|
|
1098
|
-
it("denies query subscriptions when modelRouter queryFilter throws", async () => {
|
|
1099
|
-
registerRealtime({
|
|
1100
|
-
collectionName: "filtered",
|
|
1101
|
-
config: {methods: ["create"], roomStrategy: "model"},
|
|
1102
|
-
modelName: "Filtered",
|
|
1103
|
-
options: {
|
|
1104
|
-
permissions: {
|
|
1105
|
-
create: [() => true],
|
|
1106
|
-
delete: [() => true],
|
|
1107
|
-
list: [() => true],
|
|
1108
|
-
read: [() => true],
|
|
1109
|
-
update: [() => true],
|
|
1110
|
-
},
|
|
1111
|
-
queryFields: ["status"],
|
|
1112
|
-
queryFilter: () => {
|
|
1113
|
-
throw new Error("tenant lookup failed");
|
|
1114
|
-
},
|
|
1115
|
-
},
|
|
1116
|
-
routePath: "/filtered",
|
|
1117
|
-
});
|
|
1118
|
-
const socket = createMockSocket({id: "user1"});
|
|
1119
|
-
installRealtimeSocketHandlers(socket);
|
|
1120
|
-
await socket.trigger("subscribe:query", {
|
|
1121
|
-
collection: "filtered",
|
|
1122
|
-
query: {status: "active"},
|
|
1123
|
-
});
|
|
1124
|
-
const queryRooms = Array.from(socket.rooms).filter((r) => r.startsWith("query:"));
|
|
1125
|
-
expect(queryRooms).toHaveLength(0);
|
|
1126
|
-
expect(getQuerySubscriptionsForCollection("filtered")).toHaveLength(0);
|
|
1127
|
-
expect(socket.emitted.some((e) => e.event === "query:subscribed")).toBe(false);
|
|
1128
|
-
});
|
|
1129
|
-
|
|
1130
|
-
it("denies query keys outside the modelRouter queryFields allowlist", async () => {
|
|
1131
|
-
registerRealtime({
|
|
1132
|
-
collectionName: "charts",
|
|
1133
|
-
config: {methods: ["create", "update", "delete"], roomStrategy: "model"},
|
|
1134
|
-
modelName: "Chart",
|
|
1135
|
-
options: {...permissiveOptions, queryFields: ["status"]},
|
|
1136
|
-
routePath: "/charts",
|
|
1137
|
-
});
|
|
1138
|
-
const socket = createMockSocket({id: "user1"});
|
|
1139
|
-
installRealtimeSocketHandlers(socket);
|
|
1140
|
-
await socket.trigger("subscribe:query", {
|
|
1141
|
-
collection: "charts",
|
|
1142
|
-
query: {diagnosis: {$in: ["F32.1"]}},
|
|
1143
|
-
});
|
|
1144
|
-
await socket.trigger("subscribe:query", {
|
|
1145
|
-
collection: "charts",
|
|
1146
|
-
query: {$or: [{status: "open"}, {diagnosis: "F41.1"}]},
|
|
1147
|
-
});
|
|
1148
|
-
await socket.trigger("subscribe:query", {
|
|
1149
|
-
collection: "charts",
|
|
1150
|
-
query: {"diagnosis.code": "F41", status: "open"},
|
|
1151
|
-
});
|
|
1152
|
-
expect(getQuerySubscriptionsForCollection("charts")).toHaveLength(0);
|
|
1153
|
-
expect(socket.emitted.some((e) => e.event === "query:subscribed")).toBe(false);
|
|
1154
|
-
|
|
1155
|
-
await socket.trigger("subscribe:query", {
|
|
1156
|
-
collection: "charts",
|
|
1157
|
-
query: {$or: [{status: "open"}, {status: {$in: ["closed"]}}]},
|
|
1158
|
-
});
|
|
1159
|
-
expect(getQuerySubscriptionsForCollection("charts")).toHaveLength(1);
|
|
1160
|
-
});
|
|
1161
|
-
|
|
1162
|
-
it("ignores malformed query payloads", async () => {
|
|
1163
|
-
registerOwnerCollection();
|
|
1164
|
-
const socket = createMockSocket({id: "user1"});
|
|
1165
|
-
installRealtimeSocketHandlers(socket);
|
|
1166
|
-
await socket.trigger("subscribe:query", null);
|
|
1167
|
-
await socket.trigger("subscribe:query", {});
|
|
1168
|
-
await socket.trigger("subscribe:query", {collection: "todos"});
|
|
1169
|
-
await socket.trigger("subscribe:query", {collection: "todos", query: [1, 2, 3]});
|
|
1170
|
-
await socket.trigger("subscribe:query", {collection: "todos", query: {$and: [null]}});
|
|
1171
|
-
await socket.trigger("subscribe:query", {collection: "todos", query: {$or: "priority"}});
|
|
1172
|
-
const queryRooms = Array.from(socket.rooms).filter((r) => r.startsWith("query:"));
|
|
1173
|
-
expect(queryRooms).toHaveLength(0);
|
|
1174
|
-
});
|
|
1175
|
-
|
|
1176
|
-
it("enforces MAX_QUERY_SUBSCRIPTIONS cap", async () => {
|
|
1177
|
-
registerOwnerCollection();
|
|
1178
|
-
const socket = createMockSocket({admin: true, id: "admin1"});
|
|
1179
|
-
installRealtimeSocketHandlers(socket);
|
|
1180
|
-
for (let i = 0; i < MAX_QUERY_SUBSCRIPTIONS + 5; i++) {
|
|
1181
|
-
await socket.trigger("subscribe:query", {
|
|
1182
|
-
collection: "todos",
|
|
1183
|
-
query: {priority: i},
|
|
1184
|
-
});
|
|
1185
|
-
}
|
|
1186
|
-
const queryRooms = Array.from(socket.rooms).filter((r) => r.startsWith("query:"));
|
|
1187
|
-
expect(queryRooms.length).toBe(MAX_QUERY_SUBSCRIPTIONS);
|
|
1188
|
-
});
|
|
1189
|
-
});
|
|
1190
|
-
|
|
1191
|
-
describe("unsubscribe and counters", () => {
|
|
1192
|
-
it("unsubscribe:model frees a slot so further subscriptions are allowed", async () => {
|
|
1193
|
-
registerModelCollection();
|
|
1194
|
-
registerRealtime({
|
|
1195
|
-
collectionName: "other",
|
|
1196
|
-
config: {methods: ["create"], roomStrategy: "model"},
|
|
1197
|
-
modelName: "Other",
|
|
1198
|
-
options: {
|
|
1199
|
-
permissions: {
|
|
1200
|
-
create: [() => true],
|
|
1201
|
-
delete: [() => true],
|
|
1202
|
-
list: [() => true],
|
|
1203
|
-
read: [() => true],
|
|
1204
|
-
update: [() => true],
|
|
1205
|
-
},
|
|
1206
|
-
},
|
|
1207
|
-
routePath: "/other",
|
|
1208
|
-
});
|
|
1209
|
-
const socket = createMockSocket({id: "user1"});
|
|
1210
|
-
installRealtimeSocketHandlers(socket);
|
|
1211
|
-
await socket.trigger("subscribe:model", "broadcasts");
|
|
1212
|
-
expect(socket.rooms.has("model:broadcasts")).toBe(true);
|
|
1213
|
-
await socket.trigger("unsubscribe:model", "broadcasts");
|
|
1214
|
-
expect(socket.rooms.has("model:broadcasts")).toBe(false);
|
|
1215
|
-
// can re-subscribe
|
|
1216
|
-
await socket.trigger("subscribe:model", "other");
|
|
1217
|
-
expect(socket.rooms.has("model:other")).toBe(true);
|
|
1218
|
-
});
|
|
1219
|
-
|
|
1220
|
-
it("unsubscribe:document removes the room and decrements the counter", async () => {
|
|
1221
|
-
registerModelCollection();
|
|
1222
|
-
const socket = createMockSocket({id: "user1"});
|
|
1223
|
-
installRealtimeSocketHandlers(socket);
|
|
1224
|
-
await socket.trigger("subscribe:document", {collection: "broadcasts", id: "doc1"});
|
|
1225
|
-
expect(socket.rooms.has("document:broadcasts:doc1")).toBe(true);
|
|
1226
|
-
await socket.trigger("unsubscribe:document", {collection: "broadcasts", id: "doc1"});
|
|
1227
|
-
expect(socket.rooms.has("document:broadcasts:doc1")).toBe(false);
|
|
1228
|
-
});
|
|
1229
|
-
|
|
1230
|
-
it("unsubscribe:document ignores malformed payloads", async () => {
|
|
1231
|
-
const socket = createMockSocket({id: "user1"});
|
|
1232
|
-
installRealtimeSocketHandlers(socket);
|
|
1233
|
-
// None of these should throw or affect rooms
|
|
1234
|
-
await socket.trigger("unsubscribe:document", null);
|
|
1235
|
-
await socket.trigger("unsubscribe:document", {});
|
|
1236
|
-
await socket.trigger("unsubscribe:document", {collection: "broadcasts"});
|
|
1237
|
-
await socket.trigger("unsubscribe:document", {id: "doc1"});
|
|
1238
|
-
const docRooms = Array.from(socket.rooms).filter((r) => r.startsWith("document:"));
|
|
1239
|
-
expect(docRooms).toHaveLength(0);
|
|
1240
|
-
});
|
|
1241
|
-
|
|
1242
|
-
it("unsubscribe:query removes the query subscription and leaves the room", async () => {
|
|
1243
|
-
registerModelCollection();
|
|
1244
|
-
const socket = createMockSocket({id: "user1"});
|
|
1245
|
-
installRealtimeSocketHandlers(socket);
|
|
1246
|
-
await socket.trigger("subscribe:query", {collection: "broadcasts", query: {priority: 1}});
|
|
1247
|
-
const subscribed = socket.emitted.find((e) => e.event === "query:subscribed");
|
|
1248
|
-
expect(subscribed).toBeDefined();
|
|
1249
|
-
if (!subscribed) {
|
|
1250
|
-
throw new Error("Expected a query subscription event");
|
|
1251
|
-
}
|
|
1252
|
-
const queryId = (subscribed.payload as {queryId: string}).queryId;
|
|
1253
|
-
expect(socket.rooms.has(`query:${queryId}`)).toBe(true);
|
|
1254
|
-
expect(getQuerySubscriptionsForCollection("broadcasts").length).toBe(1);
|
|
1255
|
-
await socket.trigger("unsubscribe:query", {queryId});
|
|
1256
|
-
expect(socket.rooms.has(`query:${queryId}`)).toBe(false);
|
|
1257
|
-
expect(getQuerySubscriptionsForCollection("broadcasts").length).toBe(0);
|
|
1258
|
-
});
|
|
1259
|
-
|
|
1260
|
-
it("unsubscribe:query ignores malformed payloads", async () => {
|
|
1261
|
-
const socket = createMockSocket({id: "user1"});
|
|
1262
|
-
installRealtimeSocketHandlers(socket);
|
|
1263
|
-
await socket.trigger("unsubscribe:query", null);
|
|
1264
|
-
await socket.trigger("unsubscribe:query", {});
|
|
1265
|
-
// No assertion needed — just exercises the no-op path
|
|
1266
|
-
});
|
|
1267
|
-
|
|
1268
|
-
it("disconnect removes all query subscriptions for the socket", async () => {
|
|
1269
|
-
registerOwnerCollection();
|
|
1270
|
-
const socket = createMockSocket({admin: true, id: "admin1"});
|
|
1271
|
-
installRealtimeSocketHandlers(socket);
|
|
1272
|
-
await socket.trigger("subscribe:query", {collection: "todos", query: {priority: 1}});
|
|
1273
|
-
await socket.trigger("subscribe:query", {collection: "todos", query: {priority: 2}});
|
|
1274
|
-
expect(getQuerySubscriptionsForCollection("todos").length).toBeGreaterThan(0);
|
|
1275
|
-
await socket.trigger("disconnect");
|
|
1276
|
-
// The mock leaves rooms intact but the store should be cleared for this socket.
|
|
1277
|
-
// Other sockets aren't subscribed, so the store should be empty.
|
|
1278
|
-
expect(getQuerySubscriptionsForCollection("todos").length).toBe(0);
|
|
1279
|
-
});
|
|
1280
|
-
});
|
|
1281
|
-
});
|
|
1282
|
-
|
|
1283
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
1284
|
-
// serializeDoc — responseHandler fallback for change stream events
|
|
1285
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
1286
|
-
|
|
1287
|
-
describe("serializeDoc (change stream serializer)", () => {
|
|
1288
|
-
const makeEntry = (overrides: Partial<RealtimeRegistryEntry> = {}): RealtimeRegistryEntry => ({
|
|
1289
|
-
collectionName: "users",
|
|
1290
|
-
config: {methods: ["create", "update", "delete"], roomStrategy: "model"},
|
|
1291
|
-
modelName: "User",
|
|
1292
|
-
options: permissiveOptions,
|
|
1293
|
-
routePath: "/users",
|
|
1294
|
-
...overrides,
|
|
1295
|
-
});
|
|
1296
|
-
|
|
1297
|
-
it("prefers realtimeResponseHandler when provided", async () => {
|
|
1298
|
-
const entry = makeEntry({
|
|
1299
|
-
config: {
|
|
1300
|
-
methods: ["update"],
|
|
1301
|
-
realtimeResponseHandler: (doc) => ({customized: doc.name}),
|
|
1302
|
-
roomStrategy: "model",
|
|
1303
|
-
},
|
|
1304
|
-
});
|
|
1305
|
-
const result = await serializeDoc(entry, {name: "Alice", secret: "x"}, "update");
|
|
1306
|
-
expect(result).toEqual({customized: "Alice"});
|
|
1307
|
-
});
|
|
1308
|
-
|
|
1309
|
-
it("falls back to modelRouter responseHandler when no realtime handler is set", async () => {
|
|
1310
|
-
// Mimics a stripping responseHandler like the example-backend users router.
|
|
1311
|
-
const handler: ResponseHandler = async (doc) => {
|
|
1312
|
-
const record = {...(doc as unknown as Record<string, unknown>)};
|
|
1313
|
-
delete record.hash;
|
|
1314
|
-
delete record.salt;
|
|
1315
|
-
return record as unknown as JSONValue;
|
|
1316
|
-
};
|
|
1317
|
-
const responseHandler = mock(handler);
|
|
1318
|
-
const entry = makeEntry({options: {...permissiveOptions, responseHandler}});
|
|
1319
|
-
const result = await serializeDoc(
|
|
1320
|
-
entry,
|
|
1321
|
-
{email: "a@b.com", hash: "h", name: "Alice", salt: "s"},
|
|
1322
|
-
"update"
|
|
1323
|
-
);
|
|
1324
|
-
expect(result).toEqual({email: "a@b.com", name: "Alice"});
|
|
1325
|
-
expect(responseHandler).toHaveBeenCalled();
|
|
1326
|
-
});
|
|
1327
|
-
|
|
1328
|
-
it("maps 'delete' method to 'read' when invoking the REST responseHandler", async () => {
|
|
1329
|
-
let observedMethod: string | undefined;
|
|
1330
|
-
const responseHandler: ResponseHandler = async (doc, method) => {
|
|
1331
|
-
observedMethod = method;
|
|
1332
|
-
return doc as unknown as JSONValue;
|
|
1333
|
-
};
|
|
1334
|
-
const entry = makeEntry({options: {...permissiveOptions, responseHandler}});
|
|
1335
|
-
await serializeDoc(entry, {name: "Alice"}, "delete");
|
|
1336
|
-
expect(observedMethod).toBe("read");
|
|
1337
|
-
});
|
|
1338
|
-
|
|
1339
|
-
it("re-throws when modelRouter responseHandler throws (event dropped, no leak)", async () => {
|
|
1340
|
-
// Critical: do NOT fall back to toJSON, which would skip the handler's sanitization
|
|
1341
|
-
// (e.g. stripping hash/salt) and leak the raw document.
|
|
1342
|
-
const responseHandler: ResponseHandler = async () => {
|
|
1343
|
-
throw new Error("boom");
|
|
1344
|
-
};
|
|
1345
|
-
const entry = makeEntry({options: {...permissiveOptions, responseHandler}});
|
|
1346
|
-
const doc = {hash: "h", name: "Alice", salt: "s", toJSON: () => ({hash: "h", name: "Alice"})};
|
|
1347
|
-
await expect(serializeDoc(entry, doc, "update")).rejects.toThrow("boom");
|
|
1348
|
-
});
|
|
1349
|
-
|
|
1350
|
-
it("re-throws when realtimeResponseHandler throws (event dropped, no leak)", async () => {
|
|
1351
|
-
const entry = makeEntry({
|
|
1352
|
-
config: {
|
|
1353
|
-
methods: ["update"],
|
|
1354
|
-
realtimeResponseHandler: () => {
|
|
1355
|
-
throw new Error("boom");
|
|
1356
|
-
},
|
|
1357
|
-
roomStrategy: "model",
|
|
1358
|
-
},
|
|
1359
|
-
});
|
|
1360
|
-
const doc = {name: "Alice", toJSON: () => ({name: "Alice-json"})};
|
|
1361
|
-
await expect(serializeDoc(entry, doc, "update")).rejects.toThrow("boom");
|
|
1362
|
-
});
|
|
1363
|
-
|
|
1364
|
-
it("returns toJSON output when no handlers are configured", async () => {
|
|
1365
|
-
const entry = makeEntry();
|
|
1366
|
-
const doc = {name: "Alice", toJSON: () => ({id: "1", name: "Alice"})};
|
|
1367
|
-
const result = await serializeDoc(entry, doc, "create");
|
|
1368
|
-
expect(result).toEqual({id: "1", name: "Alice"});
|
|
1369
|
-
});
|
|
1370
|
-
|
|
1371
|
-
it("returns raw doc when toJSON is missing and no handlers configured", async () => {
|
|
1372
|
-
const entry = makeEntry();
|
|
1373
|
-
const result = await serializeDoc(entry, {name: "Alice"}, "create");
|
|
1374
|
-
expect(result).toEqual({name: "Alice"});
|
|
433
|
+
it("joins user-specific and authenticated rooms when token has userId", async () => {
|
|
434
|
+
const socket = createMockSocket({id: "user1"});
|
|
435
|
+
installRealtimeSocketHandlers(socket);
|
|
436
|
+
await flushJoins();
|
|
437
|
+
expect(socket.rooms.has("user:user1")).toBe(true);
|
|
438
|
+
expect(socket.rooms.has("authenticated")).toBe(true);
|
|
439
|
+
});
|
|
440
|
+
|
|
441
|
+
it("joins admin room for admin tokens", async () => {
|
|
442
|
+
const socket = createMockSocket({admin: true, id: "admin1"});
|
|
443
|
+
installRealtimeSocketHandlers(socket);
|
|
444
|
+
await flushJoins();
|
|
445
|
+
expect(socket.rooms.has("admin")).toBe(true);
|
|
446
|
+
});
|
|
447
|
+
|
|
448
|
+
it("does not join admin room for non-admin tokens", async () => {
|
|
449
|
+
const socket = createMockSocket({admin: false, id: "user1"});
|
|
450
|
+
installRealtimeSocketHandlers(socket);
|
|
451
|
+
await flushJoins();
|
|
452
|
+
expect(socket.rooms.has("admin")).toBe(false);
|
|
453
|
+
});
|
|
454
|
+
|
|
455
|
+
it("joins no rooms when the token has no user id", async () => {
|
|
456
|
+
const socket = createMockSocket();
|
|
457
|
+
installRealtimeSocketHandlers(socket);
|
|
458
|
+
await flushJoins();
|
|
459
|
+
expect(socket.rooms.size).toBe(0);
|
|
460
|
+
});
|
|
461
|
+
|
|
462
|
+
it("installs no legacy RTK subscription handlers", () => {
|
|
463
|
+
const socket = createMockSocket({id: "user1"});
|
|
464
|
+
installRealtimeSocketHandlers(socket);
|
|
465
|
+
for (const event of [
|
|
466
|
+
"subscribe:model",
|
|
467
|
+
"unsubscribe:model",
|
|
468
|
+
"subscribe:document",
|
|
469
|
+
"unsubscribe:document",
|
|
470
|
+
"subscribe:query",
|
|
471
|
+
"unsubscribe:query",
|
|
472
|
+
]) {
|
|
473
|
+
expect(socket.listeners.has(event)).toBe(false);
|
|
474
|
+
}
|
|
475
|
+
expect([...socket.listeners.keys()]).toEqual(["disconnect"]);
|
|
1375
476
|
});
|
|
1376
477
|
|
|
1377
|
-
it("
|
|
1378
|
-
const
|
|
1379
|
-
const
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
);
|
|
1384
|
-
expect(result).toEqual({
|
|
1385
|
-
_id: "507f1f77bcf86cd799439011",
|
|
1386
|
-
id: "507f1f77bcf86cd799439011",
|
|
1387
|
-
name: "Alice",
|
|
1388
|
-
});
|
|
478
|
+
it("logs disconnects", async () => {
|
|
479
|
+
const logInfo = mock((_msg: string): void => {});
|
|
480
|
+
const socket = createMockSocket({id: "user1"});
|
|
481
|
+
installRealtimeSocketHandlers(socket, {logInfo});
|
|
482
|
+
await socket.trigger("disconnect");
|
|
483
|
+
expect(logInfo).toHaveBeenCalledWith("[realtime] User user1 disconnected");
|
|
1389
484
|
});
|
|
1390
485
|
});
|
|
1391
486
|
|
|
@@ -1408,27 +503,12 @@ describe("mapOperationType", () => {
|
|
|
1408
503
|
expect(mapOperationType("replace", asChange({}))).toBe("update");
|
|
1409
504
|
});
|
|
1410
505
|
|
|
1411
|
-
it("maps update with deleted=true to delete (soft delete)
|
|
506
|
+
it("maps update with deleted=true to delete (soft delete)", () => {
|
|
1412
507
|
expect(
|
|
1413
|
-
mapOperationType("update", asChange({updateDescription: {updatedFields: {deleted: true}}})
|
|
1414
|
-
"create",
|
|
1415
|
-
"update",
|
|
1416
|
-
"delete",
|
|
1417
|
-
])
|
|
508
|
+
mapOperationType("update", asChange({updateDescription: {updatedFields: {deleted: true}}}))
|
|
1418
509
|
).toBe("delete");
|
|
1419
510
|
});
|
|
1420
511
|
|
|
1421
|
-
it("keeps soft delete as update when delete is NOT in the enabled methods", () => {
|
|
1422
|
-
// A model configured with methods: ["create", "update"] must still see
|
|
1423
|
-
// soft-delete events as updates — otherwise they'd be silently dropped.
|
|
1424
|
-
expect(
|
|
1425
|
-
mapOperationType("update", asChange({updateDescription: {updatedFields: {deleted: true}}}), [
|
|
1426
|
-
"create",
|
|
1427
|
-
"update",
|
|
1428
|
-
])
|
|
1429
|
-
).toBe("update");
|
|
1430
|
-
});
|
|
1431
|
-
|
|
1432
512
|
it("maps delete to delete", () => {
|
|
1433
513
|
expect(mapOperationType("delete", asChange({}))).toBe("delete");
|
|
1434
514
|
});
|
|
@@ -1439,72 +519,11 @@ describe("mapOperationType", () => {
|
|
|
1439
519
|
});
|
|
1440
520
|
});
|
|
1441
521
|
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
config: {methods: ["create", "update", "delete"], roomStrategy: "model"},
|
|
1446
|
-
modelName: "Todo",
|
|
1447
|
-
options: permissiveOptions,
|
|
1448
|
-
routePath: "/todos",
|
|
1449
|
-
};
|
|
1450
|
-
|
|
1451
|
-
it("returns user-specific room for owner strategy with ownerId", () => {
|
|
1452
|
-
const entry = {...baseEntry, config: {...baseEntry.config, roomStrategy: "owner"}};
|
|
1453
|
-
const rooms = resolveRooms(entry, {ownerId: "user-1"}, "create");
|
|
1454
|
-
expect(rooms).toEqual(["user:user-1"]);
|
|
1455
|
-
});
|
|
1456
|
-
|
|
1457
|
-
it("converts ObjectId-like ownerId to string", () => {
|
|
1458
|
-
const entry = {...baseEntry, config: {...baseEntry.config, roomStrategy: "owner"}};
|
|
1459
|
-
const ownerId = {toString: (): string => "owner-from-obj"};
|
|
1460
|
-
const rooms = resolveRooms(entry, {ownerId}, "create");
|
|
1461
|
-
expect(rooms).toEqual(["user:owner-from-obj"]);
|
|
1462
|
-
});
|
|
1463
|
-
|
|
1464
|
-
it("falls back to model room when owner strategy has no ownerId", () => {
|
|
1465
|
-
const entry = {...baseEntry, config: {...baseEntry.config, roomStrategy: "owner"}};
|
|
1466
|
-
const rooms = resolveRooms(entry, {}, "create");
|
|
1467
|
-
expect(rooms).toEqual(["model:todos"]);
|
|
1468
|
-
});
|
|
1469
|
-
|
|
1470
|
-
it("returns model room for model strategy", () => {
|
|
1471
|
-
const entry = {...baseEntry, config: {...baseEntry.config, roomStrategy: "model"}};
|
|
1472
|
-
const rooms = resolveRooms(entry, {}, "create");
|
|
1473
|
-
expect(rooms).toEqual(["model:todos"]);
|
|
1474
|
-
});
|
|
1475
|
-
|
|
1476
|
-
it("returns authenticated room for broadcast strategy", () => {
|
|
1477
|
-
const entry = {...baseEntry, config: {...baseEntry.config, roomStrategy: "broadcast"}};
|
|
1478
|
-
const rooms = resolveRooms(entry, {}, "create");
|
|
1479
|
-
expect(rooms).toEqual(["authenticated"]);
|
|
1480
|
-
});
|
|
1481
|
-
|
|
1482
|
-
it("defaults to model room for unknown strategy", () => {
|
|
1483
|
-
const entry = {
|
|
1484
|
-
...baseEntry,
|
|
1485
|
-
config: {
|
|
1486
|
-
...baseEntry.config,
|
|
1487
|
-
roomStrategy: "unknown" as unknown as RealtimeConfig["roomStrategy"],
|
|
1488
|
-
},
|
|
1489
|
-
};
|
|
1490
|
-
const rooms = resolveRooms(entry, {}, "create");
|
|
1491
|
-
expect(rooms).toEqual(["model:todos"]);
|
|
1492
|
-
});
|
|
1493
|
-
|
|
1494
|
-
it("invokes custom function room resolver", () => {
|
|
1495
|
-
const entry: RealtimeRegistryEntry = {
|
|
1496
|
-
...baseEntry,
|
|
1497
|
-
config: {
|
|
1498
|
-
...baseEntry.config,
|
|
1499
|
-
roomStrategy: (doc, method): string[] => [`custom:${method}:${String(doc.id)}`],
|
|
1500
|
-
},
|
|
1501
|
-
};
|
|
1502
|
-
const rooms = resolveRooms(entry, {id: "42"}, "update");
|
|
1503
|
-
expect(rooms).toEqual(["custom:update:42"]);
|
|
1504
|
-
});
|
|
1505
|
-
});
|
|
522
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
523
|
+
// emitPayloadToAuthorizedRoom — per-socket authorization for sync:delta fan-out
|
|
524
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
1506
525
|
|
|
1507
|
-
describe("
|
|
526
|
+
describe("emitPayloadToAuthorizedRoom", () => {
|
|
1508
527
|
const makeIo = (): {
|
|
1509
528
|
addSocketToRoom: (room: string, decodedToken?: DecodedRealtimeToken) => void;
|
|
1510
529
|
emissions: Array<{room: string; event: string; payload: unknown}>;
|
|
@@ -1537,337 +556,70 @@ describe("emitToDocumentAndQueryRooms", () => {
|
|
|
1537
556
|
adapter: {rooms: roomSockets},
|
|
1538
557
|
sockets,
|
|
1539
558
|
},
|
|
1540
|
-
to: (room: string) => ({
|
|
1541
|
-
emit: (event: string, payload: unknown): void => {
|
|
1542
|
-
emissions.push({event, payload, room});
|
|
1543
|
-
},
|
|
1544
|
-
}),
|
|
1545
559
|
} as unknown as Server;
|
|
1546
560
|
return {addSocketToRoom, emissions, io};
|
|
1547
561
|
};
|
|
1548
562
|
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
563
|
+
const ownerReadEntry: AuthorizedEmitEntry = {
|
|
564
|
+
collectionTag: "todos",
|
|
565
|
+
modelName: "Todo",
|
|
566
|
+
options: {
|
|
567
|
+
permissions: {
|
|
568
|
+
read: [
|
|
569
|
+
(_method, user?: {admin?: boolean; id?: string}, obj?: unknown) =>
|
|
570
|
+
user?.admin === true || user?.id === (obj as {ownerId?: string} | undefined)?.ownerId,
|
|
571
|
+
],
|
|
572
|
+
},
|
|
573
|
+
},
|
|
574
|
+
};
|
|
1552
575
|
|
|
1553
576
|
afterEach(() => {
|
|
1554
|
-
|
|
1555
|
-
});
|
|
1556
|
-
|
|
1557
|
-
it("emits to the document room", async () => {
|
|
1558
|
-
const {emissions, io} = makeIo();
|
|
1559
|
-
const event: RealtimeEvent = {
|
|
1560
|
-
collection: "todos",
|
|
1561
|
-
id: "doc-1",
|
|
1562
|
-
method: "update",
|
|
1563
|
-
model: "Todo",
|
|
1564
|
-
timestamp: 1,
|
|
1565
|
-
};
|
|
1566
|
-
await emitToDocumentAndQueryRooms(io, "todos", event, {}, () => {});
|
|
1567
|
-
expect(emissions.some((e) => e.room === "document:todos:doc-1")).toBe(true);
|
|
577
|
+
clearAdminBroadcastScopes();
|
|
1568
578
|
});
|
|
1569
579
|
|
|
1570
|
-
it("
|
|
1571
|
-
|
|
1572
|
-
const healthyId = computeQueryId("todos", {priority: 1});
|
|
1573
|
-
addQuerySubscription("socket-b", "todos", {priority: 1}, healthyId);
|
|
580
|
+
it("emits a per-socket payload only to sockets that can read the document", async () => {
|
|
581
|
+
const room = "sync:todos|owner:owner-1";
|
|
1574
582
|
const {addSocketToRoom, emissions, io} = makeIo();
|
|
1575
|
-
addSocketToRoom(
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
id: "doc-1",
|
|
1588
|
-
method: "create",
|
|
1589
|
-
model: "Todo",
|
|
1590
|
-
timestamp: 1,
|
|
1591
|
-
};
|
|
1592
|
-
|
|
1593
|
-
await emitToDocumentAndQueryRooms(
|
|
1594
|
-
throwingIo,
|
|
1595
|
-
"todos",
|
|
1596
|
-
event,
|
|
1597
|
-
{name: "x", priority: 1},
|
|
1598
|
-
() => {}
|
|
1599
|
-
);
|
|
583
|
+
addSocketToRoom(room, {id: "owner-1"});
|
|
584
|
+
addSocketToRoom(room, {id: "other-user"});
|
|
585
|
+
|
|
586
|
+
await emitPayloadToAuthorizedRoom({
|
|
587
|
+
buildPayload: (user) => ({id: "todo-1", visibleTo: user?.id}),
|
|
588
|
+
entry: ownerReadEntry,
|
|
589
|
+
eventName: "sync:delta",
|
|
590
|
+
fullDocument: {_id: "todo-1", ownerId: "owner-1"},
|
|
591
|
+
io,
|
|
592
|
+
logDebug: () => {},
|
|
593
|
+
room,
|
|
594
|
+
});
|
|
1600
595
|
|
|
1601
|
-
expect(emissions
|
|
596
|
+
expect(emissions).toEqual([
|
|
597
|
+
{event: "sync:delta", payload: {id: "todo-1", visibleTo: "owner-1"}, room},
|
|
598
|
+
]);
|
|
1602
599
|
});
|
|
1603
600
|
|
|
1604
|
-
it("
|
|
1605
|
-
const
|
|
1606
|
-
addQuerySubscription("socket-a", "todos", {priority: 1}, queryId);
|
|
601
|
+
it("continues emitting to other sockets when building one payload fails", async () => {
|
|
602
|
+
const room = "sync:todos|broadcast";
|
|
1607
603
|
const {addSocketToRoom, emissions, io} = makeIo();
|
|
1608
|
-
addSocketToRoom(
|
|
1609
|
-
|
|
1610
|
-
collection: "todos",
|
|
1611
|
-
id: "doc-1",
|
|
1612
|
-
method: "delete",
|
|
1613
|
-
model: "Todo",
|
|
1614
|
-
timestamp: 1,
|
|
1615
|
-
};
|
|
1616
|
-
const entry: RealtimeRegistryEntry = {
|
|
1617
|
-
collectionName: "todos",
|
|
1618
|
-
config: {methods: ["delete"], roomStrategy: "model"},
|
|
1619
|
-
modelName: "Todo",
|
|
1620
|
-
options: permissiveOptions,
|
|
1621
|
-
routePath: "/todos",
|
|
1622
|
-
};
|
|
1623
|
-
await emitToDocumentAndQueryRooms(io, "todos", event, undefined, () => {}, entry);
|
|
1624
|
-
expect(emissions.some((e) => e.room === `query:${queryId}` && e.event === "sync")).toBe(true);
|
|
1625
|
-
});
|
|
604
|
+
addSocketToRoom(room, {id: "bad-user"});
|
|
605
|
+
addSocketToRoom(room, {id: "good-user"});
|
|
1626
606
|
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
const event: RealtimeEvent = {
|
|
1634
|
-
collection: "todos",
|
|
1635
|
-
id: "doc-1",
|
|
1636
|
-
method: "delete",
|
|
1637
|
-
model: "Todo",
|
|
1638
|
-
timestamp: 1,
|
|
1639
|
-
};
|
|
1640
|
-
const entry: RealtimeRegistryEntry = {
|
|
1641
|
-
collectionName: "todos",
|
|
1642
|
-
config: {methods: ["delete"], roomStrategy: "owner"},
|
|
1643
|
-
modelName: "Todo",
|
|
1644
|
-
options: permissiveOptions,
|
|
1645
|
-
routePath: "/todos",
|
|
1646
|
-
};
|
|
1647
|
-
await emitToDocumentAndQueryRooms(io, "todos", event, undefined, () => {}, entry);
|
|
1648
|
-
// Document room still receives the event, but query rooms must not — otherwise users
|
|
1649
|
-
// would see deletes for docs they don't own.
|
|
1650
|
-
expect(emissions.some((e) => e.room === `query:${queryId}`)).toBe(false);
|
|
1651
|
-
expect(emissions.some((e) => e.room === "document:todos:doc-1")).toBe(true);
|
|
1652
|
-
});
|
|
1653
|
-
|
|
1654
|
-
it("forwards soft deletes only to query rooms whose filter the document satisfies", async () => {
|
|
1655
|
-
const matchingQueryId = computeQueryId("todos", {priority: 1});
|
|
1656
|
-
const nonMatchingQueryId = computeQueryId("todos", {priority: 9});
|
|
1657
|
-
addQuerySubscription("socket-a", "todos", {priority: 1}, matchingQueryId);
|
|
1658
|
-
addQuerySubscription("socket-b", "todos", {priority: 9}, nonMatchingQueryId);
|
|
1659
|
-
const {addSocketToRoom, emissions, io} = makeIo();
|
|
1660
|
-
addSocketToRoom(`query:${matchingQueryId}`);
|
|
1661
|
-
addSocketToRoom(`query:${nonMatchingQueryId}`);
|
|
1662
|
-
const event: RealtimeEvent = {
|
|
1663
|
-
collection: "todos",
|
|
1664
|
-
data: {deleted: true, priority: 1},
|
|
1665
|
-
id: "doc-1",
|
|
1666
|
-
method: "delete",
|
|
1667
|
-
model: "Todo",
|
|
1668
|
-
timestamp: 1,
|
|
1669
|
-
};
|
|
1670
|
-
const entry: RealtimeRegistryEntry = {
|
|
1671
|
-
collectionName: "todos",
|
|
1672
|
-
config: {methods: ["delete"], roomStrategy: "owner"},
|
|
1673
|
-
modelName: "Todo",
|
|
1674
|
-
options: permissiveOptions,
|
|
1675
|
-
routePath: "/todos",
|
|
1676
|
-
};
|
|
1677
|
-
await emitToDocumentAndQueryRooms(
|
|
1678
|
-
io,
|
|
1679
|
-
"todos",
|
|
1680
|
-
event,
|
|
1681
|
-
{deleted: true, priority: 1},
|
|
1682
|
-
() => {},
|
|
1683
|
-
entry
|
|
1684
|
-
);
|
|
1685
|
-
expect(emissions.some((e) => e.room === `query:${matchingQueryId}`)).toBe(true);
|
|
1686
|
-
expect(emissions.some((e) => e.room === `query:${nonMatchingQueryId}`)).toBe(false);
|
|
1687
|
-
});
|
|
1688
|
-
|
|
1689
|
-
it("skips matching when fullDocument is missing on non-delete events", async () => {
|
|
1690
|
-
const queryId = computeQueryId("todos", {priority: 1});
|
|
1691
|
-
addQuerySubscription("socket-a", "todos", {priority: 1}, queryId);
|
|
1692
|
-
const {emissions, io} = makeIo();
|
|
1693
|
-
const event: RealtimeEvent = {
|
|
1694
|
-
collection: "todos",
|
|
1695
|
-
id: "doc-1",
|
|
1696
|
-
method: "create",
|
|
1697
|
-
model: "Todo",
|
|
1698
|
-
timestamp: 1,
|
|
1699
|
-
};
|
|
1700
|
-
await emitToDocumentAndQueryRooms(io, "todos", event, undefined, () => {});
|
|
1701
|
-
expect(emissions.some((e) => e.room === `query:${queryId}`)).toBe(false);
|
|
1702
|
-
});
|
|
1703
|
-
|
|
1704
|
-
it("emits create events to query rooms when the doc matches", async () => {
|
|
1705
|
-
const queryId = computeQueryId("todos", {priority: 1});
|
|
1706
|
-
addQuerySubscription("socket-a", "todos", {priority: 1}, queryId);
|
|
1707
|
-
const {emissions, io} = makeIo();
|
|
1708
|
-
const event: RealtimeEvent = {
|
|
1709
|
-
collection: "todos",
|
|
1710
|
-
id: "doc-1",
|
|
1711
|
-
method: "create",
|
|
1712
|
-
model: "Todo",
|
|
1713
|
-
timestamp: 1,
|
|
1714
|
-
};
|
|
1715
|
-
await emitToDocumentAndQueryRooms(io, "todos", event, {priority: 1}, () => {});
|
|
1716
|
-
const queryEmissions = emissions.filter((e) => e.room === `query:${queryId}`);
|
|
1717
|
-
expect(queryEmissions.length).toBe(1);
|
|
1718
|
-
expect(queryEmissions[0].payload).toMatchObject({method: "create"});
|
|
1719
|
-
});
|
|
1720
|
-
|
|
1721
|
-
it("does not emit create events to query rooms when the doc does not match", async () => {
|
|
1722
|
-
const queryId = computeQueryId("todos", {priority: 1});
|
|
1723
|
-
addQuerySubscription("socket-a", "todos", {priority: 1}, queryId);
|
|
1724
|
-
const {emissions, io} = makeIo();
|
|
1725
|
-
const event: RealtimeEvent = {
|
|
1726
|
-
collection: "todos",
|
|
1727
|
-
id: "doc-1",
|
|
1728
|
-
method: "create",
|
|
1729
|
-
model: "Todo",
|
|
1730
|
-
timestamp: 1,
|
|
1731
|
-
};
|
|
1732
|
-
await emitToDocumentAndQueryRooms(io, "todos", event, {priority: 9}, () => {});
|
|
1733
|
-
expect(emissions.some((e) => e.room === `query:${queryId}`)).toBe(false);
|
|
1734
|
-
});
|
|
1735
|
-
|
|
1736
|
-
it("emits update as-is when the document still matches the query", async () => {
|
|
1737
|
-
const queryId = computeQueryId("todos", {priority: 1});
|
|
1738
|
-
addQuerySubscription("socket-a", "todos", {priority: 1}, queryId);
|
|
1739
|
-
const {emissions, io} = makeIo();
|
|
1740
|
-
const event: RealtimeEvent = {
|
|
1741
|
-
collection: "todos",
|
|
1742
|
-
id: "doc-1",
|
|
1743
|
-
method: "update",
|
|
1744
|
-
model: "Todo",
|
|
1745
|
-
timestamp: 1,
|
|
1746
|
-
};
|
|
1747
|
-
await emitToDocumentAndQueryRooms(io, "todos", event, {priority: 1}, () => {});
|
|
1748
|
-
const queryEmissions = emissions.filter((e) => e.room === `query:${queryId}`);
|
|
1749
|
-
expect(queryEmissions.length).toBe(1);
|
|
1750
|
-
expect(queryEmissions[0].payload).toMatchObject({method: "update"});
|
|
1751
|
-
});
|
|
1752
|
-
|
|
1753
|
-
it("converts updates that no longer match into delete events for the query", async () => {
|
|
1754
|
-
const queryId = computeQueryId("todos", {priority: 1});
|
|
1755
|
-
addQuerySubscription("socket-a", "todos", {priority: 1}, queryId);
|
|
1756
|
-
const {emissions, io} = makeIo();
|
|
1757
|
-
const event: RealtimeEvent = {
|
|
1758
|
-
collection: "todos",
|
|
1759
|
-
id: "doc-1",
|
|
1760
|
-
method: "update",
|
|
1761
|
-
model: "Todo",
|
|
1762
|
-
timestamp: 1,
|
|
1763
|
-
};
|
|
1764
|
-
await emitToDocumentAndQueryRooms(io, "todos", event, {priority: 9}, () => {});
|
|
1765
|
-
const queryEmissions = emissions.filter((e) => e.room === `query:${queryId}`);
|
|
1766
|
-
expect(queryEmissions.length).toBe(1);
|
|
1767
|
-
expect(queryEmissions[0].payload).toMatchObject({method: "delete"});
|
|
1768
|
-
});
|
|
1769
|
-
|
|
1770
|
-
it("filters socket emissions by object read permission and responseHandler", async () => {
|
|
1771
|
-
const {addSocketToRoom, emissions, io} = makeIo();
|
|
1772
|
-
addSocketToRoom("model:todos", {id: "owner-1"});
|
|
1773
|
-
addSocketToRoom("model:todos", {id: "other-user"});
|
|
1774
|
-
const entry: RealtimeRegistryEntry = {
|
|
1775
|
-
collectionName: "todos",
|
|
1776
|
-
config: {methods: ["update"], roomStrategy: "model"},
|
|
1777
|
-
modelName: "Todo",
|
|
1778
|
-
options: {
|
|
1779
|
-
permissions: {
|
|
1780
|
-
create: [() => true],
|
|
1781
|
-
delete: [() => true],
|
|
1782
|
-
list: [() => true],
|
|
1783
|
-
read: [
|
|
1784
|
-
(_method: string, user?: {admin?: boolean; id?: string}, obj?: unknown) =>
|
|
1785
|
-
user?.admin === true || user?.id === (obj as {ownerId?: string} | undefined)?.ownerId,
|
|
1786
|
-
],
|
|
1787
|
-
update: [() => true],
|
|
1788
|
-
},
|
|
1789
|
-
responseHandler: async (doc, _method, req) => {
|
|
1790
|
-
const record = doc as unknown as {_id?: unknown; title?: unknown};
|
|
1791
|
-
return {
|
|
1792
|
-
id: record._id,
|
|
1793
|
-
title: record.title,
|
|
1794
|
-
visibleTo: req.user?.id,
|
|
1795
|
-
} as unknown as JSONValue;
|
|
1796
|
-
},
|
|
607
|
+
await emitPayloadToAuthorizedRoom({
|
|
608
|
+
buildPayload: (user) => {
|
|
609
|
+
if (user?.id === "bad-user") {
|
|
610
|
+
throw new Error("cannot serialize for bad user");
|
|
611
|
+
}
|
|
612
|
+
return {visibleTo: user?.id};
|
|
1797
613
|
},
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
await emitToAuthorizedRoom(
|
|
614
|
+
entry: {...ownerReadEntry, options: {permissions: {read: [() => true]}}},
|
|
615
|
+
eventName: "sync:delta",
|
|
616
|
+
fullDocument: {_id: "todo-1"},
|
|
1802
617
|
io,
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
collection: "todos",
|
|
1806
|
-
id: "todo-1",
|
|
1807
|
-
method: "update",
|
|
1808
|
-
model: "Todo",
|
|
1809
|
-
timestamp: 1,
|
|
1810
|
-
},
|
|
1811
|
-
entry,
|
|
1812
|
-
{_id: "todo-1", ownerId: "owner-1", secret: "hidden", title: "Visible"},
|
|
1813
|
-
() => {}
|
|
1814
|
-
);
|
|
1815
|
-
|
|
1816
|
-
expect(emissions).toHaveLength(1);
|
|
1817
|
-
expect(emissions[0].payload).toMatchObject({
|
|
1818
|
-
data: {id: "todo-1", title: "Visible", visibleTo: "owner-1"},
|
|
618
|
+
logDebug: () => {},
|
|
619
|
+
room,
|
|
1819
620
|
});
|
|
1820
|
-
});
|
|
1821
|
-
|
|
1822
|
-
it("continues emitting to other sockets when per-socket serialization fails", async () => {
|
|
1823
|
-
const {addSocketToRoom, emissions, io} = makeIo();
|
|
1824
|
-
addSocketToRoom("model:todos", {id: "bad-user"});
|
|
1825
|
-
addSocketToRoom("model:todos", {id: "good-user"});
|
|
1826
|
-
const entry: RealtimeRegistryEntry = {
|
|
1827
|
-
collectionName: "todos",
|
|
1828
|
-
config: {methods: ["update"], roomStrategy: "model"},
|
|
1829
|
-
modelName: "Todo",
|
|
1830
|
-
options: {
|
|
1831
|
-
permissions: {
|
|
1832
|
-
create: [() => true],
|
|
1833
|
-
delete: [() => true],
|
|
1834
|
-
list: [() => true],
|
|
1835
|
-
read: [() => true],
|
|
1836
|
-
update: [() => true],
|
|
1837
|
-
},
|
|
1838
|
-
responseHandler: async (doc, _method, req) => {
|
|
1839
|
-
if (req.user?.id === "bad-user") {
|
|
1840
|
-
throw new Error("cannot serialize for bad user");
|
|
1841
|
-
}
|
|
1842
|
-
|
|
1843
|
-
return {
|
|
1844
|
-
...(doc as Record<string, unknown>),
|
|
1845
|
-
visibleTo: req.user?.id,
|
|
1846
|
-
} as unknown as JSONValue;
|
|
1847
|
-
},
|
|
1848
|
-
},
|
|
1849
|
-
routePath: "/todos",
|
|
1850
|
-
};
|
|
1851
|
-
|
|
1852
|
-
await emitToAuthorizedRoom(
|
|
1853
|
-
io,
|
|
1854
|
-
"model:todos",
|
|
1855
|
-
{
|
|
1856
|
-
collection: "todos",
|
|
1857
|
-
id: "todo-1",
|
|
1858
|
-
method: "update",
|
|
1859
|
-
model: "Todo",
|
|
1860
|
-
timestamp: 1,
|
|
1861
|
-
},
|
|
1862
|
-
entry,
|
|
1863
|
-
{_id: "todo-1", title: "Visible"},
|
|
1864
|
-
() => {}
|
|
1865
|
-
);
|
|
1866
621
|
|
|
1867
|
-
expect(emissions).
|
|
1868
|
-
expect(emissions[0].payload).toMatchObject({
|
|
1869
|
-
data: {id: "todo-1", title: "Visible", visibleTo: "good-user"},
|
|
1870
|
-
});
|
|
622
|
+
expect(emissions).toEqual([{event: "sync:delta", payload: {visibleTo: "good-user"}, room}]);
|
|
1871
623
|
});
|
|
1872
624
|
|
|
1873
625
|
it("allows admin broadcast sockets without running product read permissions", async () => {
|
|
@@ -1877,33 +629,18 @@ describe("emitToDocumentAndQueryRooms", () => {
|
|
|
1877
629
|
listPermissions: [() => true],
|
|
1878
630
|
readPermissions: [() => true],
|
|
1879
631
|
});
|
|
1880
|
-
const entry: RealtimeRegistryEntry = {
|
|
1881
|
-
collectionName: "todos",
|
|
1882
|
-
config: {methods: ["update"], roomStrategy: "model"},
|
|
1883
|
-
modelName: "Todo",
|
|
1884
|
-
options: {
|
|
1885
|
-
...permissiveOptions,
|
|
1886
|
-
permissions: {...permissiveOptions.permissions, read: [() => false]},
|
|
1887
|
-
},
|
|
1888
|
-
routePath: "/todos",
|
|
1889
|
-
};
|
|
1890
632
|
|
|
1891
|
-
await
|
|
633
|
+
await emitPayloadToAuthorizedRoom({
|
|
634
|
+
buildPayload: () => ({id: "todo-1"}),
|
|
635
|
+
entry: {...ownerReadEntry, options: {permissions: {read: [() => false]}}},
|
|
636
|
+
eventName: "sync:delta",
|
|
637
|
+
fullDocument: {_id: "todo-1", ownerId: "owner-1"},
|
|
1892
638
|
io,
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
id: "todo-1",
|
|
1897
|
-
method: "update",
|
|
1898
|
-
model: "Todo",
|
|
1899
|
-
timestamp: 1,
|
|
1900
|
-
},
|
|
1901
|
-
entry,
|
|
1902
|
-
{_id: "todo-1", ownerId: "owner-1"},
|
|
1903
|
-
() => {}
|
|
1904
|
-
);
|
|
639
|
+
logDebug: () => {},
|
|
640
|
+
room: "sync:todos|admin",
|
|
641
|
+
});
|
|
1905
642
|
|
|
1906
|
-
|
|
643
|
+
expect(emissions).toHaveLength(1);
|
|
1907
644
|
});
|
|
1908
645
|
|
|
1909
646
|
it("does not emit admin broadcast documents denied by the admin scope", async () => {
|
|
@@ -1913,245 +650,39 @@ describe("emitToDocumentAndQueryRooms", () => {
|
|
|
1913
650
|
listPermissions: [() => false],
|
|
1914
651
|
readPermissions: [() => true],
|
|
1915
652
|
});
|
|
1916
|
-
const entry: RealtimeRegistryEntry = {
|
|
1917
|
-
collectionName: "todos",
|
|
1918
|
-
config: {methods: ["update"], roomStrategy: "model"},
|
|
1919
|
-
modelName: "Todo",
|
|
1920
|
-
options: permissiveOptions,
|
|
1921
|
-
routePath: "/todos",
|
|
1922
|
-
};
|
|
1923
653
|
|
|
1924
|
-
await
|
|
654
|
+
await emitPayloadToAuthorizedRoom({
|
|
655
|
+
buildPayload: () => ({id: "todo-1"}),
|
|
656
|
+
entry: {...ownerReadEntry, options: {permissions: {read: [() => true]}}},
|
|
657
|
+
eventName: "sync:delta",
|
|
658
|
+
fullDocument: {_id: "todo-1", ownerId: "owner-1"},
|
|
1925
659
|
io,
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
id: "todo-1",
|
|
1930
|
-
method: "update",
|
|
1931
|
-
model: "Todo",
|
|
1932
|
-
timestamp: 1,
|
|
1933
|
-
},
|
|
1934
|
-
entry,
|
|
1935
|
-
{_id: "todo-1", ownerId: "owner-1"},
|
|
1936
|
-
() => {}
|
|
1937
|
-
);
|
|
660
|
+
logDebug: () => {},
|
|
661
|
+
room: "sync:todos|admin",
|
|
662
|
+
});
|
|
1938
663
|
|
|
1939
|
-
|
|
664
|
+
expect(emissions).toEqual([]);
|
|
1940
665
|
});
|
|
1941
666
|
|
|
1942
|
-
it("
|
|
667
|
+
it("fails closed without a document when read permission requires an object owner", async () => {
|
|
668
|
+
const room = "sync:todos|owner:owner-1";
|
|
1943
669
|
const {addSocketToRoom, emissions, io} = makeIo();
|
|
1944
|
-
addSocketToRoom(
|
|
1945
|
-
const entry: RealtimeRegistryEntry = {
|
|
1946
|
-
collectionName: "todos",
|
|
1947
|
-
config: {methods: ["delete"], roomStrategy: "model"},
|
|
1948
|
-
modelName: "Todo",
|
|
1949
|
-
options: {
|
|
1950
|
-
permissions: {
|
|
1951
|
-
create: [() => true],
|
|
1952
|
-
delete: [() => true],
|
|
1953
|
-
list: [() => true],
|
|
1954
|
-
read: [
|
|
1955
|
-
(_method: string, user?: {admin?: boolean; id?: string}, obj?: unknown) =>
|
|
1956
|
-
user?.admin === true || user?.id === (obj as {ownerId?: string} | undefined)?.ownerId,
|
|
1957
|
-
],
|
|
1958
|
-
update: [() => true],
|
|
1959
|
-
},
|
|
1960
|
-
},
|
|
1961
|
-
routePath: "/todos",
|
|
1962
|
-
};
|
|
670
|
+
addSocketToRoom(room, {id: "other-user"});
|
|
1963
671
|
|
|
1964
|
-
await
|
|
672
|
+
await emitPayloadToAuthorizedRoom({
|
|
673
|
+
buildPayload: () => ({deleted: true, id: "todo-1"}),
|
|
674
|
+
entry: ownerReadEntry,
|
|
675
|
+
eventName: "sync:delta",
|
|
676
|
+
fullDocument: undefined,
|
|
1965
677
|
io,
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
collection: "todos",
|
|
1969
|
-
id: "todo-1",
|
|
1970
|
-
method: "delete",
|
|
1971
|
-
model: "Todo",
|
|
1972
|
-
timestamp: 1,
|
|
1973
|
-
},
|
|
1974
|
-
entry,
|
|
1975
|
-
undefined,
|
|
1976
|
-
() => {}
|
|
1977
|
-
);
|
|
1978
|
-
|
|
1979
|
-
expect(emissions).toEqual([]);
|
|
1980
|
-
});
|
|
1981
|
-
|
|
1982
|
-
describe("query room fanout with a registry entry", () => {
|
|
1983
|
-
const modelEntry: RealtimeRegistryEntry = {
|
|
1984
|
-
collectionName: "todos",
|
|
1985
|
-
config: {methods: ["create", "update", "delete"], roomStrategy: "model"},
|
|
1986
|
-
modelName: "Todo",
|
|
1987
|
-
options: {
|
|
1988
|
-
permissions: {
|
|
1989
|
-
create: [() => true],
|
|
1990
|
-
delete: [() => true],
|
|
1991
|
-
list: [() => true],
|
|
1992
|
-
read: [() => true],
|
|
1993
|
-
update: [() => true],
|
|
1994
|
-
},
|
|
1995
|
-
},
|
|
1996
|
-
routePath: "/todos",
|
|
1997
|
-
};
|
|
1998
|
-
|
|
1999
|
-
const makeEvent = (method: RealtimeEvent["method"]): RealtimeEvent => ({
|
|
2000
|
-
collection: "todos",
|
|
2001
|
-
id: "doc-1",
|
|
2002
|
-
method,
|
|
2003
|
-
model: "Todo",
|
|
2004
|
-
timestamp: 1,
|
|
2005
|
-
});
|
|
2006
|
-
|
|
2007
|
-
it("emits creates through the permission-filtered path", async () => {
|
|
2008
|
-
const queryId = computeQueryId("todos", {priority: 1});
|
|
2009
|
-
addQuerySubscription("socket-a", "todos", {priority: 1}, queryId);
|
|
2010
|
-
const {addSocketToRoom, emissions, io} = makeIo();
|
|
2011
|
-
addSocketToRoom(`query:${queryId}`, {id: "user-1"});
|
|
2012
|
-
|
|
2013
|
-
await emitToDocumentAndQueryRooms(
|
|
2014
|
-
io,
|
|
2015
|
-
"todos",
|
|
2016
|
-
makeEvent("create"),
|
|
2017
|
-
{priority: 1},
|
|
2018
|
-
() => {},
|
|
2019
|
-
modelEntry
|
|
2020
|
-
);
|
|
2021
|
-
|
|
2022
|
-
const queryEmissions = emissions.filter((e) => e.room === `query:${queryId}`);
|
|
2023
|
-
expect(queryEmissions).toHaveLength(1);
|
|
2024
|
-
expect(queryEmissions[0].payload).toMatchObject({data: {priority: 1}, method: "create"});
|
|
678
|
+
logDebug: () => {},
|
|
679
|
+
room,
|
|
2025
680
|
});
|
|
2026
681
|
|
|
2027
|
-
|
|
2028
|
-
const queryId = computeQueryId("todos", {priority: 1});
|
|
2029
|
-
addQuerySubscription("socket-a", "todos", {priority: 1}, queryId);
|
|
2030
|
-
const {addSocketToRoom, emissions, io} = makeIo();
|
|
2031
|
-
addSocketToRoom(`query:${queryId}`, {id: "user-1"});
|
|
2032
|
-
|
|
2033
|
-
await emitToDocumentAndQueryRooms(
|
|
2034
|
-
io,
|
|
2035
|
-
"todos",
|
|
2036
|
-
makeEvent("update"),
|
|
2037
|
-
{priority: 1},
|
|
2038
|
-
() => {},
|
|
2039
|
-
modelEntry
|
|
2040
|
-
);
|
|
2041
|
-
|
|
2042
|
-
const queryEmissions = emissions.filter((e) => e.room === `query:${queryId}`);
|
|
2043
|
-
expect(queryEmissions).toHaveLength(1);
|
|
2044
|
-
expect(queryEmissions[0].payload).toMatchObject({method: "update"});
|
|
2045
|
-
});
|
|
2046
|
-
|
|
2047
|
-
it("converts non-matching updates into deletes through the permission-filtered path", async () => {
|
|
2048
|
-
const queryId = computeQueryId("todos", {priority: 1});
|
|
2049
|
-
addQuerySubscription("socket-a", "todos", {priority: 1}, queryId);
|
|
2050
|
-
const {addSocketToRoom, emissions, io} = makeIo();
|
|
2051
|
-
addSocketToRoom(`query:${queryId}`, {id: "user-1"});
|
|
2052
|
-
|
|
2053
|
-
await emitToDocumentAndQueryRooms(
|
|
2054
|
-
io,
|
|
2055
|
-
"todos",
|
|
2056
|
-
makeEvent("update"),
|
|
2057
|
-
{priority: 9},
|
|
2058
|
-
() => {},
|
|
2059
|
-
modelEntry
|
|
2060
|
-
);
|
|
2061
|
-
|
|
2062
|
-
const queryEmissions = emissions.filter((e) => e.room === `query:${queryId}`);
|
|
2063
|
-
expect(queryEmissions).toHaveLength(1);
|
|
2064
|
-
expect(queryEmissions[0].payload).toMatchObject({method: "delete"});
|
|
2065
|
-
});
|
|
2066
|
-
|
|
2067
|
-
it("matches query rooms against the recipient's RBAC-masked document", async () => {
|
|
2068
|
-
const fieldMaskRequests: unknown[] = [];
|
|
2069
|
-
const rbacEntry: RealtimeRegistryEntry = {
|
|
2070
|
-
...modelEntry,
|
|
2071
|
-
options: {
|
|
2072
|
-
...modelEntry.options,
|
|
2073
|
-
access: {resource: "chart"},
|
|
2074
|
-
accessControl: {
|
|
2075
|
-
can: async () => ({allowed: true}),
|
|
2076
|
-
fieldMask: async (args: unknown) => {
|
|
2077
|
-
fieldMaskRequests.push(args);
|
|
2078
|
-
return {omit: ["diagnosis"], read: "*", write: "*"};
|
|
2079
|
-
},
|
|
2080
|
-
statements: {chart: ["read", "list"]},
|
|
2081
|
-
} as unknown as NonNullable<RealtimeRegistryEntry["options"]["accessControl"]>,
|
|
2082
|
-
},
|
|
2083
|
-
};
|
|
2084
|
-
const matchingId = computeQueryId("todos", {diagnosis: "F32.1"});
|
|
2085
|
-
const otherId = computeQueryId("todos", {diagnosis: "F41.1"});
|
|
2086
|
-
addQuerySubscription("socket-a", "todos", {diagnosis: "F32.1"}, matchingId);
|
|
2087
|
-
addQuerySubscription("socket-b", "todos", {diagnosis: "F41.1"}, otherId);
|
|
2088
|
-
const {addSocketToRoom, emissions, io} = makeIo();
|
|
2089
|
-
addSocketToRoom(`query:${matchingId}`, {id: "scheduler"});
|
|
2090
|
-
addSocketToRoom(`query:${otherId}`, {id: "scheduler"});
|
|
2091
|
-
|
|
2092
|
-
await emitToDocumentAndQueryRooms(
|
|
2093
|
-
io,
|
|
2094
|
-
"todos",
|
|
2095
|
-
makeEvent("update"),
|
|
2096
|
-
{_id: "doc-1", diagnosis: "F32.1", status: "open"},
|
|
2097
|
-
() => {},
|
|
2098
|
-
rbacEntry
|
|
2099
|
-
);
|
|
2100
|
-
|
|
2101
|
-
const methodFor = (queryId: string): unknown =>
|
|
2102
|
-
(emissions.find((e) => e.room === `query:${queryId}`)?.payload as {method?: string})
|
|
2103
|
-
?.method;
|
|
2104
|
-
// The hidden value must not decide which event each room receives.
|
|
2105
|
-
expect(methodFor(matchingId)).toBe(methodFor(otherId));
|
|
2106
|
-
expect(methodFor(matchingId)).toBe("delete");
|
|
2107
|
-
for (const emission of emissions) {
|
|
2108
|
-
expect((emission.payload as {data?: Record<string, unknown>}).data).not.toHaveProperty(
|
|
2109
|
-
"diagnosis"
|
|
2110
|
-
);
|
|
2111
|
-
}
|
|
2112
|
-
expect(fieldMaskRequests.length).toBeGreaterThan(0);
|
|
2113
|
-
});
|
|
2114
|
-
|
|
2115
|
-
it("skips query rooms whose subscribers cannot read the document", async () => {
|
|
2116
|
-
const queryId = computeQueryId("todos", {priority: 1});
|
|
2117
|
-
addQuerySubscription("socket-a", "todos", {priority: 1}, queryId);
|
|
2118
|
-
const {addSocketToRoom, emissions, io} = makeIo();
|
|
2119
|
-
addSocketToRoom(`query:${queryId}`, {id: "other-user"});
|
|
2120
|
-
const ownerEntry: RealtimeRegistryEntry = {
|
|
2121
|
-
...modelEntry,
|
|
2122
|
-
options: {
|
|
2123
|
-
permissions: {
|
|
2124
|
-
create: [() => true],
|
|
2125
|
-
delete: [() => true],
|
|
2126
|
-
list: [() => true],
|
|
2127
|
-
read: [
|
|
2128
|
-
(_method, user?: {admin?: boolean; id?: string}, obj?: unknown) =>
|
|
2129
|
-
user?.admin === true ||
|
|
2130
|
-
user?.id === (obj as {ownerId?: string} | undefined)?.ownerId,
|
|
2131
|
-
],
|
|
2132
|
-
update: [() => true],
|
|
2133
|
-
},
|
|
2134
|
-
},
|
|
2135
|
-
};
|
|
2136
|
-
|
|
2137
|
-
await emitToDocumentAndQueryRooms(
|
|
2138
|
-
io,
|
|
2139
|
-
"todos",
|
|
2140
|
-
makeEvent("create"),
|
|
2141
|
-
{ownerId: "user-1", priority: 1},
|
|
2142
|
-
() => {},
|
|
2143
|
-
ownerEntry
|
|
2144
|
-
);
|
|
2145
|
-
|
|
2146
|
-
expect(emissions.some((e) => e.room === `query:${queryId}`)).toBe(false);
|
|
2147
|
-
});
|
|
682
|
+
expect(emissions).toEqual([]);
|
|
2148
683
|
});
|
|
2149
684
|
});
|
|
2150
685
|
|
|
2151
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
2152
|
-
// redactCredentials — Redis URL logging
|
|
2153
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
2154
|
-
|
|
2155
686
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
2156
687
|
// startChangeStreamWatcher / stopChangeStreamWatcher — MongoDB change stream
|
|
2157
688
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
@@ -2161,14 +692,12 @@ describe("startChangeStreamWatcher", () => {
|
|
|
2161
692
|
|
|
2162
693
|
beforeEach(() => {
|
|
2163
694
|
originalDb = mongoose.connection.db;
|
|
2164
|
-
clearRealtimeRegistry();
|
|
2165
695
|
});
|
|
2166
696
|
|
|
2167
697
|
afterEach(async () => {
|
|
2168
698
|
setConnectionDb(originalDb);
|
|
2169
|
-
clearRealtimeRegistry();
|
|
2170
699
|
// Ensure the watcher is stopped between tests
|
|
2171
|
-
const {stopChangeStreamWatcher: stop} = await import("./changeStreamWatcher");
|
|
700
|
+
const {stopChangeStreamWatcher: stop} = await import("./changeStreamWatcher.js");
|
|
2172
701
|
await stop();
|
|
2173
702
|
});
|
|
2174
703
|
|
|
@@ -2222,7 +751,7 @@ describe("startChangeStreamWatcher", () => {
|
|
|
2222
751
|
};
|
|
2223
752
|
setConnectionDb(mockDb);
|
|
2224
753
|
|
|
2225
|
-
const {startChangeStreamWatcher} = await import("./changeStreamWatcher");
|
|
754
|
+
const {startChangeStreamWatcher} = await import("./changeStreamWatcher.js");
|
|
2226
755
|
const io = createMockIo();
|
|
2227
756
|
|
|
2228
757
|
startChangeStreamWatcher(io, {}, true);
|
|
@@ -2237,7 +766,7 @@ describe("startChangeStreamWatcher", () => {
|
|
|
2237
766
|
it("throws when mongoose connection db is unavailable", async () => {
|
|
2238
767
|
setConnectionDb(undefined);
|
|
2239
768
|
|
|
2240
|
-
const {startChangeStreamWatcher} = await import("./changeStreamWatcher");
|
|
769
|
+
const {startChangeStreamWatcher} = await import("./changeStreamWatcher.js");
|
|
2241
770
|
const io = createMockIo();
|
|
2242
771
|
|
|
2243
772
|
expect(() => startChangeStreamWatcher(io)).toThrow(
|
|
@@ -2249,351 +778,32 @@ describe("startChangeStreamWatcher", () => {
|
|
|
2249
778
|
const mockDb = {
|
|
2250
779
|
watch: mock(() => null),
|
|
2251
780
|
};
|
|
2252
|
-
setConnectionDb(mockDb);
|
|
2253
|
-
|
|
2254
|
-
const {startChangeStreamWatcher} = await import("./changeStreamWatcher");
|
|
2255
|
-
const io = createMockIo();
|
|
2256
|
-
|
|
2257
|
-
expect(() => startChangeStreamWatcher(io)).toThrow("Failed to create change stream watcher");
|
|
2258
|
-
});
|
|
2259
|
-
|
|
2260
|
-
it("handles change events for registered models", async () => {
|
|
2261
|
-
const mockStream = createMockChangeStream();
|
|
2262
|
-
const mockDb = {
|
|
2263
|
-
watch: mock(() => mockStream),
|
|
2264
|
-
};
|
|
2265
|
-
setConnectionDb(mockDb);
|
|
2266
|
-
|
|
2267
|
-
registerRealtime({
|
|
2268
|
-
collectionName: "todos",
|
|
2269
|
-
config: {
|
|
2270
|
-
methods: ["create", "update", "delete"],
|
|
2271
|
-
roomStrategy: "model",
|
|
2272
|
-
},
|
|
2273
|
-
modelName: "Todo",
|
|
2274
|
-
options: {
|
|
2275
|
-
permissions: {
|
|
2276
|
-
create: [() => true],
|
|
2277
|
-
delete: [() => true],
|
|
2278
|
-
list: [() => true],
|
|
2279
|
-
read: [() => true],
|
|
2280
|
-
update: [() => true],
|
|
2281
|
-
},
|
|
2282
|
-
},
|
|
2283
|
-
routePath: "/todos",
|
|
2284
|
-
});
|
|
2285
|
-
|
|
2286
|
-
const {startChangeStreamWatcher} = await import("./changeStreamWatcher");
|
|
2287
|
-
const io = createMockIo();
|
|
2288
|
-
|
|
2289
|
-
startChangeStreamWatcher(io, {}, true);
|
|
2290
|
-
|
|
2291
|
-
// Trigger an insert change event
|
|
2292
|
-
await invokeRegisteredChangeHandler(mockStream, {
|
|
2293
|
-
documentKey: {_id: "doc-1"},
|
|
2294
|
-
fullDocument: {_id: "doc-1", name: "Test Todo"},
|
|
2295
|
-
ns: {coll: "todos"},
|
|
2296
|
-
operationType: "insert",
|
|
2297
|
-
});
|
|
2298
|
-
});
|
|
2299
|
-
|
|
2300
|
-
it("skips events for unregistered collections", async () => {
|
|
2301
|
-
const mockStream = createMockChangeStream();
|
|
2302
|
-
const mockDb = {
|
|
2303
|
-
watch: mock(() => mockStream),
|
|
2304
|
-
};
|
|
2305
|
-
setConnectionDb(mockDb);
|
|
2306
|
-
|
|
2307
|
-
const {startChangeStreamWatcher} = await import("./changeStreamWatcher");
|
|
2308
|
-
const io = createMockIo();
|
|
2309
|
-
|
|
2310
|
-
startChangeStreamWatcher(io, {}, true);
|
|
2311
|
-
|
|
2312
|
-
// Trigger for an unregistered collection — should not throw
|
|
2313
|
-
await invokeRegisteredChangeHandler(mockStream, {
|
|
2314
|
-
documentKey: {_id: "doc-1"},
|
|
2315
|
-
fullDocument: {_id: "doc-1"},
|
|
2316
|
-
ns: {coll: "unknown_collection"},
|
|
2317
|
-
operationType: "insert",
|
|
2318
|
-
});
|
|
2319
|
-
});
|
|
2320
|
-
|
|
2321
|
-
it("skips events when method is not enabled for the model", async () => {
|
|
2322
|
-
const mockStream = createMockChangeStream();
|
|
2323
|
-
const mockDb = {
|
|
2324
|
-
watch: mock(() => mockStream),
|
|
2325
|
-
};
|
|
2326
|
-
setConnectionDb(mockDb);
|
|
2327
|
-
|
|
2328
|
-
registerRealtime({
|
|
2329
|
-
collectionName: "todos",
|
|
2330
|
-
config: {
|
|
2331
|
-
methods: ["create"], // only create enabled
|
|
2332
|
-
roomStrategy: "model",
|
|
2333
|
-
},
|
|
2334
|
-
modelName: "Todo",
|
|
2335
|
-
options: {
|
|
2336
|
-
permissions: {
|
|
2337
|
-
create: [() => true],
|
|
2338
|
-
delete: [],
|
|
2339
|
-
list: [() => true],
|
|
2340
|
-
read: [() => true],
|
|
2341
|
-
update: [],
|
|
2342
|
-
},
|
|
2343
|
-
},
|
|
2344
|
-
routePath: "/todos",
|
|
2345
|
-
});
|
|
2346
|
-
|
|
2347
|
-
const {startChangeStreamWatcher} = await import("./changeStreamWatcher");
|
|
2348
|
-
const io = createMockIo();
|
|
2349
|
-
|
|
2350
|
-
startChangeStreamWatcher(io, {}, true);
|
|
2351
|
-
|
|
2352
|
-
// Update event should be skipped because "update" not in methods
|
|
2353
|
-
await invokeRegisteredChangeHandler(mockStream, {
|
|
2354
|
-
documentKey: {_id: "doc-1"},
|
|
2355
|
-
fullDocument: {_id: "doc-1", name: "Updated"},
|
|
2356
|
-
ns: {coll: "todos"},
|
|
2357
|
-
operationType: "update",
|
|
2358
|
-
updateDescription: {updatedFields: {name: "Updated"}},
|
|
2359
|
-
});
|
|
2360
|
-
});
|
|
2361
|
-
|
|
2362
|
-
it("handles delete events for owner-strategy models", async () => {
|
|
2363
|
-
const mockStream = createMockChangeStream();
|
|
2364
|
-
const mockDb = {
|
|
2365
|
-
watch: mock(() => mockStream),
|
|
2366
|
-
};
|
|
2367
|
-
setConnectionDb(mockDb);
|
|
2368
|
-
|
|
2369
|
-
registerRealtime({
|
|
2370
|
-
collectionName: "todos",
|
|
2371
|
-
config: {
|
|
2372
|
-
methods: ["create", "update", "delete"],
|
|
2373
|
-
roomStrategy: "owner",
|
|
2374
|
-
},
|
|
2375
|
-
modelName: "Todo",
|
|
2376
|
-
options: {
|
|
2377
|
-
permissions: {
|
|
2378
|
-
create: [() => true],
|
|
2379
|
-
delete: [() => true],
|
|
2380
|
-
list: [() => true],
|
|
2381
|
-
read: [() => true],
|
|
2382
|
-
update: [() => true],
|
|
2383
|
-
},
|
|
2384
|
-
},
|
|
2385
|
-
routePath: "/todos",
|
|
2386
|
-
});
|
|
2387
|
-
|
|
2388
|
-
const {startChangeStreamWatcher} = await import("./changeStreamWatcher");
|
|
2389
|
-
const io = createMockIo();
|
|
2390
|
-
|
|
2391
|
-
startChangeStreamWatcher(io, {}, true);
|
|
2392
|
-
|
|
2393
|
-
// Hard delete (no fullDocument)
|
|
2394
|
-
await invokeRegisteredChangeHandler(mockStream, {
|
|
2395
|
-
documentKey: {_id: "doc-1"},
|
|
2396
|
-
ns: {coll: "todos"},
|
|
2397
|
-
operationType: "delete",
|
|
2398
|
-
});
|
|
2399
|
-
});
|
|
2400
|
-
|
|
2401
|
-
it("handles delete events for broadcast-strategy models", async () => {
|
|
2402
|
-
const mockStream = createMockChangeStream();
|
|
2403
|
-
const mockDb = {
|
|
2404
|
-
watch: mock(() => mockStream),
|
|
2405
|
-
};
|
|
2406
|
-
setConnectionDb(mockDb);
|
|
2407
|
-
|
|
2408
|
-
registerRealtime({
|
|
2409
|
-
collectionName: "broadcasts",
|
|
2410
|
-
config: {
|
|
2411
|
-
methods: ["create", "update", "delete"],
|
|
2412
|
-
roomStrategy: "broadcast",
|
|
2413
|
-
},
|
|
2414
|
-
modelName: "Broadcast",
|
|
2415
|
-
options: {
|
|
2416
|
-
permissions: {
|
|
2417
|
-
create: [() => true],
|
|
2418
|
-
delete: [() => true],
|
|
2419
|
-
list: [() => true],
|
|
2420
|
-
read: [() => true],
|
|
2421
|
-
update: [() => true],
|
|
2422
|
-
},
|
|
2423
|
-
},
|
|
2424
|
-
routePath: "/broadcasts",
|
|
2425
|
-
});
|
|
2426
|
-
|
|
2427
|
-
const {startChangeStreamWatcher} = await import("./changeStreamWatcher");
|
|
2428
|
-
const io = createMockIo();
|
|
2429
|
-
|
|
2430
|
-
startChangeStreamWatcher(io, {}, true);
|
|
2431
|
-
|
|
2432
|
-
// Hard delete for broadcast strategy
|
|
2433
|
-
await invokeRegisteredChangeHandler(mockStream, {
|
|
2434
|
-
documentKey: {_id: "doc-1"},
|
|
2435
|
-
ns: {coll: "broadcasts"},
|
|
2436
|
-
operationType: "delete",
|
|
2437
|
-
});
|
|
2438
|
-
});
|
|
2439
|
-
|
|
2440
|
-
// Records every emission so hard-delete room routing can be asserted.
|
|
2441
|
-
const createRecordingIo = (
|
|
2442
|
-
room: string,
|
|
2443
|
-
decodedToken: {admin?: boolean; id?: string} = {admin: true, id: "admin"}
|
|
2444
|
-
): {
|
|
2445
|
-
emissions: Array<{event: string; payload: unknown}>;
|
|
2446
|
-
io: import("socket.io").Server;
|
|
2447
|
-
} => {
|
|
2448
|
-
const emissions: Array<{event: string; payload: unknown}> = [];
|
|
2449
|
-
const rooms = new Map<string, Set<string>>([[room, new Set(["socket-1"])]]);
|
|
2450
|
-
const sockets = new Map<string, unknown>([
|
|
2451
|
-
[
|
|
2452
|
-
"socket-1",
|
|
2453
|
-
{
|
|
2454
|
-
decodedToken,
|
|
2455
|
-
emit: (event: string, payload: unknown): void => {
|
|
2456
|
-
emissions.push({event, payload});
|
|
2457
|
-
},
|
|
2458
|
-
id: "socket-1",
|
|
2459
|
-
},
|
|
2460
|
-
],
|
|
2461
|
-
]);
|
|
2462
|
-
return {
|
|
2463
|
-
emissions,
|
|
2464
|
-
io: {
|
|
2465
|
-
sockets: {adapter: {rooms}, sockets},
|
|
2466
|
-
to: (_room: string) => ({emit: (_event: string, _data: unknown) => {}}),
|
|
2467
|
-
} as unknown as import("socket.io").Server,
|
|
2468
|
-
};
|
|
2469
|
-
};
|
|
2470
|
-
|
|
2471
|
-
it("routes hard deletes for model-strategy models to the model room", async () => {
|
|
2472
|
-
const mockStream = createMockChangeStream();
|
|
2473
|
-
const mockDb = {
|
|
2474
|
-
watch: mock(() => mockStream),
|
|
2475
|
-
};
|
|
2476
|
-
setConnectionDb(mockDb);
|
|
2477
|
-
|
|
2478
|
-
registerRealtime({
|
|
2479
|
-
collectionName: "todos",
|
|
2480
|
-
config: {
|
|
2481
|
-
methods: ["create", "update", "delete"],
|
|
2482
|
-
roomStrategy: "model",
|
|
2483
|
-
},
|
|
2484
|
-
modelName: "Todo",
|
|
2485
|
-
options: {
|
|
2486
|
-
permissions: {
|
|
2487
|
-
create: [() => true],
|
|
2488
|
-
delete: [() => true],
|
|
2489
|
-
list: [() => true],
|
|
2490
|
-
read: [() => true],
|
|
2491
|
-
update: [() => true],
|
|
2492
|
-
},
|
|
2493
|
-
},
|
|
2494
|
-
routePath: "/todos",
|
|
2495
|
-
});
|
|
2496
|
-
|
|
2497
|
-
const {startChangeStreamWatcher} = await import("./changeStreamWatcher");
|
|
2498
|
-
const {emissions, io} = createRecordingIo("model:todos");
|
|
2499
|
-
|
|
2500
|
-
startChangeStreamWatcher(io, {}, true);
|
|
2501
|
-
|
|
2502
|
-
await invokeRegisteredChangeHandler(mockStream, {
|
|
2503
|
-
documentKey: {_id: "doc-1"},
|
|
2504
|
-
ns: {coll: "todos"},
|
|
2505
|
-
operationType: "delete",
|
|
2506
|
-
});
|
|
2507
|
-
|
|
2508
|
-
expect(emissions).toHaveLength(1);
|
|
2509
|
-
expect(emissions[0].payload).toMatchObject({id: "doc-1", method: "delete", model: "Todo"});
|
|
2510
|
-
});
|
|
2511
|
-
|
|
2512
|
-
it("swallows errors thrown while processing a change event", async () => {
|
|
2513
|
-
const mockStream = createMockChangeStream();
|
|
2514
|
-
const mockDb = {
|
|
2515
|
-
watch: mock(() => mockStream),
|
|
2516
|
-
};
|
|
2517
|
-
setConnectionDb(mockDb);
|
|
2518
|
-
|
|
2519
|
-
registerRealtime({
|
|
2520
|
-
collectionName: "todos",
|
|
2521
|
-
config: {
|
|
2522
|
-
methods: ["create", "update", "delete"],
|
|
2523
|
-
roomStrategy: "model",
|
|
2524
|
-
},
|
|
2525
|
-
modelName: "Todo",
|
|
2526
|
-
options: {
|
|
2527
|
-
permissions: {
|
|
2528
|
-
create: [() => true],
|
|
2529
|
-
delete: [() => true],
|
|
2530
|
-
list: [() => true],
|
|
2531
|
-
read: [() => true],
|
|
2532
|
-
update: [() => true],
|
|
2533
|
-
},
|
|
2534
|
-
},
|
|
2535
|
-
routePath: "/todos",
|
|
2536
|
-
});
|
|
2537
|
-
|
|
2538
|
-
const {startChangeStreamWatcher} = await import("./changeStreamWatcher");
|
|
2539
|
-
const roomLookup = mock(() => {
|
|
2540
|
-
throw new Error("adapter unavailable");
|
|
2541
|
-
});
|
|
2542
|
-
const io = {
|
|
2543
|
-
sockets: {adapter: {rooms: {get: roomLookup}}, sockets: new Map()},
|
|
2544
|
-
to: (_room: string) => ({emit: (_event: string, _data: unknown) => {}}),
|
|
2545
|
-
} as unknown as import("socket.io").Server;
|
|
2546
|
-
|
|
2547
|
-
startChangeStreamWatcher(io, {}, true);
|
|
781
|
+
setConnectionDb(mockDb);
|
|
2548
782
|
|
|
2549
|
-
|
|
2550
|
-
|
|
2551
|
-
documentKey: {_id: "doc-1"},
|
|
2552
|
-
fullDocument: {_id: "doc-1", name: "Test Todo"},
|
|
2553
|
-
ns: {coll: "todos"},
|
|
2554
|
-
operationType: "insert",
|
|
2555
|
-
});
|
|
783
|
+
const {startChangeStreamWatcher} = await import("./changeStreamWatcher.js");
|
|
784
|
+
const io = createMockIo();
|
|
2556
785
|
|
|
2557
|
-
expect(
|
|
786
|
+
expect(() => startChangeStreamWatcher(io)).toThrow("Failed to create change stream watcher");
|
|
2558
787
|
});
|
|
2559
788
|
|
|
2560
|
-
it("
|
|
789
|
+
it("skips events for unregistered collections", async () => {
|
|
2561
790
|
const mockStream = createMockChangeStream();
|
|
2562
791
|
const mockDb = {
|
|
2563
792
|
watch: mock(() => mockStream),
|
|
2564
793
|
};
|
|
2565
794
|
setConnectionDb(mockDb);
|
|
2566
795
|
|
|
2567
|
-
|
|
2568
|
-
collectionName: "todos",
|
|
2569
|
-
config: {
|
|
2570
|
-
methods: ["create", "update", "delete"],
|
|
2571
|
-
roomStrategy: "model",
|
|
2572
|
-
},
|
|
2573
|
-
modelName: "Todo",
|
|
2574
|
-
options: {
|
|
2575
|
-
permissions: {
|
|
2576
|
-
create: [() => true],
|
|
2577
|
-
delete: [() => true],
|
|
2578
|
-
list: [() => true],
|
|
2579
|
-
read: [() => true],
|
|
2580
|
-
update: [() => true],
|
|
2581
|
-
},
|
|
2582
|
-
},
|
|
2583
|
-
routePath: "/todos",
|
|
2584
|
-
});
|
|
2585
|
-
|
|
2586
|
-
const {startChangeStreamWatcher} = await import("./changeStreamWatcher");
|
|
796
|
+
const {startChangeStreamWatcher} = await import("./changeStreamWatcher.js");
|
|
2587
797
|
const io = createMockIo();
|
|
2588
798
|
|
|
2589
799
|
startChangeStreamWatcher(io, {}, true);
|
|
2590
800
|
|
|
801
|
+
// Trigger for an unregistered collection — should not throw
|
|
2591
802
|
await invokeRegisteredChangeHandler(mockStream, {
|
|
2592
803
|
documentKey: {_id: "doc-1"},
|
|
2593
|
-
fullDocument: {_id: "doc-1"
|
|
2594
|
-
ns: {coll: "
|
|
2595
|
-
operationType: "
|
|
2596
|
-
updateDescription: {updatedFields: {name: "Updated", status: "done"}},
|
|
804
|
+
fullDocument: {_id: "doc-1"},
|
|
805
|
+
ns: {coll: "unknown_collection"},
|
|
806
|
+
operationType: "insert",
|
|
2597
807
|
});
|
|
2598
808
|
});
|
|
2599
809
|
|
|
@@ -2604,7 +814,7 @@ describe("startChangeStreamWatcher", () => {
|
|
|
2604
814
|
};
|
|
2605
815
|
setConnectionDb(mockDb);
|
|
2606
816
|
|
|
2607
|
-
const {startChangeStreamWatcher} = await import("./changeStreamWatcher");
|
|
817
|
+
const {startChangeStreamWatcher} = await import("./changeStreamWatcher.js");
|
|
2608
818
|
const io = createMockIo();
|
|
2609
819
|
|
|
2610
820
|
startChangeStreamWatcher(io, {ignoredCollections: ["audit_logs"]}, true);
|
|
@@ -2626,26 +836,7 @@ describe("startChangeStreamWatcher", () => {
|
|
|
2626
836
|
};
|
|
2627
837
|
setConnectionDb(mockDb);
|
|
2628
838
|
|
|
2629
|
-
|
|
2630
|
-
collectionName: "todos",
|
|
2631
|
-
config: {
|
|
2632
|
-
methods: ["create", "update", "delete"],
|
|
2633
|
-
roomStrategy: "model",
|
|
2634
|
-
},
|
|
2635
|
-
modelName: "Todo",
|
|
2636
|
-
options: {
|
|
2637
|
-
permissions: {
|
|
2638
|
-
create: [() => true],
|
|
2639
|
-
delete: [() => true],
|
|
2640
|
-
list: [() => true],
|
|
2641
|
-
read: [() => true],
|
|
2642
|
-
update: [() => true],
|
|
2643
|
-
},
|
|
2644
|
-
},
|
|
2645
|
-
routePath: "/todos",
|
|
2646
|
-
});
|
|
2647
|
-
|
|
2648
|
-
const {startChangeStreamWatcher} = await import("./changeStreamWatcher");
|
|
839
|
+
const {startChangeStreamWatcher} = await import("./changeStreamWatcher.js");
|
|
2649
840
|
const io = createMockIo();
|
|
2650
841
|
|
|
2651
842
|
startChangeStreamWatcher(io, {ignoredOperations: ["insert"]}, true);
|
|
@@ -2659,6 +850,34 @@ describe("startChangeStreamWatcher", () => {
|
|
|
2659
850
|
});
|
|
2660
851
|
});
|
|
2661
852
|
|
|
853
|
+
it("swallows errors thrown while processing a change event", async () => {
|
|
854
|
+
const mockStream = createMockChangeStream();
|
|
855
|
+
const mockDb = {
|
|
856
|
+
watch: mock(() => mockStream),
|
|
857
|
+
};
|
|
858
|
+
setConnectionDb(mockDb);
|
|
859
|
+
|
|
860
|
+
const {startChangeStreamWatcher} = await import("./changeStreamWatcher.js");
|
|
861
|
+
const io = createMockIo();
|
|
862
|
+
|
|
863
|
+
startChangeStreamWatcher(io, {}, true);
|
|
864
|
+
|
|
865
|
+
const malformedEvent = {
|
|
866
|
+
documentKey: {_id: "doc-1"},
|
|
867
|
+
get ns(): never {
|
|
868
|
+
throw new Error("malformed change event");
|
|
869
|
+
},
|
|
870
|
+
operationType: "insert",
|
|
871
|
+
};
|
|
872
|
+
// The handler must not reject — one bad event cannot take down the change stream.
|
|
873
|
+
await expect(
|
|
874
|
+
invokeRegisteredChangeHandler(
|
|
875
|
+
mockStream,
|
|
876
|
+
malformedEvent as unknown as Record<string, unknown>
|
|
877
|
+
)
|
|
878
|
+
).resolves.toBeUndefined();
|
|
879
|
+
});
|
|
880
|
+
|
|
2662
881
|
it("skips events with no collectionName or docId", async () => {
|
|
2663
882
|
const mockStream = createMockChangeStream();
|
|
2664
883
|
const mockDb = {
|
|
@@ -2666,7 +885,7 @@ describe("startChangeStreamWatcher", () => {
|
|
|
2666
885
|
};
|
|
2667
886
|
setConnectionDb(mockDb);
|
|
2668
887
|
|
|
2669
|
-
const {startChangeStreamWatcher} = await import("./changeStreamWatcher");
|
|
888
|
+
const {startChangeStreamWatcher} = await import("./changeStreamWatcher.js");
|
|
2670
889
|
const io = createMockIo();
|
|
2671
890
|
|
|
2672
891
|
startChangeStreamWatcher(io, {}, true);
|
|
@@ -2692,7 +911,7 @@ describe("startChangeStreamWatcher", () => {
|
|
|
2692
911
|
};
|
|
2693
912
|
setConnectionDb(mockDb);
|
|
2694
913
|
|
|
2695
|
-
const {startChangeStreamWatcher} = await import("./changeStreamWatcher");
|
|
914
|
+
const {startChangeStreamWatcher} = await import("./changeStreamWatcher.js");
|
|
2696
915
|
const io = createMockIo();
|
|
2697
916
|
|
|
2698
917
|
startChangeStreamWatcher(io, {}, true);
|
|
@@ -2703,43 +922,6 @@ describe("startChangeStreamWatcher", () => {
|
|
|
2703
922
|
});
|
|
2704
923
|
});
|
|
2705
924
|
|
|
2706
|
-
it("returns early when the mapped realtime operation is null", async () => {
|
|
2707
|
-
const mockStream = createMockChangeStream();
|
|
2708
|
-
const mockDb = {
|
|
2709
|
-
watch: mock(() => mockStream),
|
|
2710
|
-
};
|
|
2711
|
-
setConnectionDb(mockDb);
|
|
2712
|
-
|
|
2713
|
-
registerRealtime({
|
|
2714
|
-
collectionName: "todos",
|
|
2715
|
-
config: {
|
|
2716
|
-
methods: ["create", "update", "delete"],
|
|
2717
|
-
roomStrategy: "model",
|
|
2718
|
-
},
|
|
2719
|
-
modelName: "Todo",
|
|
2720
|
-
options: {permissions: permissiveOptions.permissions},
|
|
2721
|
-
routePath: "/todos",
|
|
2722
|
-
});
|
|
2723
|
-
|
|
2724
|
-
const {startChangeStreamWatcher} = await import("./changeStreamWatcher");
|
|
2725
|
-
const {emissions, io} = createRecordingIo("model:todos");
|
|
2726
|
-
let operationTypeReads = 0;
|
|
2727
|
-
startChangeStreamWatcher(io, {}, true);
|
|
2728
|
-
|
|
2729
|
-
await invokeRegisteredChangeHandler(mockStream, {
|
|
2730
|
-
documentKey: {_id: "doc-1"},
|
|
2731
|
-
fullDocument: {_id: "doc-1"},
|
|
2732
|
-
ns: {coll: "todos"},
|
|
2733
|
-
get operationType(): string {
|
|
2734
|
-
operationTypeReads += 1;
|
|
2735
|
-
return operationTypeReads === 1 ? "insert" : "invalidate";
|
|
2736
|
-
},
|
|
2737
|
-
});
|
|
2738
|
-
|
|
2739
|
-
assert.isAtLeast(operationTypeReads, 2);
|
|
2740
|
-
assert.isEmpty(emissions);
|
|
2741
|
-
});
|
|
2742
|
-
|
|
2743
925
|
it("handles error/close/end events gracefully", async () => {
|
|
2744
926
|
const mockStream = createMockChangeStream();
|
|
2745
927
|
const mockDb = {
|
|
@@ -2747,7 +929,7 @@ describe("startChangeStreamWatcher", () => {
|
|
|
2747
929
|
};
|
|
2748
930
|
setConnectionDb(mockDb);
|
|
2749
931
|
|
|
2750
|
-
const {startChangeStreamWatcher} = await import("./changeStreamWatcher");
|
|
932
|
+
const {startChangeStreamWatcher} = await import("./changeStreamWatcher.js");
|
|
2751
933
|
const io = createMockIo();
|
|
2752
934
|
|
|
2753
935
|
startChangeStreamWatcher(io, {}, true);
|
|
@@ -2759,7 +941,7 @@ describe("startChangeStreamWatcher", () => {
|
|
|
2759
941
|
});
|
|
2760
942
|
|
|
2761
943
|
// Task 9.16: a transient stream failure used to be logged and then permanently starve
|
|
2762
|
-
// every
|
|
944
|
+
// every sync delta until the process restarted.
|
|
2763
945
|
describe("restart with resume token (Task 9.16)", () => {
|
|
2764
946
|
const waitFor = async (
|
|
2765
947
|
predicate: () => boolean,
|
|
@@ -2776,65 +958,37 @@ describe("startChangeStreamWatcher", () => {
|
|
|
2776
958
|
throw new Error(`Timed out after ${timeoutMs}ms waiting for ${label}`);
|
|
2777
959
|
};
|
|
2778
960
|
|
|
2779
|
-
|
|
2780
|
-
registerRealtime({
|
|
2781
|
-
collectionName: "todos",
|
|
2782
|
-
config: {methods: ["create", "update", "delete"], roomStrategy: "model"},
|
|
2783
|
-
modelName: "Todo",
|
|
2784
|
-
options: {
|
|
2785
|
-
permissions: {
|
|
2786
|
-
create: [() => true],
|
|
2787
|
-
delete: [() => true],
|
|
2788
|
-
list: [() => true],
|
|
2789
|
-
read: [() => true],
|
|
2790
|
-
update: [() => true],
|
|
2791
|
-
},
|
|
2792
|
-
},
|
|
2793
|
-
routePath: "/todos",
|
|
2794
|
-
});
|
|
2795
|
-
};
|
|
2796
|
-
|
|
2797
|
-
/** An io whose room socket records deliveries, plus a recorded server-wide `emit`. */
|
|
961
|
+
/** An io with no sockets that records server-wide `emit` calls. */
|
|
2798
962
|
const createRecordingIo = (): {
|
|
2799
963
|
io: import("socket.io").Server;
|
|
2800
|
-
deliveries: {event: string; payload: unknown}[];
|
|
2801
964
|
serverEmissions: {event: string; payload: unknown}[];
|
|
2802
965
|
} => {
|
|
2803
|
-
const deliveries: {event: string; payload: unknown}[] = [];
|
|
2804
966
|
const serverEmissions: {event: string; payload: unknown}[] = [];
|
|
2805
|
-
const rooms = new Map<string, Set<string>>();
|
|
2806
|
-
rooms.set("model:todos", new Set(["sock-1"]));
|
|
2807
|
-
const sockets = new Map<string, MockRoomSocket>();
|
|
2808
|
-
sockets.set("sock-1", {
|
|
2809
|
-
decodedToken: {id: "user-1"},
|
|
2810
|
-
emit: (event: string, payload: unknown) => {
|
|
2811
|
-
deliveries.push({event, payload});
|
|
2812
|
-
},
|
|
2813
|
-
id: "sock-1",
|
|
2814
|
-
});
|
|
2815
967
|
return {
|
|
2816
|
-
deliveries,
|
|
2817
968
|
io: {
|
|
2818
969
|
emit: (event: string, payload: unknown) => {
|
|
2819
970
|
serverEmissions.push({event, payload});
|
|
2820
971
|
},
|
|
2821
|
-
sockets: {adapter: {rooms}, sockets},
|
|
972
|
+
sockets: {adapter: {rooms: new Map()}, sockets: new Map()},
|
|
2822
973
|
to: () => ({emit: () => {}}),
|
|
2823
974
|
} as unknown as import("socket.io").Server,
|
|
2824
975
|
serverEmissions,
|
|
2825
976
|
};
|
|
2826
977
|
};
|
|
2827
978
|
|
|
2828
|
-
|
|
979
|
+
const resumeAfterForCall = (watch: ReturnType<typeof mock>, callIndex: number): unknown =>
|
|
980
|
+
((watch.mock.calls[callIndex] as unknown[])[1] as {resumeAfter?: unknown}).resumeAfter;
|
|
981
|
+
|
|
982
|
+
it("reopens with resumeAfter after a stream error and keeps tracking changes", async () => {
|
|
2829
983
|
const firstStream = createMockChangeStream();
|
|
2830
984
|
const secondStream = createMockChangeStream();
|
|
2831
|
-
const
|
|
2832
|
-
const
|
|
985
|
+
const thirdStream = createMockChangeStream();
|
|
986
|
+
const streams = [firstStream, secondStream, thirdStream];
|
|
987
|
+
const mockDb = {watch: mock(() => streams.shift() ?? thirdStream)};
|
|
2833
988
|
setConnectionDb(mockDb);
|
|
2834
|
-
registerTodos();
|
|
2835
989
|
|
|
2836
|
-
const {startChangeStreamWatcher} = await import("./changeStreamWatcher");
|
|
2837
|
-
const {
|
|
990
|
+
const {startChangeStreamWatcher} = await import("./changeStreamWatcher.js");
|
|
991
|
+
const {io} = createRecordingIo();
|
|
2838
992
|
startChangeStreamWatcher(io, {}, true);
|
|
2839
993
|
|
|
2840
994
|
// A change on the first stream establishes the resume position.
|
|
@@ -2842,28 +996,25 @@ describe("startChangeStreamWatcher", () => {
|
|
|
2842
996
|
_id: {_data: "token-1"},
|
|
2843
997
|
documentKey: {_id: "doc-1"},
|
|
2844
998
|
fullDocument: {_id: "doc-1", name: "before the failure"},
|
|
2845
|
-
ns: {coll: "
|
|
999
|
+
ns: {coll: "unregistered"},
|
|
2846
1000
|
operationType: "insert",
|
|
2847
1001
|
});
|
|
2848
|
-
expect(deliveries).toHaveLength(1);
|
|
2849
1002
|
|
|
2850
1003
|
firstStream.trigger("error", new Error("replica set election"));
|
|
2851
1004
|
await waitFor(() => mockDb.watch.mock.calls.length >= 2, "the stream to reopen");
|
|
1005
|
+
expect(resumeAfterForCall(mockDb.watch, 1)).toEqual({_data: "token-1"});
|
|
2852
1006
|
|
|
2853
|
-
|
|
2854
|
-
resumeAfter?: unknown;
|
|
2855
|
-
};
|
|
2856
|
-
expect(reopenOptions.resumeAfter).toEqual({_data: "token-1"});
|
|
2857
|
-
|
|
2858
|
-
// The reopened stream is fully wired: later writes still fan out.
|
|
1007
|
+
// The reopened stream is fully wired: its changes advance the resume position.
|
|
2859
1008
|
await invokeRegisteredChangeHandler(secondStream, {
|
|
2860
1009
|
_id: {_data: "token-2"},
|
|
2861
1010
|
documentKey: {_id: "doc-2"},
|
|
2862
1011
|
fullDocument: {_id: "doc-2", name: "after the restart"},
|
|
2863
|
-
ns: {coll: "
|
|
1012
|
+
ns: {coll: "unregistered"},
|
|
2864
1013
|
operationType: "insert",
|
|
2865
1014
|
});
|
|
2866
|
-
|
|
1015
|
+
secondStream.trigger("error", new Error("network blip"));
|
|
1016
|
+
await waitFor(() => mockDb.watch.mock.calls.length >= 3, "the stream to reopen again");
|
|
1017
|
+
expect(resumeAfterForCall(mockDb.watch, 2)).toEqual({_data: "token-2"});
|
|
2867
1018
|
});
|
|
2868
1019
|
|
|
2869
1020
|
it("drops the resume token and asks clients to resync when the oplog history is lost", async () => {
|
|
@@ -2873,7 +1024,9 @@ describe("startChangeStreamWatcher", () => {
|
|
|
2873
1024
|
const mockDb = {watch: mock(() => streams.shift() ?? secondStream)};
|
|
2874
1025
|
setConnectionDb(mockDb);
|
|
2875
1026
|
|
|
2876
|
-
const {SYNC_RESYNC_EVENT, startChangeStreamWatcher} = await import(
|
|
1027
|
+
const {SYNC_RESYNC_EVENT, startChangeStreamWatcher} = await import(
|
|
1028
|
+
"./changeStreamWatcher.js"
|
|
1029
|
+
);
|
|
2877
1030
|
const {io, serverEmissions} = createRecordingIo();
|
|
2878
1031
|
startChangeStreamWatcher(io, {}, true);
|
|
2879
1032
|
|
|
@@ -2907,7 +1060,7 @@ describe("startChangeStreamWatcher", () => {
|
|
|
2907
1060
|
setConnectionDb(mockDb);
|
|
2908
1061
|
|
|
2909
1062
|
const {startChangeStreamWatcher, stopChangeStreamWatcher: stop} = await import(
|
|
2910
|
-
"./changeStreamWatcher"
|
|
1063
|
+
"./changeStreamWatcher.js"
|
|
2911
1064
|
);
|
|
2912
1065
|
const {io} = createRecordingIo();
|
|
2913
1066
|
startChangeStreamWatcher(io, {}, true);
|
|
@@ -2926,7 +1079,7 @@ describe("startChangeStreamWatcher", () => {
|
|
|
2926
1079
|
};
|
|
2927
1080
|
setConnectionDb(mockDb);
|
|
2928
1081
|
|
|
2929
|
-
const {startChangeStreamWatcher} = await import("./changeStreamWatcher");
|
|
1082
|
+
const {startChangeStreamWatcher} = await import("./changeStreamWatcher.js");
|
|
2930
1083
|
const io = createMockIo();
|
|
2931
1084
|
|
|
2932
1085
|
startChangeStreamWatcher(io, {batchSize: 100, fullDocument: "whenAvailable"}, true);
|
|
@@ -2938,71 +1091,6 @@ describe("startChangeStreamWatcher", () => {
|
|
|
2938
1091
|
expect(options.batchSize).toBe(100);
|
|
2939
1092
|
expect(options.fullDocument).toBe("whenAvailable");
|
|
2940
1093
|
});
|
|
2941
|
-
|
|
2942
|
-
it("catches errors thrown in the change handler", async () => {
|
|
2943
|
-
const mockStream = createMockChangeStream();
|
|
2944
|
-
const mockDb = {
|
|
2945
|
-
watch: mock(() => mockStream),
|
|
2946
|
-
};
|
|
2947
|
-
setConnectionDb(mockDb);
|
|
2948
|
-
|
|
2949
|
-
// Register with a model that will throw during permission check
|
|
2950
|
-
registerRealtime({
|
|
2951
|
-
collectionName: "todos",
|
|
2952
|
-
config: {
|
|
2953
|
-
methods: ["create", "update", "delete"],
|
|
2954
|
-
roomStrategy: "model",
|
|
2955
|
-
},
|
|
2956
|
-
modelName: "Todo",
|
|
2957
|
-
options: {
|
|
2958
|
-
permissions: {
|
|
2959
|
-
create: [() => true],
|
|
2960
|
-
delete: [() => true],
|
|
2961
|
-
list: [() => true],
|
|
2962
|
-
read: [
|
|
2963
|
-
() => {
|
|
2964
|
-
throw new Error("permission check error");
|
|
2965
|
-
},
|
|
2966
|
-
],
|
|
2967
|
-
update: [() => true],
|
|
2968
|
-
},
|
|
2969
|
-
},
|
|
2970
|
-
routePath: "/todos",
|
|
2971
|
-
});
|
|
2972
|
-
|
|
2973
|
-
const {startChangeStreamWatcher} = await import("./changeStreamWatcher");
|
|
2974
|
-
|
|
2975
|
-
// Create an IO with a socket in the target room
|
|
2976
|
-
const emissions: Array<{_data: unknown; _event: string}> = [];
|
|
2977
|
-
const mockSocket: MockRoomSocket = {
|
|
2978
|
-
decodedToken: {id: "user-1"},
|
|
2979
|
-
emit: (_event: string, _data: unknown) => {
|
|
2980
|
-
emissions.push({_data, _event});
|
|
2981
|
-
},
|
|
2982
|
-
id: "sock-1",
|
|
2983
|
-
};
|
|
2984
|
-
const rooms = new Map<string, Set<string>>();
|
|
2985
|
-
rooms.set("model:todos", new Set(["sock-1"]));
|
|
2986
|
-
const sockets = new Map<string, MockRoomSocket>();
|
|
2987
|
-
sockets.set("sock-1", mockSocket);
|
|
2988
|
-
const io = {
|
|
2989
|
-
sockets: {
|
|
2990
|
-
adapter: {rooms},
|
|
2991
|
-
sockets,
|
|
2992
|
-
},
|
|
2993
|
-
to: () => ({emit: () => {}}),
|
|
2994
|
-
} as unknown as import("socket.io").Server;
|
|
2995
|
-
|
|
2996
|
-
startChangeStreamWatcher(io, {}, true);
|
|
2997
|
-
|
|
2998
|
-
// Should not throw even though permission check throws
|
|
2999
|
-
await invokeRegisteredChangeHandler(mockStream, {
|
|
3000
|
-
documentKey: {_id: "doc-1"},
|
|
3001
|
-
fullDocument: {_id: "doc-1", name: "Test"},
|
|
3002
|
-
ns: {coll: "todos"},
|
|
3003
|
-
operationType: "insert",
|
|
3004
|
-
});
|
|
3005
|
-
});
|
|
3006
1094
|
});
|
|
3007
1095
|
|
|
3008
1096
|
describe("stopChangeStreamWatcher", () => {
|
|
@@ -3018,7 +1106,7 @@ describe("stopChangeStreamWatcher", () => {
|
|
|
3018
1106
|
setConnectionDb(mockDb);
|
|
3019
1107
|
|
|
3020
1108
|
const {startChangeStreamWatcher, stopChangeStreamWatcher} = await import(
|
|
3021
|
-
"./changeStreamWatcher"
|
|
1109
|
+
"./changeStreamWatcher.js"
|
|
3022
1110
|
);
|
|
3023
1111
|
const io = {
|
|
3024
1112
|
sockets: {
|
|
@@ -3235,7 +1323,6 @@ describe("startChangeStreamWatcher & stopChangeStreamWatcher", () => {
|
|
|
3235
1323
|
|
|
3236
1324
|
afterEach(async () => {
|
|
3237
1325
|
await stopChangeStreamWatcher();
|
|
3238
|
-
clearRealtimeRegistry();
|
|
3239
1326
|
});
|
|
3240
1327
|
|
|
3241
1328
|
it("starts and stops without error when MongoDB is connected", async () => {
|
|
@@ -3279,428 +1366,6 @@ describe("startChangeStreamWatcher & stopChangeStreamWatcher", () => {
|
|
|
3279
1366
|
});
|
|
3280
1367
|
});
|
|
3281
1368
|
|
|
3282
|
-
// Change streams require a MongoDB replica set. CI (api-ci.yml) runs standalone MongoDB,
|
|
3283
|
-
// so these tests are skipped when replica sets are not available.
|
|
3284
|
-
const hasReplicaSet = async (): Promise<boolean> => {
|
|
3285
|
-
try {
|
|
3286
|
-
const mongoose = require("mongoose");
|
|
3287
|
-
const admin = mongoose.connection.db.admin();
|
|
3288
|
-
const status = await admin.command({replSetGetStatus: 1});
|
|
3289
|
-
return !!status.ok;
|
|
3290
|
-
} catch {
|
|
3291
|
-
return false;
|
|
3292
|
-
}
|
|
3293
|
-
};
|
|
3294
|
-
|
|
3295
|
-
describe("startChangeStreamWatcher — change event integration", () => {
|
|
3296
|
-
const mongoose = require("mongoose");
|
|
3297
|
-
let replicaSetAvailable = false;
|
|
3298
|
-
|
|
3299
|
-
const realtimeTestSchema = new mongoose.Schema(
|
|
3300
|
-
{
|
|
3301
|
-
deleted: {default: false, type: Boolean},
|
|
3302
|
-
name: {type: String},
|
|
3303
|
-
ownerId: {type: String},
|
|
3304
|
-
},
|
|
3305
|
-
{collection: "realtimetests", strict: "throw"}
|
|
3306
|
-
);
|
|
3307
|
-
|
|
3308
|
-
interface RealtimeTestDoc {
|
|
3309
|
-
deleted?: boolean;
|
|
3310
|
-
name?: string;
|
|
3311
|
-
ownerId?: string;
|
|
3312
|
-
}
|
|
3313
|
-
|
|
3314
|
-
let RealtimeTestModel: Model<RealtimeTestDoc>;
|
|
3315
|
-
try {
|
|
3316
|
-
RealtimeTestModel = mongoose.model("RealtimeTest");
|
|
3317
|
-
} catch {
|
|
3318
|
-
RealtimeTestModel = mongoose.model("RealtimeTest", realtimeTestSchema);
|
|
3319
|
-
}
|
|
3320
|
-
|
|
3321
|
-
interface TrackedEmission {
|
|
3322
|
-
event: string;
|
|
3323
|
-
payload: RealtimeEvent;
|
|
3324
|
-
room?: string;
|
|
3325
|
-
socketId?: string;
|
|
3326
|
-
}
|
|
3327
|
-
|
|
3328
|
-
const makeTrackedIo = (): Server & {
|
|
3329
|
-
addSocketToRoom: (room: string, decodedToken?: DecodedRealtimeToken) => void;
|
|
3330
|
-
emissions: TrackedEmission[];
|
|
3331
|
-
} => {
|
|
3332
|
-
const emissions: TrackedEmission[] = [];
|
|
3333
|
-
const rooms = new Map<string, Set<string>>();
|
|
3334
|
-
const sockets = new Map<string, MockRoomSocket>();
|
|
3335
|
-
|
|
3336
|
-
const addSocketToRoom = (
|
|
3337
|
-
room: string,
|
|
3338
|
-
decodedToken: DecodedRealtimeToken = {admin: true, id: "admin"}
|
|
3339
|
-
): void => {
|
|
3340
|
-
const socketId = `socket-${Math.random().toString(36).slice(2, 9)}`;
|
|
3341
|
-
if (!rooms.has(room)) {
|
|
3342
|
-
rooms.set(room, new Set());
|
|
3343
|
-
}
|
|
3344
|
-
rooms.get(room)?.add(socketId);
|
|
3345
|
-
sockets.set(socketId, {
|
|
3346
|
-
decodedToken,
|
|
3347
|
-
emit: (event: string, payload: unknown): void => {
|
|
3348
|
-
emissions.push({event, payload: payload as RealtimeEvent, room, socketId});
|
|
3349
|
-
},
|
|
3350
|
-
id: socketId,
|
|
3351
|
-
});
|
|
3352
|
-
};
|
|
3353
|
-
|
|
3354
|
-
return {
|
|
3355
|
-
addSocketToRoom,
|
|
3356
|
-
emissions,
|
|
3357
|
-
sockets: {
|
|
3358
|
-
adapter: {rooms},
|
|
3359
|
-
sockets,
|
|
3360
|
-
},
|
|
3361
|
-
to: (room: string) => ({
|
|
3362
|
-
emit: (event: string, payload: unknown): void => {
|
|
3363
|
-
emissions.push({event, payload: payload as RealtimeEvent, room});
|
|
3364
|
-
},
|
|
3365
|
-
}),
|
|
3366
|
-
} as unknown as Server & {
|
|
3367
|
-
addSocketToRoom: (room: string, decodedToken?: DecodedRealtimeToken) => void;
|
|
3368
|
-
emissions: TrackedEmission[];
|
|
3369
|
-
};
|
|
3370
|
-
};
|
|
3371
|
-
|
|
3372
|
-
beforeAll(async () => {
|
|
3373
|
-
replicaSetAvailable = await hasReplicaSet();
|
|
3374
|
-
});
|
|
3375
|
-
|
|
3376
|
-
beforeEach(async () => {
|
|
3377
|
-
clearRealtimeRegistry();
|
|
3378
|
-
clearQueryStore();
|
|
3379
|
-
await RealtimeTestModel.deleteMany({});
|
|
3380
|
-
});
|
|
3381
|
-
|
|
3382
|
-
afterEach(async () => {
|
|
3383
|
-
await stopChangeStreamWatcher();
|
|
3384
|
-
clearRealtimeRegistry();
|
|
3385
|
-
clearQueryStore();
|
|
3386
|
-
await RealtimeTestModel.deleteMany({});
|
|
3387
|
-
});
|
|
3388
|
-
|
|
3389
|
-
it("processes insert events from MongoDB change stream", async () => {
|
|
3390
|
-
if (!replicaSetAvailable) {
|
|
3391
|
-
return;
|
|
3392
|
-
}
|
|
3393
|
-
registerRealtime({
|
|
3394
|
-
collectionName: "realtimetests",
|
|
3395
|
-
config: {methods: ["create", "update", "delete"], roomStrategy: "model"},
|
|
3396
|
-
modelName: "RealtimeTest",
|
|
3397
|
-
options: {
|
|
3398
|
-
permissions: {
|
|
3399
|
-
create: [() => true],
|
|
3400
|
-
delete: [() => true],
|
|
3401
|
-
list: [() => true],
|
|
3402
|
-
read: [() => true],
|
|
3403
|
-
update: [() => true],
|
|
3404
|
-
},
|
|
3405
|
-
},
|
|
3406
|
-
routePath: "/realtimetests",
|
|
3407
|
-
});
|
|
3408
|
-
|
|
3409
|
-
const io = makeTrackedIo();
|
|
3410
|
-
io.addSocketToRoom("model:realtimetests");
|
|
3411
|
-
startChangeStreamWatcher(io, {}, true);
|
|
3412
|
-
|
|
3413
|
-
await RealtimeTestModel.create({name: "test-item", ownerId: "user-1"});
|
|
3414
|
-
|
|
3415
|
-
// Wait for the change stream event to be processed
|
|
3416
|
-
await new Promise((resolve) => setTimeout(resolve, 1500));
|
|
3417
|
-
|
|
3418
|
-
const createEmissions = io.emissions.filter(
|
|
3419
|
-
(e) => e.event === "sync" && e.payload.method === "create"
|
|
3420
|
-
);
|
|
3421
|
-
expect(createEmissions.length).toBeGreaterThanOrEqual(1);
|
|
3422
|
-
await stopChangeStreamWatcher();
|
|
3423
|
-
});
|
|
3424
|
-
|
|
3425
|
-
it("processes update events from MongoDB change stream", async () => {
|
|
3426
|
-
if (!replicaSetAvailable) {
|
|
3427
|
-
return;
|
|
3428
|
-
}
|
|
3429
|
-
registerRealtime({
|
|
3430
|
-
collectionName: "realtimetests",
|
|
3431
|
-
config: {methods: ["create", "update", "delete"], roomStrategy: "model"},
|
|
3432
|
-
modelName: "RealtimeTest",
|
|
3433
|
-
options: {
|
|
3434
|
-
permissions: {
|
|
3435
|
-
create: [() => true],
|
|
3436
|
-
delete: [() => true],
|
|
3437
|
-
list: [() => true],
|
|
3438
|
-
read: [() => true],
|
|
3439
|
-
update: [() => true],
|
|
3440
|
-
},
|
|
3441
|
-
},
|
|
3442
|
-
routePath: "/realtimetests",
|
|
3443
|
-
});
|
|
3444
|
-
|
|
3445
|
-
const doc = await RealtimeTestModel.create({name: "item-to-update", ownerId: "user-1"});
|
|
3446
|
-
|
|
3447
|
-
const io = makeTrackedIo();
|
|
3448
|
-
io.addSocketToRoom("model:realtimetests");
|
|
3449
|
-
startChangeStreamWatcher(io, {}, true);
|
|
3450
|
-
|
|
3451
|
-
await RealtimeTestModel.updateOne({_id: doc._id}, {$set: {name: "updated-item"}});
|
|
3452
|
-
|
|
3453
|
-
await new Promise((resolve) => setTimeout(resolve, 1500));
|
|
3454
|
-
|
|
3455
|
-
const updateEmissions = io.emissions.filter(
|
|
3456
|
-
(e) => e.event === "sync" && e.payload?.method === "update"
|
|
3457
|
-
);
|
|
3458
|
-
expect(updateEmissions.length).toBeGreaterThanOrEqual(1);
|
|
3459
|
-
await stopChangeStreamWatcher();
|
|
3460
|
-
});
|
|
3461
|
-
|
|
3462
|
-
it("processes hard delete events from MongoDB change stream", async () => {
|
|
3463
|
-
if (!replicaSetAvailable) {
|
|
3464
|
-
return;
|
|
3465
|
-
}
|
|
3466
|
-
registerRealtime({
|
|
3467
|
-
collectionName: "realtimetests",
|
|
3468
|
-
config: {methods: ["create", "update", "delete"], roomStrategy: "model"},
|
|
3469
|
-
modelName: "RealtimeTest",
|
|
3470
|
-
options: {
|
|
3471
|
-
permissions: {
|
|
3472
|
-
create: [() => true],
|
|
3473
|
-
delete: [() => true],
|
|
3474
|
-
list: [() => true],
|
|
3475
|
-
read: [() => true],
|
|
3476
|
-
update: [() => true],
|
|
3477
|
-
},
|
|
3478
|
-
},
|
|
3479
|
-
routePath: "/realtimetests",
|
|
3480
|
-
});
|
|
3481
|
-
|
|
3482
|
-
const doc = await RealtimeTestModel.create({name: "item-to-delete"});
|
|
3483
|
-
|
|
3484
|
-
const io = makeTrackedIo();
|
|
3485
|
-
io.addSocketToRoom("model:realtimetests");
|
|
3486
|
-
startChangeStreamWatcher(io, {}, true);
|
|
3487
|
-
|
|
3488
|
-
await RealtimeTestModel.deleteOne({_id: doc._id});
|
|
3489
|
-
|
|
3490
|
-
await new Promise((resolve) => setTimeout(resolve, 1500));
|
|
3491
|
-
|
|
3492
|
-
const deleteEmissions = io.emissions.filter(
|
|
3493
|
-
(e) => e.event === "sync" && e.payload?.method === "delete"
|
|
3494
|
-
);
|
|
3495
|
-
expect(deleteEmissions.length).toBeGreaterThanOrEqual(1);
|
|
3496
|
-
await stopChangeStreamWatcher();
|
|
3497
|
-
});
|
|
3498
|
-
|
|
3499
|
-
it("processes soft delete events from MongoDB change stream", async () => {
|
|
3500
|
-
if (!replicaSetAvailable) {
|
|
3501
|
-
return;
|
|
3502
|
-
}
|
|
3503
|
-
registerRealtime({
|
|
3504
|
-
collectionName: "realtimetests",
|
|
3505
|
-
config: {methods: ["create", "update", "delete"], roomStrategy: "model"},
|
|
3506
|
-
modelName: "RealtimeTest",
|
|
3507
|
-
options: {
|
|
3508
|
-
permissions: {
|
|
3509
|
-
create: [() => true],
|
|
3510
|
-
delete: [() => true],
|
|
3511
|
-
list: [() => true],
|
|
3512
|
-
read: [() => true],
|
|
3513
|
-
update: [() => true],
|
|
3514
|
-
},
|
|
3515
|
-
},
|
|
3516
|
-
routePath: "/realtimetests",
|
|
3517
|
-
});
|
|
3518
|
-
|
|
3519
|
-
const doc = await RealtimeTestModel.create({name: "item-to-soft-delete"});
|
|
3520
|
-
|
|
3521
|
-
const io = makeTrackedIo();
|
|
3522
|
-
io.addSocketToRoom("model:realtimetests");
|
|
3523
|
-
startChangeStreamWatcher(io, {}, true);
|
|
3524
|
-
|
|
3525
|
-
await RealtimeTestModel.updateOne({_id: doc._id}, {$set: {deleted: true}});
|
|
3526
|
-
|
|
3527
|
-
await new Promise((resolve) => setTimeout(resolve, 1500));
|
|
3528
|
-
|
|
3529
|
-
const deleteEmissions = io.emissions.filter(
|
|
3530
|
-
(e) => e.event === "sync" && e.payload?.method === "delete"
|
|
3531
|
-
);
|
|
3532
|
-
expect(deleteEmissions.length).toBeGreaterThanOrEqual(1);
|
|
3533
|
-
await stopChangeStreamWatcher();
|
|
3534
|
-
});
|
|
3535
|
-
|
|
3536
|
-
it("includes updatedFields and emits to document rooms", async () => {
|
|
3537
|
-
if (!replicaSetAvailable) {
|
|
3538
|
-
return;
|
|
3539
|
-
}
|
|
3540
|
-
registerRealtime({
|
|
3541
|
-
collectionName: "realtimetests",
|
|
3542
|
-
config: {methods: ["create", "update", "delete"], roomStrategy: "model"},
|
|
3543
|
-
modelName: "RealtimeTest",
|
|
3544
|
-
options: {
|
|
3545
|
-
permissions: {
|
|
3546
|
-
create: [() => true],
|
|
3547
|
-
delete: [() => true],
|
|
3548
|
-
list: [() => true],
|
|
3549
|
-
read: [() => true],
|
|
3550
|
-
update: [() => true],
|
|
3551
|
-
},
|
|
3552
|
-
},
|
|
3553
|
-
routePath: "/realtimetests",
|
|
3554
|
-
});
|
|
3555
|
-
|
|
3556
|
-
const doc = await RealtimeTestModel.create({name: "fields-test"});
|
|
3557
|
-
const docId = doc._id.toString();
|
|
3558
|
-
|
|
3559
|
-
const io = makeTrackedIo();
|
|
3560
|
-
io.addSocketToRoom("model:realtimetests");
|
|
3561
|
-
io.addSocketToRoom(`document:realtimetests:${docId}`);
|
|
3562
|
-
startChangeStreamWatcher(io, {}, true);
|
|
3563
|
-
|
|
3564
|
-
await RealtimeTestModel.updateOne({_id: doc._id}, {$set: {name: "fields-updated"}});
|
|
3565
|
-
|
|
3566
|
-
await new Promise((resolve) => setTimeout(resolve, 1500));
|
|
3567
|
-
|
|
3568
|
-
const updateEmissions = io.emissions.filter(
|
|
3569
|
-
(e) => e.event === "sync" && e.payload?.method === "update"
|
|
3570
|
-
);
|
|
3571
|
-
expect(updateEmissions.length).toBeGreaterThanOrEqual(1);
|
|
3572
|
-
if (updateEmissions.length > 0) {
|
|
3573
|
-
expect(updateEmissions[0].payload.updatedFields).toBeDefined();
|
|
3574
|
-
expect(updateEmissions[0].payload.updatedFields).toContain("name");
|
|
3575
|
-
}
|
|
3576
|
-
await stopChangeStreamWatcher();
|
|
3577
|
-
});
|
|
3578
|
-
});
|
|
3579
|
-
|
|
3580
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
3581
|
-
// emitToDocumentAndQueryRooms — no-entry path
|
|
3582
|
-
// ─────────────────────────────────────────────────────────────────────────────
|
|
3583
|
-
|
|
3584
|
-
describe("emitToDocumentAndQueryRooms — no registry entry", () => {
|
|
3585
|
-
const makeIoSimple = (): Server & {
|
|
3586
|
-
emissions: Array<{room: string; event: string; payload: unknown}>;
|
|
3587
|
-
} => {
|
|
3588
|
-
const emissions: Array<{room: string; event: string; payload: unknown}> = [];
|
|
3589
|
-
return {
|
|
3590
|
-
emissions,
|
|
3591
|
-
sockets: {
|
|
3592
|
-
adapter: {rooms: new Map<string, Set<string>>()},
|
|
3593
|
-
sockets: new Map<string, MockRoomSocket>(),
|
|
3594
|
-
},
|
|
3595
|
-
to: (room: string) => ({
|
|
3596
|
-
emit: (event: string, payload: unknown): void => {
|
|
3597
|
-
emissions.push({event, payload, room});
|
|
3598
|
-
},
|
|
3599
|
-
}),
|
|
3600
|
-
} as unknown as Server & {
|
|
3601
|
-
emissions: Array<{room: string; event: string; payload: unknown}>;
|
|
3602
|
-
};
|
|
3603
|
-
};
|
|
3604
|
-
|
|
3605
|
-
beforeEach(() => {
|
|
3606
|
-
clearQueryStore();
|
|
3607
|
-
});
|
|
3608
|
-
|
|
3609
|
-
afterEach(() => {
|
|
3610
|
-
clearQueryStore();
|
|
3611
|
-
});
|
|
3612
|
-
|
|
3613
|
-
it("emits to document room via io.to when no entry is provided", async () => {
|
|
3614
|
-
const io = makeIoSimple();
|
|
3615
|
-
const event: RealtimeEvent = {
|
|
3616
|
-
collection: "items",
|
|
3617
|
-
id: "doc-1",
|
|
3618
|
-
method: "update",
|
|
3619
|
-
model: "Item",
|
|
3620
|
-
timestamp: 1,
|
|
3621
|
-
};
|
|
3622
|
-
await emitToDocumentAndQueryRooms(io, "items", event, {}, () => {});
|
|
3623
|
-
expect(io.emissions.some((e) => e.room === "document:items:doc-1")).toBe(true);
|
|
3624
|
-
});
|
|
3625
|
-
|
|
3626
|
-
it("emits hard deletes to query rooms via io.to when no entry", async () => {
|
|
3627
|
-
const queryId = computeQueryId("items", {status: "active"});
|
|
3628
|
-
addQuerySubscription("socket-a", "items", {status: "active"}, queryId);
|
|
3629
|
-
const io = makeIoSimple();
|
|
3630
|
-
const event: RealtimeEvent = {
|
|
3631
|
-
collection: "items",
|
|
3632
|
-
id: "doc-1",
|
|
3633
|
-
method: "delete",
|
|
3634
|
-
model: "Item",
|
|
3635
|
-
timestamp: 1,
|
|
3636
|
-
};
|
|
3637
|
-
await emitToDocumentAndQueryRooms(io, "items", event, undefined, () => {});
|
|
3638
|
-
expect(io.emissions.some((e) => e.room === `query:${queryId}`)).toBe(true);
|
|
3639
|
-
});
|
|
3640
|
-
|
|
3641
|
-
it("emits soft delete to query rooms via io.to when no entry and doc matches", async () => {
|
|
3642
|
-
const queryId = computeQueryId("items", {status: "active"});
|
|
3643
|
-
addQuerySubscription("socket-a", "items", {status: "active"}, queryId);
|
|
3644
|
-
const io = makeIoSimple();
|
|
3645
|
-
const event: RealtimeEvent = {
|
|
3646
|
-
collection: "items",
|
|
3647
|
-
id: "doc-1",
|
|
3648
|
-
method: "delete",
|
|
3649
|
-
model: "Item",
|
|
3650
|
-
timestamp: 1,
|
|
3651
|
-
};
|
|
3652
|
-
await emitToDocumentAndQueryRooms(io, "items", event, {status: "active"}, () => {});
|
|
3653
|
-
expect(io.emissions.some((e) => e.room === `query:${queryId}`)).toBe(true);
|
|
3654
|
-
});
|
|
3655
|
-
|
|
3656
|
-
it("emits create events to query rooms via io.to when no entry and doc matches", async () => {
|
|
3657
|
-
const queryId = computeQueryId("items", {status: "active"});
|
|
3658
|
-
addQuerySubscription("socket-a", "items", {status: "active"}, queryId);
|
|
3659
|
-
const io = makeIoSimple();
|
|
3660
|
-
const event: RealtimeEvent = {
|
|
3661
|
-
collection: "items",
|
|
3662
|
-
id: "doc-1",
|
|
3663
|
-
method: "create",
|
|
3664
|
-
model: "Item",
|
|
3665
|
-
timestamp: 1,
|
|
3666
|
-
};
|
|
3667
|
-
await emitToDocumentAndQueryRooms(io, "items", event, {status: "active"}, () => {});
|
|
3668
|
-
expect(io.emissions.some((e) => e.room === `query:${queryId}`)).toBe(true);
|
|
3669
|
-
});
|
|
3670
|
-
|
|
3671
|
-
it("emits update events to query rooms via io.to when no entry and doc matches", async () => {
|
|
3672
|
-
const queryId = computeQueryId("items", {status: "active"});
|
|
3673
|
-
addQuerySubscription("socket-a", "items", {status: "active"}, queryId);
|
|
3674
|
-
const io = makeIoSimple();
|
|
3675
|
-
const event: RealtimeEvent = {
|
|
3676
|
-
collection: "items",
|
|
3677
|
-
id: "doc-1",
|
|
3678
|
-
method: "update",
|
|
3679
|
-
model: "Item",
|
|
3680
|
-
timestamp: 1,
|
|
3681
|
-
};
|
|
3682
|
-
await emitToDocumentAndQueryRooms(io, "items", event, {status: "active"}, () => {});
|
|
3683
|
-
expect(io.emissions.some((e) => e.room === `query:${queryId}`)).toBe(true);
|
|
3684
|
-
});
|
|
3685
|
-
|
|
3686
|
-
it("emits delete to query rooms via io.to when update no longer matches and no entry", async () => {
|
|
3687
|
-
const queryId = computeQueryId("items", {status: "active"});
|
|
3688
|
-
addQuerySubscription("socket-a", "items", {status: "active"}, queryId);
|
|
3689
|
-
const io = makeIoSimple();
|
|
3690
|
-
const event: RealtimeEvent = {
|
|
3691
|
-
collection: "items",
|
|
3692
|
-
id: "doc-1",
|
|
3693
|
-
method: "update",
|
|
3694
|
-
model: "Item",
|
|
3695
|
-
timestamp: 1,
|
|
3696
|
-
};
|
|
3697
|
-
await emitToDocumentAndQueryRooms(io, "items", event, {status: "inactive"}, () => {});
|
|
3698
|
-
const queryEmissions = io.emissions.filter((e) => e.room === `query:${queryId}`);
|
|
3699
|
-
expect(queryEmissions.length).toBe(1);
|
|
3700
|
-
expect(queryEmissions[0].payload).toMatchObject({method: "delete"});
|
|
3701
|
-
});
|
|
3702
|
-
});
|
|
3703
|
-
|
|
3704
1369
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
3705
1370
|
// RealtimeApp — onServerCreated, setupAdapter, close
|
|
3706
1371
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
@@ -3717,7 +1382,6 @@ describe("RealtimeApp — onServerCreated and setupAdapter", () => {
|
|
|
3717
1382
|
|
|
3718
1383
|
afterEach(async () => {
|
|
3719
1384
|
process.env = originalEnv;
|
|
3720
|
-
clearRealtimeRegistry();
|
|
3721
1385
|
});
|
|
3722
1386
|
|
|
3723
1387
|
it("register adds /realtime/health endpoint with debug flag", async () => {
|