@terreno/api 0.31.0 → 56.0.0-beta.0
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 +122 -2
- package/LICENSE +202 -21
- package/dist/api.d.ts +12 -3
- package/dist/api.js +110 -361
- package/dist/auth.d.ts +26 -0
- package/dist/auth.js +100 -1
- package/dist/betterAuth.d.ts +5 -0
- package/dist/betterAuthSetup.d.ts +1 -15
- package/dist/betterAuthSetup.js +29 -8
- package/dist/configurationPlugin.js +2 -2
- package/dist/docLoader.js +12 -9
- package/dist/errors.d.ts +13 -0
- package/dist/errors.js +29 -1
- package/dist/expressServer.js +5 -11
- package/dist/githubAuth.js +4 -1
- package/dist/index.d.ts +17 -1
- package/dist/index.js +29 -1
- package/dist/middleware.d.ts +7 -0
- package/dist/middleware.js +16 -1
- package/dist/openApiCompat.d.ts +10 -1
- package/dist/openApiCompat.js +115 -47
- package/dist/permissions.d.ts +27 -0
- package/dist/permissions.js +42 -1
- package/dist/plugins.d.ts +15 -3
- package/dist/plugins.js +36 -6
- package/dist/realtime/changeStreamWatcher.d.ts +100 -3
- package/dist/realtime/changeStreamWatcher.js +542 -137
- package/dist/realtime/realtimeApp.d.ts +3 -1
- package/dist/realtime/realtimeApp.js +75 -27
- package/dist/realtime/sessionRevalidation.d.ts +90 -0
- package/dist/realtime/sessionRevalidation.js +438 -0
- package/dist/realtime/socketAuth.d.ts +97 -0
- package/dist/realtime/socketAuth.js +272 -0
- package/dist/realtime/socketUser.d.ts +54 -0
- package/dist/realtime/socketUser.js +75 -5
- package/dist/realtime/types.d.ts +40 -0
- package/dist/secretProviders.d.ts +23 -0
- package/dist/secretProviders.js +9 -3
- package/dist/sync/executors.d.ts +198 -0
- package/dist/sync/executors.js +670 -0
- package/dist/sync/loadHarness.js +807 -0
- package/dist/sync/models.d.ts +216 -0
- package/dist/sync/models.js +644 -0
- package/dist/sync/mutationHandler.d.ts +97 -0
- package/dist/sync/mutationHandler.js +886 -0
- package/dist/sync/registry.d.ts +73 -0
- package/dist/sync/registry.js +223 -0
- package/dist/sync/routes.d.ts +62 -0
- package/dist/sync/routes.js +936 -0
- package/dist/sync/scripts/compactTombstones.d.ts +47 -0
- package/dist/sync/scripts/compactTombstones.js +270 -0
- package/dist/sync/serialize.d.ts +20 -0
- package/dist/{tests/bunSetup.js → sync/serialize.js} +35 -68
- package/dist/sync/socketHandlers.d.ts +54 -0
- package/dist/sync/socketHandlers.js +470 -0
- package/dist/sync/streams.d.ts +85 -0
- package/dist/sync/streams.js +221 -0
- package/dist/sync/syncApp.d.ts +29 -0
- package/dist/sync/syncApp.js +44 -0
- package/dist/sync/syncBatch.d.ts +71 -0
- package/dist/sync/syncBatch.js +252 -0
- package/dist/sync/syncSeqPlugin.d.ts +8 -0
- package/dist/sync/syncSeqPlugin.js +903 -0
- package/dist/sync/types.d.ts +254 -0
- package/dist/sync/types.js +9 -0
- package/dist/terrenoApp.js +90 -27
- package/dist/tests/models.d.ts +11 -27
- package/dist/tests/models.js +3 -5
- package/dist/tests/testHelper.d.ts +3 -9
- package/dist/vendor/wesleytodd-openapi/index.d.ts +1 -1
- package/dist/vendor/wesleytodd-openapi/lib/ui.d.ts +2 -1
- package/package.json +10 -8
- package/src/__tests__/openApiCompat.test.ts +20 -0
- package/src/actions.test.ts +12 -19
- package/src/actions.ts +2 -2
- package/src/api.coverage.test.ts +9 -7
- package/src/api.errorPaths.test.ts +1 -47
- package/src/api.test.ts +12 -0
- package/src/api.ts +98 -317
- package/src/auth.test.ts +128 -176
- package/src/auth.ts +109 -0
- package/src/betterAuth.ts +6 -0
- package/src/betterAuthSetup.test.ts +34 -0
- package/src/betterAuthSetup.ts +27 -8
- package/src/configurationPlugin.ts +2 -2
- package/src/consentApp.test.ts +12 -12
- package/src/docLoader.ts +3 -1
- package/src/errors.ts +33 -0
- package/src/expressServer.test.ts +7 -1
- package/src/expressServer.ts +5 -11
- package/src/githubAuth.ts +3 -1
- package/src/index.ts +42 -0
- package/src/middleware.test.ts +40 -1
- package/src/middleware.ts +15 -0
- package/src/models/versionConfig.ts +1 -1
- package/src/openApiBuilder.test.ts +9 -24
- package/src/openApiCompat.ts +99 -45
- package/src/openApiValidator.test.ts +0 -41
- package/src/permissions.test.ts +75 -1
- package/src/permissions.ts +49 -0
- package/src/plugins.test.ts +54 -14
- package/src/plugins.ts +47 -9
- package/src/populate.test.ts +16 -25
- package/src/realtime/changeStreamWatcher.ts +552 -114
- package/src/realtime/realtime.test.ts +157 -239
- package/src/realtime/realtimeApp.ts +80 -19
- package/src/realtime/sessionRevalidation.test.ts +423 -0
- package/src/realtime/sessionRevalidation.ts +273 -0
- package/src/realtime/socketAuth.test.ts +355 -0
- package/src/realtime/socketAuth.ts +228 -0
- package/src/realtime/socketUser.ts +69 -0
- package/src/realtime/types.ts +40 -0
- package/src/secretProviders.test.ts +7 -1
- package/src/secretProviders.ts +15 -3
- package/src/sync/ensureSyncIndexes.test.ts +144 -0
- package/src/sync/executors.test.ts +882 -0
- package/src/sync/executors.ts +703 -0
- package/src/sync/integration.test.ts +1160 -0
- package/src/sync/loadHarness.ts +618 -0
- package/src/sync/models.ts +640 -0
- package/src/sync/mutationHandler.test.ts +1252 -0
- package/src/sync/mutationHandler.ts +850 -0
- package/src/sync/registry.ts +232 -0
- package/src/sync/routes.ts +812 -0
- package/src/sync/scripts/compactTombstones.test.ts +249 -0
- package/src/sync/scripts/compactTombstones.ts +145 -0
- package/src/sync/serialize.ts +48 -0
- package/src/sync/sessionRevalidationIntegration.test.ts +281 -0
- package/src/sync/socketHandlers.ts +320 -0
- package/src/sync/streams.ts +188 -0
- package/src/sync/sync.test.ts +582 -0
- package/src/sync/syncApp.ts +44 -0
- package/src/sync/syncBatch.ts +219 -0
- package/src/sync/syncFrontier.test.ts +494 -0
- package/src/sync/syncPhaseC.test.ts +718 -0
- package/src/sync/syncRoutes.test.ts +865 -0
- package/src/sync/syncSeqPlugin.ts +738 -0
- package/src/sync/syncSocket.test.ts +1440 -0
- package/src/sync/types.ts +270 -0
- package/src/terrenoApp.ts +37 -17
- package/src/tests/bunSetup.ts +8 -0
- package/src/tests/models.ts +6 -8
- package/tsconfig.json +4 -4
- package/tsconfig.typedoc.json +7 -1
- package/dist/__tests__/openApiCompat.test.js +0 -317
- package/dist/__tests__/versionCheckPlugin.test.d.ts +0 -1
- package/dist/__tests__/versionCheckPlugin.test.js +0 -597
- package/dist/actions.openApi.test.d.ts +0 -1
- package/dist/actions.openApi.test.js +0 -253
- package/dist/actions.test.d.ts +0 -1
- package/dist/actions.test.js +0 -1087
- package/dist/api.arrayOperations.test.d.ts +0 -1
- package/dist/api.arrayOperations.test.js +0 -878
- package/dist/api.asyncHandler.test.d.ts +0 -1
- package/dist/api.asyncHandler.test.js +0 -236
- package/dist/api.coverage.test.d.ts +0 -1
- package/dist/api.coverage.test.js +0 -192
- package/dist/api.errorPaths.test.d.ts +0 -1
- package/dist/api.errorPaths.test.js +0 -887
- package/dist/api.errors.test.d.ts +0 -1
- package/dist/api.errors.test.js +0 -185
- package/dist/api.hooks.test.d.ts +0 -1
- package/dist/api.hooks.test.js +0 -950
- package/dist/api.query.test.d.ts +0 -1
- package/dist/api.query.test.js +0 -948
- package/dist/api.test.d.ts +0 -1
- package/dist/api.test.js +0 -2820
- package/dist/auth.compile.test.d.ts +0 -1
- package/dist/auth.compile.test.js +0 -201
- package/dist/auth.coverage.test.d.ts +0 -1
- package/dist/auth.coverage.test.js +0 -202
- package/dist/auth.test.d.ts +0 -1
- package/dist/auth.test.js +0 -2286
- package/dist/betterAuth.test.d.ts +0 -1
- package/dist/betterAuth.test.js +0 -181
- package/dist/betterAuthApp.test.d.ts +0 -1
- package/dist/betterAuthApp.test.js +0 -242
- package/dist/betterAuthSetup.test.d.ts +0 -1
- package/dist/betterAuthSetup.test.js +0 -762
- package/dist/config.test.d.ts +0 -1
- package/dist/config.test.js +0 -353
- package/dist/configuration.test.d.ts +0 -1
- package/dist/configuration.test.js +0 -980
- package/dist/configurationPlugin.test.d.ts +0 -1
- package/dist/configurationPlugin.test.js +0 -827
- package/dist/consentApp.test.d.ts +0 -1
- package/dist/consentApp.test.js +0 -1411
- package/dist/docLoader.test.d.ts +0 -1
- package/dist/docLoader.test.js +0 -137
- package/dist/envConfigurationPlugin.test.d.ts +0 -1
- package/dist/envConfigurationPlugin.test.js +0 -369
- package/dist/errors.test.d.ts +0 -1
- package/dist/errors.test.js +0 -607
- package/dist/expressServer.test.d.ts +0 -1
- package/dist/expressServer.test.js +0 -1249
- package/dist/githubAuth.test.d.ts +0 -1
- package/dist/githubAuth.test.js +0 -1142
- package/dist/httpClient.test.d.ts +0 -1
- package/dist/httpClient.test.js +0 -1471
- package/dist/logger.test.d.ts +0 -1
- package/dist/logger.test.js +0 -685
- package/dist/middleware.test.d.ts +0 -1
- package/dist/middleware.test.js +0 -241
- package/dist/notifiers/googleChatNotifier.test.d.ts +0 -1
- package/dist/notifiers/googleChatNotifier.test.js +0 -298
- package/dist/notifiers/slackNotifier.test.d.ts +0 -1
- package/dist/notifiers/slackNotifier.test.js +0 -297
- package/dist/notifiers/zoomNotifier.test.d.ts +0 -1
- package/dist/notifiers/zoomNotifier.test.js +0 -373
- package/dist/openApi.test.d.ts +0 -1
- package/dist/openApi.test.js +0 -620
- package/dist/openApiBuilder.test.d.ts +0 -1
- package/dist/openApiBuilder.test.js +0 -599
- package/dist/openApiEtag.test.d.ts +0 -1
- package/dist/openApiEtag.test.js +0 -86
- package/dist/openApiValidator.test.d.ts +0 -1
- package/dist/openApiValidator.test.js +0 -795
- package/dist/permissions.middleware.test.d.ts +0 -1
- package/dist/permissions.middleware.test.js +0 -308
- package/dist/permissions.test.d.ts +0 -1
- package/dist/permissions.test.js +0 -439
- package/dist/plugins.test.d.ts +0 -1
- package/dist/plugins.test.js +0 -902
- package/dist/populate.test.d.ts +0 -1
- package/dist/populate.test.js +0 -370
- package/dist/realtime/realtime.test.d.ts +0 -10
- package/dist/realtime/realtime.test.js +0 -4213
- package/dist/realtime/realtimeAppSetup.test.d.ts +0 -1
- package/dist/realtime/realtimeAppSetup.test.js +0 -213
- package/dist/requestContext.test.d.ts +0 -1
- package/dist/requestContext.test.js +0 -412
- package/dist/scriptRunner.test.d.ts +0 -1
- package/dist/scriptRunner.test.js +0 -386
- package/dist/secretProviders.test.d.ts +0 -1
- package/dist/secretProviders.test.js +0 -726
- package/dist/syncConsents.test.d.ts +0 -1
- package/dist/syncConsents.test.js +0 -522
- package/dist/terrenoApp.test.d.ts +0 -1
- package/dist/terrenoApp.test.js +0 -489
- package/dist/tests/bunSetup.d.ts +0 -1
- package/dist/tests/fixtures/compileAuthEntry.d.ts +0 -1
- package/dist/tests/fixtures/compileAuthEntry.js +0 -37
- package/dist/tests/testEnv.d.ts +0 -0
- package/dist/tests/testEnv.js +0 -6
- package/dist/transformers.test.d.ts +0 -1
- package/dist/transformers.test.js +0 -423
- package/dist/utils.test.d.ts +0 -1
- package/dist/utils.test.js +0 -242
- package/src/realtime/realtimeAppSetup.test.ts +0 -161
- /package/dist/{__tests__/openApiCompat.test.d.ts → sync/loadHarness.d.ts} +0 -0
|
@@ -0,0 +1,1440 @@
|
|
|
1
|
+
// noExplicitAny: test mocks use dynamic shapes for sockets, io, and documents
|
|
2
|
+
// biome-ignore-all lint/suspicious/noExplicitAny: test mocks use dynamic shapes for sockets, io, and documents
|
|
3
|
+
/**
|
|
4
|
+
* Tests for the sync socket layer (Tasks 2.3–2.5):
|
|
5
|
+
* - socketHandlers.ts (sync:subscribe / sync:unsubscribe / sync:mutate, caps, rate limit)
|
|
6
|
+
* - changeStreamWatcher.ts sync:delta emission (mock change streams + real change
|
|
7
|
+
* streams gated on replica-set availability, following realtime.test.ts conventions)
|
|
8
|
+
*
|
|
9
|
+
* socketAuth.ts (legacy JWT validator chain + Better Auth session validator) has its own
|
|
10
|
+
* dedicated test file: realtime/socketAuth.test.ts.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import {afterEach, beforeAll, beforeEach, describe, expect, it} from "bun:test";
|
|
14
|
+
import mongoose, {model, Schema} from "mongoose";
|
|
15
|
+
|
|
16
|
+
import type {ModelRouterOptions} from "../api";
|
|
17
|
+
import {createdUpdatedPlugin, type IsDeleted, isDeletedPlugin} from "../plugins";
|
|
18
|
+
import {
|
|
19
|
+
emitSyncDeltaForChange,
|
|
20
|
+
startChangeStreamWatcher,
|
|
21
|
+
stopChangeStreamWatcher,
|
|
22
|
+
} from "../realtime/changeStreamWatcher";
|
|
23
|
+
import {clearRealtimeRegistry, registerRealtime} from "../realtime/registry";
|
|
24
|
+
import {setupDb} from "../tests";
|
|
25
|
+
import {SyncCounter, SyncMutation, SyncScopeMove} from "./models";
|
|
26
|
+
import {MAX_SYNC_MUTATIONS_PER_BATCH} from "./mutationHandler";
|
|
27
|
+
import {
|
|
28
|
+
clearSyncRegistry,
|
|
29
|
+
findSyncEntryByCollectionTag,
|
|
30
|
+
registerSync,
|
|
31
|
+
type SyncRegistryEntry,
|
|
32
|
+
} from "./registry";
|
|
33
|
+
import type {SyncAppOptions} from "./routes";
|
|
34
|
+
import {
|
|
35
|
+
installSyncSocketHandlers,
|
|
36
|
+
MAX_SYNC_COLLECTION_SUBSCRIPTIONS,
|
|
37
|
+
MAX_SYNC_SUBSCRIBE_ARRAY_LENGTH,
|
|
38
|
+
type SyncSocketLike,
|
|
39
|
+
syncRoomForStream,
|
|
40
|
+
} from "./socketHandlers";
|
|
41
|
+
import {getSyncAppOptions, SyncApp} from "./syncApp";
|
|
42
|
+
import {
|
|
43
|
+
evictExpiredSyncMutationWindows,
|
|
44
|
+
MAX_SYNC_MUTATIONS_PER_SECOND,
|
|
45
|
+
resetSyncMutationRateLimits,
|
|
46
|
+
syncMutationRateLimitWindowCount,
|
|
47
|
+
} from "./syncBatch";
|
|
48
|
+
import {syncPlugin} from "./syncSeqPlugin";
|
|
49
|
+
import type {SyncAck, SyncDelta, SyncNack} from "./types";
|
|
50
|
+
|
|
51
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
52
|
+
// Test models
|
|
53
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
54
|
+
|
|
55
|
+
interface SockStuff extends IsDeleted {
|
|
56
|
+
_id: string;
|
|
57
|
+
name: string;
|
|
58
|
+
ownerId: string;
|
|
59
|
+
created: Date;
|
|
60
|
+
_syncSeq?: number;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const sockStuffSchema = new Schema<SockStuff>({
|
|
64
|
+
name: {description: "The name of the item", required: true, type: String},
|
|
65
|
+
ownerId: {description: "The user who owns this item", type: String},
|
|
66
|
+
});
|
|
67
|
+
sockStuffSchema.plugin(isDeletedPlugin);
|
|
68
|
+
sockStuffSchema.plugin(createdUpdatedPlugin);
|
|
69
|
+
sockStuffSchema.plugin(syncPlugin);
|
|
70
|
+
const SockStuffModel = model<SockStuff>("SockStuff", sockStuffSchema);
|
|
71
|
+
|
|
72
|
+
interface SockProject extends IsDeleted {
|
|
73
|
+
_id: string;
|
|
74
|
+
title: string;
|
|
75
|
+
orgId: string;
|
|
76
|
+
_syncSeq?: number;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const sockProjectSchema = new Schema<SockProject>({
|
|
80
|
+
orgId: {description: "The organization this project belongs to", type: String},
|
|
81
|
+
title: {description: "The project title", required: true, type: String},
|
|
82
|
+
});
|
|
83
|
+
sockProjectSchema.plugin(isDeletedPlugin);
|
|
84
|
+
sockProjectSchema.plugin(createdUpdatedPlugin);
|
|
85
|
+
sockProjectSchema.plugin(syncPlugin);
|
|
86
|
+
const SockProjectModel = model<SockProject>("SockProject", sockProjectSchema);
|
|
87
|
+
|
|
88
|
+
interface SockNews extends IsDeleted {
|
|
89
|
+
_id: string;
|
|
90
|
+
headline: string;
|
|
91
|
+
_syncSeq?: number;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const sockNewsSchema = new Schema<SockNews>({
|
|
95
|
+
headline: {description: "The news headline", required: true, type: String},
|
|
96
|
+
});
|
|
97
|
+
sockNewsSchema.plugin(isDeletedPlugin);
|
|
98
|
+
sockNewsSchema.plugin(createdUpdatedPlugin);
|
|
99
|
+
sockNewsSchema.plugin(syncPlugin);
|
|
100
|
+
const SockNewsModel = model<SockNews>("SockNews", sockNewsSchema);
|
|
101
|
+
|
|
102
|
+
const permissiveOptions = {
|
|
103
|
+
permissions: {
|
|
104
|
+
create: [() => true],
|
|
105
|
+
delete: [() => true],
|
|
106
|
+
list: [() => true],
|
|
107
|
+
read: [() => true],
|
|
108
|
+
update: [() => true],
|
|
109
|
+
},
|
|
110
|
+
} as unknown as ModelRouterOptions<any>;
|
|
111
|
+
|
|
112
|
+
const adminOnlyOptions = {
|
|
113
|
+
permissions: {
|
|
114
|
+
create: [(_m: string, user?: {admin?: boolean}) => user?.admin === true],
|
|
115
|
+
delete: [(_m: string, user?: {admin?: boolean}) => user?.admin === true],
|
|
116
|
+
list: [(_m: string, user?: {admin?: boolean}) => user?.admin === true],
|
|
117
|
+
read: [(_m: string, user?: {admin?: boolean}) => user?.admin === true],
|
|
118
|
+
update: [(_m: string, user?: {admin?: boolean}) => user?.admin === true],
|
|
119
|
+
},
|
|
120
|
+
} as unknown as ModelRouterOptions<any>;
|
|
121
|
+
|
|
122
|
+
const ownerReadOptions = {
|
|
123
|
+
permissions: {
|
|
124
|
+
create: [() => true],
|
|
125
|
+
delete: [() => true],
|
|
126
|
+
list: [() => true],
|
|
127
|
+
read: [
|
|
128
|
+
(_m: string, user?: {admin?: boolean; id?: string}, obj?: {ownerId?: unknown}) =>
|
|
129
|
+
user?.admin === true || (obj?.ownerId != null && String(obj.ownerId) === user?.id),
|
|
130
|
+
],
|
|
131
|
+
update: [() => true],
|
|
132
|
+
},
|
|
133
|
+
} as unknown as ModelRouterOptions<any>;
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* A minimal fake Mongoose model satisfying registerSync's schema/collection checks, for
|
|
137
|
+
* tests that need many registrations (each real registration requires a distinct
|
|
138
|
+
* compiled model).
|
|
139
|
+
*/
|
|
140
|
+
const makeFakeSyncModel = (name: string): any => ({
|
|
141
|
+
collection: {
|
|
142
|
+
collectionName: name.toLowerCase(),
|
|
143
|
+
createIndex: async () => {},
|
|
144
|
+
},
|
|
145
|
+
modelName: name,
|
|
146
|
+
schema: {
|
|
147
|
+
path: (p: string) => {
|
|
148
|
+
if (p === "deleted") {
|
|
149
|
+
return {instance: "Boolean"};
|
|
150
|
+
}
|
|
151
|
+
if (p === "_syncSeq") {
|
|
152
|
+
return {instance: "Number"};
|
|
153
|
+
}
|
|
154
|
+
return undefined;
|
|
155
|
+
},
|
|
156
|
+
},
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
// The shared test database can be dropped by another test file mid-suite
|
|
160
|
+
// (configurationPlugin.test.ts drops it in an afterAll); rebuild the unique indexes the
|
|
161
|
+
// duplicate-mutation tests depend on.
|
|
162
|
+
beforeAll(async () => {
|
|
163
|
+
await Promise.all([SyncCounter.ensureIndexes(), SyncMutation.ensureIndexes()]);
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
const registerAll = (): void => {
|
|
167
|
+
clearSyncRegistry();
|
|
168
|
+
registerSync({
|
|
169
|
+
config: {scope: {type: "owner"}},
|
|
170
|
+
model: SockStuffModel as any,
|
|
171
|
+
options: permissiveOptions,
|
|
172
|
+
routePath: "/sockStuff",
|
|
173
|
+
});
|
|
174
|
+
registerSync({
|
|
175
|
+
config: {scope: {field: "orgId", type: "tenant"}},
|
|
176
|
+
model: SockProjectModel as any,
|
|
177
|
+
options: permissiveOptions,
|
|
178
|
+
routePath: "/sockProjects",
|
|
179
|
+
});
|
|
180
|
+
registerSync({
|
|
181
|
+
config: {scope: {type: "broadcast"}},
|
|
182
|
+
model: SockNewsModel as any,
|
|
183
|
+
options: permissiveOptions,
|
|
184
|
+
routePath: "/sockNews",
|
|
185
|
+
});
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
189
|
+
// Mock socket (realtime.test.ts conventions)
|
|
190
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
191
|
+
|
|
192
|
+
interface MockSocket extends SyncSocketLike {
|
|
193
|
+
rooms: Set<string>;
|
|
194
|
+
emitted: {event: string; payload: unknown}[];
|
|
195
|
+
listeners: Map<string, (...args: any[]) => any>;
|
|
196
|
+
trigger: (event: string, ...args: any[]) => Promise<void>;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const createMockSocket = (decodedToken?: {id?: string; admin?: boolean}): MockSocket => {
|
|
200
|
+
const rooms = new Set<string>();
|
|
201
|
+
const emitted: {event: string; payload: unknown}[] = [];
|
|
202
|
+
const listeners = new Map<string, (...args: any[]) => any>();
|
|
203
|
+
|
|
204
|
+
const socket: MockSocket = {
|
|
205
|
+
decodedToken,
|
|
206
|
+
emit: (event, payload) => {
|
|
207
|
+
emitted.push({event, payload});
|
|
208
|
+
},
|
|
209
|
+
emitted,
|
|
210
|
+
id: `socket-${Math.random().toString(36).slice(2, 9)}`,
|
|
211
|
+
join: async (room: string) => {
|
|
212
|
+
rooms.add(room);
|
|
213
|
+
},
|
|
214
|
+
leave: async (room: string) => {
|
|
215
|
+
rooms.delete(room);
|
|
216
|
+
},
|
|
217
|
+
listeners,
|
|
218
|
+
on: (event, handler) => {
|
|
219
|
+
listeners.set(event, handler);
|
|
220
|
+
},
|
|
221
|
+
rooms,
|
|
222
|
+
trigger: async (event, ...args) => {
|
|
223
|
+
const handler = listeners.get(event);
|
|
224
|
+
if (handler) {
|
|
225
|
+
await handler(...args);
|
|
226
|
+
}
|
|
227
|
+
},
|
|
228
|
+
};
|
|
229
|
+
|
|
230
|
+
return socket;
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
const syncErrors = (socket: MockSocket): Array<{collection: string; message: string}> =>
|
|
234
|
+
socket.emitted.filter((e) => e.event === "sync:error").map((e) => e.payload as any);
|
|
235
|
+
|
|
236
|
+
const install = (socket: MockSocket, options: SyncAppOptions = {}): void => {
|
|
237
|
+
installSyncSocketHandlers(null, socket, options);
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
241
|
+
// sync:subscribe / sync:unsubscribe
|
|
242
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
243
|
+
|
|
244
|
+
describe("installSyncSocketHandlers — subscribe/unsubscribe", () => {
|
|
245
|
+
beforeAll(async () => {
|
|
246
|
+
await setupDb();
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
beforeEach(() => {
|
|
250
|
+
registerAll();
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
afterEach(() => {
|
|
254
|
+
clearSyncRegistry();
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
it("owner scope joins the socket's own owner stream room", async () => {
|
|
258
|
+
const socket = createMockSocket({id: "user1"});
|
|
259
|
+
install(socket);
|
|
260
|
+
await socket.trigger("sync:subscribe", {collections: ["sockStuff"]});
|
|
261
|
+
expect(socket.rooms.has("sync:sockStuff|owner:user1")).toBe(true);
|
|
262
|
+
const subscribed = socket.emitted.find((e) => e.event === "sync:subscribed");
|
|
263
|
+
expect(subscribed?.payload).toEqual({
|
|
264
|
+
collection: "sockStuff",
|
|
265
|
+
streams: ["sockStuff|owner:user1"],
|
|
266
|
+
});
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
it("owner scope never uses a client-supplied user id", async () => {
|
|
270
|
+
const socket = createMockSocket({id: "user1"});
|
|
271
|
+
install(socket);
|
|
272
|
+
// The payload has no place for a user id — assert the room is keyed by the token id.
|
|
273
|
+
await socket.trigger("sync:subscribe", {collections: ["sockStuff"], userId: "victim"} as any);
|
|
274
|
+
expect(socket.rooms.has("sync:sockStuff|owner:user1")).toBe(true);
|
|
275
|
+
expect(Array.from(socket.rooms).some((r) => r.includes("victim"))).toBe(false);
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
it("tenant scope joins one room per scope from getUserScopes", async () => {
|
|
279
|
+
const socket = createMockSocket({id: "user1"});
|
|
280
|
+
install(socket, {getUserScopes: () => ["org1", "org2"]});
|
|
281
|
+
await socket.trigger("sync:subscribe", {collections: ["sockProjects"]});
|
|
282
|
+
expect(socket.rooms.has("sync:sockProjects|tenant:org1")).toBe(true);
|
|
283
|
+
expect(socket.rooms.has("sync:sockProjects|tenant:org2")).toBe(true);
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
// Task 9.21: the handshake full-user load is fire-and-forget, so an eager client can
|
|
287
|
+
// subscribe before it resolves. Authorizing that against the synthetic JWT-claim user
|
|
288
|
+
// (no membership fields) resolved tenant scopes to nothing — connected, but no data.
|
|
289
|
+
it("waits for the in-flight handshake full-user load before resolving tenant streams", async () => {
|
|
290
|
+
const socket = createMockSocket({id: "user1"});
|
|
291
|
+
let landFullUser: () => void = () => {};
|
|
292
|
+
const handshake = new Promise<void>((resolve) => {
|
|
293
|
+
landFullUser = resolve;
|
|
294
|
+
});
|
|
295
|
+
socket.data = {
|
|
296
|
+
fullUserLoad: handshake.then(() => {
|
|
297
|
+
(socket.data as {fullUser?: unknown}).fullUser = {
|
|
298
|
+
_id: "user1",
|
|
299
|
+
admin: false,
|
|
300
|
+
id: "user1",
|
|
301
|
+
organizationIds: ["org7"],
|
|
302
|
+
};
|
|
303
|
+
}),
|
|
304
|
+
};
|
|
305
|
+
install(socket, {
|
|
306
|
+
getUserScopes: (user) =>
|
|
307
|
+
(user as unknown as {organizationIds?: string[]}).organizationIds ?? [],
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
const subscribing = socket.trigger("sync:subscribe", {collections: ["sockProjects"]});
|
|
311
|
+
landFullUser();
|
|
312
|
+
await subscribing;
|
|
313
|
+
|
|
314
|
+
expect(socket.rooms.has("sync:sockProjects|tenant:org7")).toBe(true);
|
|
315
|
+
expect(syncErrors(socket)).toHaveLength(0);
|
|
316
|
+
});
|
|
317
|
+
|
|
318
|
+
it("tenant scope without a getUserScopes resolver emits sync:error", async () => {
|
|
319
|
+
const socket = createMockSocket({id: "user1"});
|
|
320
|
+
install(socket, {});
|
|
321
|
+
await socket.trigger("sync:subscribe", {collections: ["sockProjects"]});
|
|
322
|
+
expect(socket.rooms.size).toBe(0);
|
|
323
|
+
expect(syncErrors(socket)).toHaveLength(1);
|
|
324
|
+
expect(syncErrors(socket)[0].collection).toBe("sockProjects");
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
it("tenant scope emits sync:error when getUserScopes throws", async () => {
|
|
328
|
+
const socket = createMockSocket({id: "user1"});
|
|
329
|
+
install(socket, {
|
|
330
|
+
getUserScopes: () => {
|
|
331
|
+
throw new Error("membership lookup failed");
|
|
332
|
+
},
|
|
333
|
+
});
|
|
334
|
+
await socket.trigger("sync:subscribe", {collections: ["sockProjects"]});
|
|
335
|
+
expect(socket.rooms.size).toBe(0);
|
|
336
|
+
expect(syncErrors(socket)).toHaveLength(1);
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
it("broadcast scope joins the shared all room", async () => {
|
|
340
|
+
const socket = createMockSocket({id: "user1"});
|
|
341
|
+
install(socket);
|
|
342
|
+
await socket.trigger("sync:subscribe", {collections: ["sockNews"]});
|
|
343
|
+
expect(socket.rooms.has("sync:sockNews|all")).toBe(true);
|
|
344
|
+
});
|
|
345
|
+
|
|
346
|
+
it("custom scope resolves streams from getUserScopes values", async () => {
|
|
347
|
+
registerSync({
|
|
348
|
+
config: {
|
|
349
|
+
scope: (doc: Record<string, unknown>) => String(doc.region),
|
|
350
|
+
snapshotFilter: () => ({}),
|
|
351
|
+
},
|
|
352
|
+
model: makeFakeSyncModel("SockRegion"),
|
|
353
|
+
options: permissiveOptions,
|
|
354
|
+
routePath: "/sockRegions",
|
|
355
|
+
});
|
|
356
|
+
const socket = createMockSocket({id: "user1"});
|
|
357
|
+
install(socket, {getUserScopes: () => ["us-east", "eu-west"]});
|
|
358
|
+
await socket.trigger("sync:subscribe", {collections: ["sockRegions"]});
|
|
359
|
+
expect(socket.rooms.has("sync:sockRegions|custom:us-east")).toBe(true);
|
|
360
|
+
expect(socket.rooms.has("sync:sockRegions|custom:eu-west")).toBe(true);
|
|
361
|
+
});
|
|
362
|
+
|
|
363
|
+
it("unknown collection emits sync:error and skips, without affecting others", async () => {
|
|
364
|
+
const socket = createMockSocket({id: "user1"});
|
|
365
|
+
install(socket);
|
|
366
|
+
await socket.trigger("sync:subscribe", {collections: ["nope", "sockStuff"]});
|
|
367
|
+
expect(syncErrors(socket)).toEqual([
|
|
368
|
+
{collection: "nope", message: "Unknown sync collection: nope"},
|
|
369
|
+
]);
|
|
370
|
+
expect(socket.rooms.has("sync:sockStuff|owner:user1")).toBe(true);
|
|
371
|
+
});
|
|
372
|
+
|
|
373
|
+
it("denies subscription when list permission fails", async () => {
|
|
374
|
+
clearSyncRegistry();
|
|
375
|
+
registerSync({
|
|
376
|
+
config: {scope: {type: "owner"}},
|
|
377
|
+
model: SockStuffModel as any,
|
|
378
|
+
options: adminOnlyOptions,
|
|
379
|
+
routePath: "/sockStuff",
|
|
380
|
+
});
|
|
381
|
+
const socket = createMockSocket({admin: false, id: "user1"});
|
|
382
|
+
install(socket);
|
|
383
|
+
await socket.trigger("sync:subscribe", {collections: ["sockStuff"]});
|
|
384
|
+
expect(socket.rooms.size).toBe(0);
|
|
385
|
+
expect(syncErrors(socket)).toHaveLength(1);
|
|
386
|
+
});
|
|
387
|
+
|
|
388
|
+
it("allows admin subscription when list permission requires admin", async () => {
|
|
389
|
+
clearSyncRegistry();
|
|
390
|
+
registerSync({
|
|
391
|
+
config: {scope: {type: "owner"}},
|
|
392
|
+
model: SockStuffModel as any,
|
|
393
|
+
options: adminOnlyOptions,
|
|
394
|
+
routePath: "/sockStuff",
|
|
395
|
+
});
|
|
396
|
+
const socket = createMockSocket({admin: true, id: "admin1"});
|
|
397
|
+
install(socket);
|
|
398
|
+
await socket.trigger("sync:subscribe", {collections: ["sockStuff"]});
|
|
399
|
+
expect(socket.rooms.has("sync:sockStuff|owner:admin1")).toBe(true);
|
|
400
|
+
});
|
|
401
|
+
|
|
402
|
+
it("emits sync:error for unauthenticated sockets", async () => {
|
|
403
|
+
const socket = createMockSocket(undefined);
|
|
404
|
+
install(socket);
|
|
405
|
+
await socket.trigger("sync:subscribe", {collections: ["sockStuff"]});
|
|
406
|
+
expect(socket.rooms.size).toBe(0);
|
|
407
|
+
expect(syncErrors(socket)[0].message).toBe("Authentication required");
|
|
408
|
+
});
|
|
409
|
+
|
|
410
|
+
it("ignores malformed payloads", async () => {
|
|
411
|
+
const socket = createMockSocket({id: "user1"});
|
|
412
|
+
install(socket);
|
|
413
|
+
await socket.trigger("sync:subscribe", null);
|
|
414
|
+
await socket.trigger("sync:subscribe", {});
|
|
415
|
+
await socket.trigger("sync:subscribe", {collections: "sockStuff"});
|
|
416
|
+
await socket.trigger("sync:subscribe", {collections: [42, "", null]});
|
|
417
|
+
expect(socket.rooms.size).toBe(0);
|
|
418
|
+
expect(syncErrors(socket)).toHaveLength(0);
|
|
419
|
+
});
|
|
420
|
+
|
|
421
|
+
it("is idempotent for repeated subscriptions to the same collection", async () => {
|
|
422
|
+
const socket = createMockSocket({id: "user1"});
|
|
423
|
+
install(socket);
|
|
424
|
+
await socket.trigger("sync:subscribe", {collections: ["sockStuff"]});
|
|
425
|
+
await socket.trigger("sync:subscribe", {collections: ["sockStuff"]});
|
|
426
|
+
const subscribedEvents = socket.emitted.filter((e) => e.event === "sync:subscribed");
|
|
427
|
+
expect(subscribedEvents).toHaveLength(1);
|
|
428
|
+
});
|
|
429
|
+
|
|
430
|
+
it("enforces the per-socket collection cap with sync:error", async () => {
|
|
431
|
+
clearSyncRegistry();
|
|
432
|
+
for (let i = 0; i < MAX_SYNC_COLLECTION_SUBSCRIPTIONS + 3; i++) {
|
|
433
|
+
registerSync({
|
|
434
|
+
config: {scope: {type: "broadcast"}},
|
|
435
|
+
model: makeFakeSyncModel(`CapColl${i}`),
|
|
436
|
+
options: permissiveOptions,
|
|
437
|
+
routePath: `/capColl${i}`,
|
|
438
|
+
});
|
|
439
|
+
}
|
|
440
|
+
const socket = createMockSocket({id: "user1"});
|
|
441
|
+
install(socket);
|
|
442
|
+
const collections = Array.from(
|
|
443
|
+
{length: MAX_SYNC_COLLECTION_SUBSCRIPTIONS + 3},
|
|
444
|
+
(_v, i) => `capColl${i}`
|
|
445
|
+
);
|
|
446
|
+
await socket.trigger("sync:subscribe", {collections});
|
|
447
|
+
const syncRooms = Array.from(socket.rooms).filter((r) => r.startsWith("sync:"));
|
|
448
|
+
expect(syncRooms).toHaveLength(MAX_SYNC_COLLECTION_SUBSCRIPTIONS);
|
|
449
|
+
expect(syncErrors(socket)).toHaveLength(3);
|
|
450
|
+
});
|
|
451
|
+
|
|
452
|
+
it("C8: rejects an oversized sync:subscribe array before iterating (length check first)", async () => {
|
|
453
|
+
const socket = createMockSocket({id: "user1"});
|
|
454
|
+
install(socket);
|
|
455
|
+
// An array over the cap must be rejected wholesale with a single sync:error and NO
|
|
456
|
+
// room joins — the length guard runs before any per-collection work.
|
|
457
|
+
const collections = Array.from(
|
|
458
|
+
{length: MAX_SYNC_SUBSCRIBE_ARRAY_LENGTH + 1},
|
|
459
|
+
(_v, i) => `sockStuff${i}`
|
|
460
|
+
);
|
|
461
|
+
await socket.trigger("sync:subscribe", {collections});
|
|
462
|
+
expect(Array.from(socket.rooms).filter((r) => r.startsWith("sync:"))).toHaveLength(0);
|
|
463
|
+
const errors = syncErrors(socket);
|
|
464
|
+
expect(errors).toHaveLength(1);
|
|
465
|
+
expect(errors[0].message).toMatch(/at most/i);
|
|
466
|
+
});
|
|
467
|
+
|
|
468
|
+
it("sync:unsubscribe leaves the rooms and frees the cap slot", async () => {
|
|
469
|
+
const socket = createMockSocket({id: "user1"});
|
|
470
|
+
install(socket, {getUserScopes: () => ["org1", "org2"]});
|
|
471
|
+
await socket.trigger("sync:subscribe", {collections: ["sockStuff", "sockProjects"]});
|
|
472
|
+
expect(socket.rooms.has("sync:sockStuff|owner:user1")).toBe(true);
|
|
473
|
+
expect(socket.rooms.has("sync:sockProjects|tenant:org1")).toBe(true);
|
|
474
|
+
|
|
475
|
+
await socket.trigger("sync:unsubscribe", {collections: ["sockProjects"]});
|
|
476
|
+
expect(socket.rooms.has("sync:sockProjects|tenant:org1")).toBe(false);
|
|
477
|
+
expect(socket.rooms.has("sync:sockProjects|tenant:org2")).toBe(false);
|
|
478
|
+
expect(socket.rooms.has("sync:sockStuff|owner:user1")).toBe(true);
|
|
479
|
+
|
|
480
|
+
// Re-subscribing after unsubscribe emits a fresh sync:subscribed.
|
|
481
|
+
await socket.trigger("sync:subscribe", {collections: ["sockProjects"]});
|
|
482
|
+
const subscribedEvents = socket.emitted.filter(
|
|
483
|
+
(e) => e.event === "sync:subscribed" && (e.payload as any).collection === "sockProjects"
|
|
484
|
+
);
|
|
485
|
+
expect(subscribedEvents).toHaveLength(2);
|
|
486
|
+
});
|
|
487
|
+
|
|
488
|
+
it("sync:unsubscribe ignores malformed payloads and unknown collections", async () => {
|
|
489
|
+
const socket = createMockSocket({id: "user1"});
|
|
490
|
+
install(socket);
|
|
491
|
+
await socket.trigger("sync:unsubscribe", null);
|
|
492
|
+
await socket.trigger("sync:unsubscribe", {collections: ["neverSubscribed", 42]});
|
|
493
|
+
expect(socket.rooms.size).toBe(0);
|
|
494
|
+
});
|
|
495
|
+
|
|
496
|
+
it("disconnect clears tracked subscriptions", async () => {
|
|
497
|
+
const socket = createMockSocket({id: "user1"});
|
|
498
|
+
install(socket);
|
|
499
|
+
await socket.trigger("sync:subscribe", {collections: ["sockStuff"]});
|
|
500
|
+
await socket.trigger("disconnect");
|
|
501
|
+
// Rooms are cleaned by Socket.io itself on disconnect; the tracking map is cleared, so
|
|
502
|
+
// a re-subscribe emits sync:subscribed again instead of being treated as a duplicate.
|
|
503
|
+
await socket.trigger("sync:subscribe", {collections: ["sockStuff"]});
|
|
504
|
+
const subscribedEvents = socket.emitted.filter((e) => e.event === "sync:subscribed");
|
|
505
|
+
expect(subscribedEvents).toHaveLength(2);
|
|
506
|
+
});
|
|
507
|
+
});
|
|
508
|
+
|
|
509
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
510
|
+
// sync:mutate
|
|
511
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
512
|
+
|
|
513
|
+
describe("installSyncSocketHandlers — sync:mutate", () => {
|
|
514
|
+
beforeAll(async () => {
|
|
515
|
+
await setupDb();
|
|
516
|
+
});
|
|
517
|
+
|
|
518
|
+
beforeEach(async () => {
|
|
519
|
+
registerAll();
|
|
520
|
+
// Task 9.20: the mutation budget is module-level per user now, so a flooding test
|
|
521
|
+
// would otherwise leave the next test's user over budget within the same second.
|
|
522
|
+
resetSyncMutationRateLimits();
|
|
523
|
+
await Promise.all([
|
|
524
|
+
SockStuffModel.collection.deleteMany({}),
|
|
525
|
+
SyncCounter.deleteMany({}),
|
|
526
|
+
SyncMutation.deleteMany({}),
|
|
527
|
+
]);
|
|
528
|
+
});
|
|
529
|
+
|
|
530
|
+
afterEach(() => {
|
|
531
|
+
clearSyncRegistry();
|
|
532
|
+
});
|
|
533
|
+
|
|
534
|
+
const lastAck = (socket: MockSocket): SyncAck | undefined => {
|
|
535
|
+
const acks = socket.emitted.filter((e) => e.event === "sync:ack");
|
|
536
|
+
return acks[acks.length - 1]?.payload as SyncAck | undefined;
|
|
537
|
+
};
|
|
538
|
+
|
|
539
|
+
const lastNack = (socket: MockSocket): SyncNack | undefined => {
|
|
540
|
+
const nacks = socket.emitted.filter((e) => e.event === "sync:nack");
|
|
541
|
+
return nacks[nacks.length - 1]?.payload as SyncNack | undefined;
|
|
542
|
+
};
|
|
543
|
+
|
|
544
|
+
it("applies a create mutation and emits sync:ack", async () => {
|
|
545
|
+
const socket = createMockSocket({id: "user1"});
|
|
546
|
+
install(socket);
|
|
547
|
+
await socket.trigger("sync:mutate", {
|
|
548
|
+
collection: "sockStuff",
|
|
549
|
+
data: {name: "created over socket", ownerId: "user1"},
|
|
550
|
+
mutationId: "sock-mut-1",
|
|
551
|
+
operation: "create",
|
|
552
|
+
});
|
|
553
|
+
const ack = lastAck(socket);
|
|
554
|
+
expect(ack?.mutationId).toBe("sock-mut-1");
|
|
555
|
+
expect(ack?.seq).toBe(1);
|
|
556
|
+
const doc = await SockStuffModel.findById(ack?.id);
|
|
557
|
+
expect(doc?.name).toBe("created over socket");
|
|
558
|
+
});
|
|
559
|
+
|
|
560
|
+
it("invokes the Socket.io ack callback with the outcome", async () => {
|
|
561
|
+
const socket = createMockSocket({id: "user1"});
|
|
562
|
+
install(socket);
|
|
563
|
+
const replies: unknown[] = [];
|
|
564
|
+
await socket.trigger(
|
|
565
|
+
"sync:mutate",
|
|
566
|
+
{
|
|
567
|
+
collection: "sockStuff",
|
|
568
|
+
data: {name: "cb", ownerId: "user1"},
|
|
569
|
+
mutationId: "sock-mut-cb",
|
|
570
|
+
operation: "create",
|
|
571
|
+
},
|
|
572
|
+
(response: unknown) => replies.push(response)
|
|
573
|
+
);
|
|
574
|
+
expect(replies).toHaveLength(1);
|
|
575
|
+
expect((replies[0] as {ack: SyncAck}).ack.mutationId).toBe("sock-mut-cb");
|
|
576
|
+
});
|
|
577
|
+
|
|
578
|
+
it("stale baseVersion emits sync:nack conflict carrying the server doc", async () => {
|
|
579
|
+
const doc = await SockStuffModel.create({name: "v1", ownerId: "user1"});
|
|
580
|
+
await SockStuffModel.findOneAndUpdate({_id: doc._id}, {$set: {name: "v2"}});
|
|
581
|
+
|
|
582
|
+
const socket = createMockSocket({id: "user1"});
|
|
583
|
+
install(socket);
|
|
584
|
+
await socket.trigger("sync:mutate", {
|
|
585
|
+
baseVersion: 1,
|
|
586
|
+
collection: "sockStuff",
|
|
587
|
+
data: {name: "stale write"},
|
|
588
|
+
id: String(doc._id),
|
|
589
|
+
mutationId: "sock-mut-conflict",
|
|
590
|
+
operation: "update",
|
|
591
|
+
});
|
|
592
|
+
const nack = lastNack(socket);
|
|
593
|
+
expect(nack?.code).toBe("conflict");
|
|
594
|
+
expect(nack?.serverSeq).toBe(2);
|
|
595
|
+
expect((nack?.serverDoc as any)?.name).toBe("v2");
|
|
596
|
+
});
|
|
597
|
+
|
|
598
|
+
it("duplicate mutationId over the socket returns the recorded outcome without re-applying", async () => {
|
|
599
|
+
const socket = createMockSocket({id: "user1"});
|
|
600
|
+
install(socket);
|
|
601
|
+
const mutation = {
|
|
602
|
+
collection: "sockStuff",
|
|
603
|
+
data: {name: "dup", ownerId: "user1"},
|
|
604
|
+
mutationId: "sock-mut-dup",
|
|
605
|
+
operation: "create",
|
|
606
|
+
};
|
|
607
|
+
await socket.trigger("sync:mutate", mutation);
|
|
608
|
+
await socket.trigger("sync:mutate", mutation);
|
|
609
|
+
const acks = socket.emitted.filter((e) => e.event === "sync:ack");
|
|
610
|
+
expect(acks).toHaveLength(2);
|
|
611
|
+
expect((acks[0].payload as SyncAck).id).toBe((acks[1].payload as SyncAck).id);
|
|
612
|
+
expect((acks[0].payload as SyncAck).seq).toBe((acks[1].payload as SyncAck).seq);
|
|
613
|
+
expect(await SockStuffModel.countDocuments({name: "dup"})).toBe(1);
|
|
614
|
+
});
|
|
615
|
+
|
|
616
|
+
it("nacks validation for an unknown collection", async () => {
|
|
617
|
+
const socket = createMockSocket({id: "user1"});
|
|
618
|
+
install(socket);
|
|
619
|
+
await socket.trigger("sync:mutate", {
|
|
620
|
+
collection: "nope",
|
|
621
|
+
data: {},
|
|
622
|
+
mutationId: "sock-mut-unknown",
|
|
623
|
+
operation: "create",
|
|
624
|
+
});
|
|
625
|
+
expect(lastNack(socket)?.code).toBe("validation");
|
|
626
|
+
});
|
|
627
|
+
|
|
628
|
+
it("nacks unauthorized for unauthenticated sockets", async () => {
|
|
629
|
+
const socket = createMockSocket(undefined);
|
|
630
|
+
install(socket);
|
|
631
|
+
await socket.trigger("sync:mutate", {
|
|
632
|
+
collection: "sockStuff",
|
|
633
|
+
data: {name: "x"},
|
|
634
|
+
mutationId: "sock-mut-anon",
|
|
635
|
+
operation: "create",
|
|
636
|
+
});
|
|
637
|
+
expect(lastNack(socket)?.code).toBe("unauthorized");
|
|
638
|
+
});
|
|
639
|
+
|
|
640
|
+
it("rate-limits mutations beyond the per-second cap with a rate_limited nack carrying retryAfterMs (FIX 1)", async () => {
|
|
641
|
+
const socket = createMockSocket({id: "user1"});
|
|
642
|
+
install(socket);
|
|
643
|
+
// Exceed the window with cheap validation nacks (unknown collection) — the rate limit
|
|
644
|
+
// triggers before the mutation is applied, so these never hit the database.
|
|
645
|
+
for (let i = 0; i < MAX_SYNC_MUTATIONS_PER_SECOND + 5; i++) {
|
|
646
|
+
await socket.trigger("sync:mutate", {
|
|
647
|
+
collection: "nope",
|
|
648
|
+
mutationId: `flood-${i}`,
|
|
649
|
+
operation: "create",
|
|
650
|
+
});
|
|
651
|
+
}
|
|
652
|
+
const nacks = socket.emitted.filter((e) => e.event === "sync:nack");
|
|
653
|
+
expect(nacks).toHaveLength(MAX_SYNC_MUTATIONS_PER_SECOND + 5);
|
|
654
|
+
const rateLimited = nacks.filter((e) =>
|
|
655
|
+
(e.payload as SyncNack).message?.includes("Rate limit")
|
|
656
|
+
);
|
|
657
|
+
expect(rateLimited).toHaveLength(5);
|
|
658
|
+
// FIX 1: the nack code is "rate_limited" (never "error") so the client
|
|
659
|
+
// never treats it as a durable-data failure, and it carries a
|
|
660
|
+
// retryAfterMs hint for the client's backoff floor.
|
|
661
|
+
for (const nack of rateLimited) {
|
|
662
|
+
const payload = nack.payload as SyncNack;
|
|
663
|
+
expect(payload.code).toBe("rate_limited");
|
|
664
|
+
expect(typeof (payload as {retryAfterMs?: number}).retryAfterMs).toBe("number");
|
|
665
|
+
}
|
|
666
|
+
});
|
|
667
|
+
});
|
|
668
|
+
|
|
669
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
670
|
+
// sync:mutateBatch
|
|
671
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
672
|
+
|
|
673
|
+
describe("installSyncSocketHandlers — sync:mutateBatch", () => {
|
|
674
|
+
beforeAll(async () => {
|
|
675
|
+
await setupDb();
|
|
676
|
+
});
|
|
677
|
+
|
|
678
|
+
beforeEach(async () => {
|
|
679
|
+
registerAll();
|
|
680
|
+
resetSyncMutationRateLimits();
|
|
681
|
+
await Promise.all([
|
|
682
|
+
SockStuffModel.collection.deleteMany({}),
|
|
683
|
+
SyncCounter.deleteMany({}),
|
|
684
|
+
SyncMutation.deleteMany({}),
|
|
685
|
+
]);
|
|
686
|
+
});
|
|
687
|
+
|
|
688
|
+
afterEach(() => {
|
|
689
|
+
clearSyncRegistry();
|
|
690
|
+
});
|
|
691
|
+
|
|
692
|
+
const create = (mutationId: string, name: string) => ({
|
|
693
|
+
collection: "sockStuff",
|
|
694
|
+
data: {name, ownerId: "user1"},
|
|
695
|
+
mutationId,
|
|
696
|
+
operation: "create",
|
|
697
|
+
});
|
|
698
|
+
|
|
699
|
+
const triggerBatch = async (
|
|
700
|
+
socket: MockSocket,
|
|
701
|
+
mutations: unknown[]
|
|
702
|
+
): Promise<{results: Array<{type: string; ack?: SyncAck; nack?: SyncNack}>}> => {
|
|
703
|
+
let response: any;
|
|
704
|
+
await socket.trigger("sync:mutateBatch", {mutations}, (res: unknown) => {
|
|
705
|
+
response = res;
|
|
706
|
+
});
|
|
707
|
+
return response;
|
|
708
|
+
};
|
|
709
|
+
|
|
710
|
+
it("applies a batch strictly in order via the ack callback", async () => {
|
|
711
|
+
const socket = createMockSocket({id: "user1"});
|
|
712
|
+
install(socket);
|
|
713
|
+
const mutations = Array.from({length: 5}, (_v, i) => create(`sock-batch-${i}`, `item ${i}`));
|
|
714
|
+
const response = await triggerBatch(socket, mutations);
|
|
715
|
+
expect(response.results).toHaveLength(5);
|
|
716
|
+
expect(response.results.every((r) => r.type === "ack")).toBe(true);
|
|
717
|
+
const seqs = response.results.map((r) => r.ack?.seq);
|
|
718
|
+
expect(seqs).toEqual([1, 2, 3, 4, 5]);
|
|
719
|
+
});
|
|
720
|
+
|
|
721
|
+
it("stops at the first nack, leaving later mutations unattempted", async () => {
|
|
722
|
+
const socket = createMockSocket({id: "user1"});
|
|
723
|
+
install(socket);
|
|
724
|
+
const mutations = [
|
|
725
|
+
create("sock-batch-halt-1", "ok"),
|
|
726
|
+
{collection: "nope", mutationId: "sock-batch-halt-2", operation: "create"},
|
|
727
|
+
create("sock-batch-halt-3", "never"),
|
|
728
|
+
];
|
|
729
|
+
const response = await triggerBatch(socket, mutations);
|
|
730
|
+
expect(response.results).toHaveLength(2);
|
|
731
|
+
expect(response.results[0].type).toBe("ack");
|
|
732
|
+
expect(response.results[1].type).toBe("nack");
|
|
733
|
+
expect(response.results[1].nack?.code).toBe("validation");
|
|
734
|
+
expect(await SockStuffModel.countDocuments({name: "never"})).toBe(0);
|
|
735
|
+
});
|
|
736
|
+
|
|
737
|
+
it("rejects an oversized batch before processing", async () => {
|
|
738
|
+
const socket = createMockSocket({id: "user1"});
|
|
739
|
+
install(socket);
|
|
740
|
+
const mutations = Array.from({length: MAX_SYNC_MUTATIONS_PER_BATCH + 1}, (_v, i) =>
|
|
741
|
+
create(`sock-batch-oversized-${i}`, `item ${i}`)
|
|
742
|
+
);
|
|
743
|
+
const response = await triggerBatch(socket, mutations);
|
|
744
|
+
expect(response.results).toHaveLength(1);
|
|
745
|
+
expect(response.results[0].nack?.code).toBe("validation");
|
|
746
|
+
expect(await SockStuffModel.countDocuments({})).toBe(0);
|
|
747
|
+
});
|
|
748
|
+
|
|
749
|
+
it("rejects intra-batch duplicate mutationIds before processing", async () => {
|
|
750
|
+
const socket = createMockSocket({id: "user1"});
|
|
751
|
+
install(socket);
|
|
752
|
+
const mutations = [create("sock-batch-dup", "a"), create("sock-batch-dup", "b")];
|
|
753
|
+
const response = await triggerBatch(socket, mutations);
|
|
754
|
+
expect(response.results).toHaveLength(1);
|
|
755
|
+
expect(response.results[0].nack?.code).toBe("validation");
|
|
756
|
+
expect(await SockStuffModel.countDocuments({})).toBe(0);
|
|
757
|
+
});
|
|
758
|
+
|
|
759
|
+
it("nacks unauthorized for unauthenticated sockets", async () => {
|
|
760
|
+
const socket = createMockSocket(undefined);
|
|
761
|
+
install(socket);
|
|
762
|
+
const response = await triggerBatch(socket, [create("sock-batch-anon", "x")]);
|
|
763
|
+
expect(response.results).toHaveLength(1);
|
|
764
|
+
expect(response.results[0].nack?.code).toBe("unauthorized");
|
|
765
|
+
});
|
|
766
|
+
|
|
767
|
+
it("rate-limits batch mutations against the same window as sync:mutate with a rate_limited nack carrying retryAfterMs (FIX 1)", async () => {
|
|
768
|
+
const socket = createMockSocket({id: "user1"});
|
|
769
|
+
install(socket);
|
|
770
|
+
// Two batches within the per-batch size cap, but together exceeding the
|
|
771
|
+
// per-second mutation budget — the shared window rejects the second batch
|
|
772
|
+
// before any of its mutations are attempted.
|
|
773
|
+
const firstBatch = Array.from({length: MAX_SYNC_MUTATIONS_PER_BATCH}, (_v, i) => ({
|
|
774
|
+
collection: "nope",
|
|
775
|
+
mutationId: `flood-batch-a-${i}`,
|
|
776
|
+
operation: "create",
|
|
777
|
+
}));
|
|
778
|
+
const secondBatch = Array.from({length: 10}, (_v, i) => ({
|
|
779
|
+
collection: "nope",
|
|
780
|
+
mutationId: `flood-batch-b-${i}`,
|
|
781
|
+
operation: "create",
|
|
782
|
+
}));
|
|
783
|
+
await triggerBatch(socket, firstBatch);
|
|
784
|
+
const response = await triggerBatch(socket, secondBatch);
|
|
785
|
+
expect(response.results).toHaveLength(1);
|
|
786
|
+
expect(response.results[0].nack?.message).toContain("Rate limit");
|
|
787
|
+
// FIX 1: rate limiting must never look like a durable-data error — the
|
|
788
|
+
// client treats "rate_limited" like a transport failure (never terminal).
|
|
789
|
+
expect(response.results[0].nack?.code).toBe("rate_limited");
|
|
790
|
+
expect(typeof (response.results[0].nack as {retryAfterMs?: number})?.retryAfterMs).toBe(
|
|
791
|
+
"number"
|
|
792
|
+
);
|
|
793
|
+
});
|
|
794
|
+
|
|
795
|
+
it("emits sync:batchReceived immediately, before any mutation is applied (FIX 5)", async () => {
|
|
796
|
+
const socket = createMockSocket({id: "user1"});
|
|
797
|
+
install(socket);
|
|
798
|
+
const mutations = [create("sock-batch-receipt-1", "a")];
|
|
799
|
+
await socket.trigger("sync:mutateBatch", {batchId: "b-123", mutations}, () => {});
|
|
800
|
+
const receipts = socket.emitted.filter((e) => e.event === "sync:batchReceived");
|
|
801
|
+
expect(receipts).toHaveLength(1);
|
|
802
|
+
expect(receipts[0].payload).toEqual({batchId: "b-123"});
|
|
803
|
+
});
|
|
804
|
+
|
|
805
|
+
it("does not emit sync:batchReceived when the request has no batchId (HTTP-shaped payload)", async () => {
|
|
806
|
+
const socket = createMockSocket({id: "user1"});
|
|
807
|
+
install(socket);
|
|
808
|
+
await triggerBatch(socket, [create("sock-batch-no-id", "a")]);
|
|
809
|
+
expect(socket.emitted.filter((e) => e.event === "sync:batchReceived")).toHaveLength(0);
|
|
810
|
+
});
|
|
811
|
+
|
|
812
|
+
// Task 9.20: the budget used to live in the per-connection handler closure, so a client
|
|
813
|
+
// could simply open another socket to get another full allowance.
|
|
814
|
+
it("shares one per-user budget across sockets, and keeps separate users independent", async () => {
|
|
815
|
+
const firstSocket = createMockSocket({id: "user1"});
|
|
816
|
+
const secondSocket = createMockSocket({id: "user1"});
|
|
817
|
+
const otherUserSocket = createMockSocket({id: "user2"});
|
|
818
|
+
install(firstSocket);
|
|
819
|
+
install(secondSocket);
|
|
820
|
+
install(otherUserSocket);
|
|
821
|
+
const flood = (label: string, length: number): unknown[] =>
|
|
822
|
+
Array.from({length}, (_v, i) => ({
|
|
823
|
+
collection: "nope",
|
|
824
|
+
mutationId: `${label}-${i}`,
|
|
825
|
+
operation: "create",
|
|
826
|
+
}));
|
|
827
|
+
|
|
828
|
+
// The first socket exhausts the whole per-second budget...
|
|
829
|
+
await triggerBatch(firstSocket, flood("shared-a", MAX_SYNC_MUTATIONS_PER_BATCH));
|
|
830
|
+
// ...so the SECOND socket for the same user has nothing left.
|
|
831
|
+
const secondResponse = await triggerBatch(secondSocket, flood("shared-b", 1));
|
|
832
|
+
expect(secondResponse.results[0].nack?.code).toBe("rate_limited");
|
|
833
|
+
// A different user is unaffected — the window is per user, not global.
|
|
834
|
+
const otherResponse = await triggerBatch(otherUserSocket, flood("shared-c", 1));
|
|
835
|
+
expect(otherResponse.results[0].nack?.code).toBe("validation");
|
|
836
|
+
});
|
|
837
|
+
|
|
838
|
+
it("charges no budget for a batch that fails validation", async () => {
|
|
839
|
+
const socket = createMockSocket({id: "user1"});
|
|
840
|
+
install(socket);
|
|
841
|
+
// An oversized batch is rejected before the budget is touched, so the follow-up batch
|
|
842
|
+
// (which would exceed the budget had the invalid one been charged) still applies.
|
|
843
|
+
const oversized = Array.from({length: MAX_SYNC_MUTATIONS_PER_BATCH + 1}, (_v, i) =>
|
|
844
|
+
create(`no-charge-${i}`, `item ${i}`)
|
|
845
|
+
);
|
|
846
|
+
const rejected = await triggerBatch(socket, oversized);
|
|
847
|
+
expect(rejected.results[0].nack?.code).toBe("validation");
|
|
848
|
+
|
|
849
|
+
const applied = await triggerBatch(
|
|
850
|
+
socket,
|
|
851
|
+
Array.from({length: MAX_SYNC_MUTATIONS_PER_BATCH}, (_v, i) => ({
|
|
852
|
+
collection: "nope",
|
|
853
|
+
mutationId: `after-no-charge-${i}`,
|
|
854
|
+
operation: "create",
|
|
855
|
+
}))
|
|
856
|
+
);
|
|
857
|
+
// Stop-on-first-nack means one validation result comes back — the point is that it is
|
|
858
|
+
// NOT a rate_limited result, i.e. the full budget was still available.
|
|
859
|
+
expect(applied.results[0].nack?.code).toBe("validation");
|
|
860
|
+
});
|
|
861
|
+
|
|
862
|
+
it("evicts expired per-user windows instead of retaining one per user forever", async () => {
|
|
863
|
+
resetSyncMutationRateLimits();
|
|
864
|
+
const firstSocket = createMockSocket({id: "user1"});
|
|
865
|
+
const otherUserSocket = createMockSocket({id: "user2"});
|
|
866
|
+
install(firstSocket);
|
|
867
|
+
install(otherUserSocket);
|
|
868
|
+
await triggerBatch(firstSocket, [create("evict-1", "a")]);
|
|
869
|
+
await triggerBatch(otherUserSocket, [create("evict-2", "b")]);
|
|
870
|
+
expect(syncMutationRateLimitWindowCount()).toBe(2);
|
|
871
|
+
// The sweep is throttled to once a minute in normal operation; drive it directly with a
|
|
872
|
+
// clock past both windows' expiry rather than waiting.
|
|
873
|
+
expect(evictExpiredSyncMutationWindows({now: Date.now() + 60_000})).toBe(0);
|
|
874
|
+
expect(syncMutationRateLimitWindowCount()).toBe(0);
|
|
875
|
+
});
|
|
876
|
+
});
|
|
877
|
+
|
|
878
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
879
|
+
// Per-app SyncAppOptions wiring (SyncApp -> RealtimeApp)
|
|
880
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
881
|
+
|
|
882
|
+
describe("SyncAppOptions context", () => {
|
|
883
|
+
it("SyncApp.register attaches its options to only its Express app", async () => {
|
|
884
|
+
const express = (await import("express")).default;
|
|
885
|
+
const firstApp = express();
|
|
886
|
+
const secondApp = express();
|
|
887
|
+
const options: SyncAppOptions = {getUserScopes: () => ["orgX"]};
|
|
888
|
+
new SyncApp(options).register(firstApp);
|
|
889
|
+
expect(getSyncAppOptions(firstApp)).toBe(options);
|
|
890
|
+
expect(getSyncAppOptions(secondApp)).toBeUndefined();
|
|
891
|
+
});
|
|
892
|
+
});
|
|
893
|
+
|
|
894
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
895
|
+
// sync:delta emission — mock io helpers
|
|
896
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
897
|
+
|
|
898
|
+
const makeTrackedIo = (): any => {
|
|
899
|
+
const emissions: Array<{event: string; payload: any; room: string; socketId: string}> = [];
|
|
900
|
+
const rooms = new Map<string, Set<string>>();
|
|
901
|
+
const sockets = new Map<string, any>();
|
|
902
|
+
|
|
903
|
+
const addSocketToRoom = (
|
|
904
|
+
room: string,
|
|
905
|
+
decodedToken: {id?: string; admin?: boolean} = {admin: true, id: "admin"}
|
|
906
|
+
): void => {
|
|
907
|
+
const socketId = `socket-${Math.random().toString(36).slice(2, 9)}`;
|
|
908
|
+
if (!rooms.has(room)) {
|
|
909
|
+
rooms.set(room, new Set());
|
|
910
|
+
}
|
|
911
|
+
rooms.get(room)?.add(socketId);
|
|
912
|
+
sockets.set(socketId, {
|
|
913
|
+
decodedToken,
|
|
914
|
+
emit: (event: string, payload: unknown): void => {
|
|
915
|
+
emissions.push({event, payload, room, socketId});
|
|
916
|
+
},
|
|
917
|
+
id: socketId,
|
|
918
|
+
});
|
|
919
|
+
};
|
|
920
|
+
|
|
921
|
+
return {
|
|
922
|
+
addSocketToRoom,
|
|
923
|
+
emissions,
|
|
924
|
+
sockets: {
|
|
925
|
+
adapter: {rooms},
|
|
926
|
+
sockets,
|
|
927
|
+
},
|
|
928
|
+
to: (room: string) => ({
|
|
929
|
+
emit: (event: string, payload: unknown): void => {
|
|
930
|
+
emissions.push({event, payload, room, socketId: "broadcast"});
|
|
931
|
+
},
|
|
932
|
+
}),
|
|
933
|
+
};
|
|
934
|
+
};
|
|
935
|
+
|
|
936
|
+
const makeChange = (overrides: Record<string, unknown>): any => ({
|
|
937
|
+
documentKey: {_id: "doc-1"},
|
|
938
|
+
ns: {coll: "sockstuffs"},
|
|
939
|
+
operationType: "insert",
|
|
940
|
+
...overrides,
|
|
941
|
+
});
|
|
942
|
+
|
|
943
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
944
|
+
// emitSyncDeltaForChange — unit tests with synthetic changes
|
|
945
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
946
|
+
|
|
947
|
+
describe("emitSyncDeltaForChange", () => {
|
|
948
|
+
beforeAll(async () => {
|
|
949
|
+
await setupDb();
|
|
950
|
+
});
|
|
951
|
+
|
|
952
|
+
beforeEach(() => {
|
|
953
|
+
registerAll();
|
|
954
|
+
});
|
|
955
|
+
|
|
956
|
+
afterEach(() => {
|
|
957
|
+
clearSyncRegistry();
|
|
958
|
+
});
|
|
959
|
+
|
|
960
|
+
const ownerEntry = (): SyncRegistryEntry => {
|
|
961
|
+
clearSyncRegistry();
|
|
962
|
+
registerSync({
|
|
963
|
+
config: {scope: {type: "owner"}},
|
|
964
|
+
model: SockStuffModel as any,
|
|
965
|
+
options: ownerReadOptions,
|
|
966
|
+
routePath: "/sockStuff",
|
|
967
|
+
});
|
|
968
|
+
return findSyncEntryByCollectionTag("sockStuff") as SyncRegistryEntry;
|
|
969
|
+
};
|
|
970
|
+
|
|
971
|
+
it("emits a create delta with seq and stream to the owner stream room", async () => {
|
|
972
|
+
const entry = ownerEntry();
|
|
973
|
+
const io = makeTrackedIo();
|
|
974
|
+
io.addSocketToRoom(syncRoomForStream("sockStuff|owner:user1"), {admin: false, id: "user1"});
|
|
975
|
+
|
|
976
|
+
await emitSyncDeltaForChange({
|
|
977
|
+
change: makeChange({
|
|
978
|
+
fullDocument: {_id: "doc-1", _syncSeq: 7, name: "hello", ownerId: "user1"},
|
|
979
|
+
operationType: "insert",
|
|
980
|
+
}),
|
|
981
|
+
docId: "doc-1",
|
|
982
|
+
entry,
|
|
983
|
+
io,
|
|
984
|
+
logDebug: () => {},
|
|
985
|
+
});
|
|
986
|
+
|
|
987
|
+
const deltas = io.emissions.filter((e: any) => e.event === "sync:delta");
|
|
988
|
+
expect(deltas).toHaveLength(1);
|
|
989
|
+
const delta = deltas[0].payload as SyncDelta;
|
|
990
|
+
expect(delta.method).toBe("create");
|
|
991
|
+
expect(delta.seq).toBe(7);
|
|
992
|
+
expect(delta.stream).toBe("sockStuff|owner:user1");
|
|
993
|
+
expect(delta.collection).toBe("sockStuff");
|
|
994
|
+
expect((delta.data as any).name).toBe("hello");
|
|
995
|
+
expect((delta.data as any).id).toBe("doc-1");
|
|
996
|
+
});
|
|
997
|
+
|
|
998
|
+
it("does not emit to sockets whose read permission fails (owner isolation)", async () => {
|
|
999
|
+
const entry = ownerEntry();
|
|
1000
|
+
const io = makeTrackedIo();
|
|
1001
|
+
const room = syncRoomForStream("sockStuff|owner:user1");
|
|
1002
|
+
io.addSocketToRoom(room, {admin: false, id: "user1"});
|
|
1003
|
+
io.addSocketToRoom(room, {admin: false, id: "intruder"});
|
|
1004
|
+
|
|
1005
|
+
await emitSyncDeltaForChange({
|
|
1006
|
+
change: makeChange({
|
|
1007
|
+
fullDocument: {_id: "doc-1", _syncSeq: 1, name: "secret", ownerId: "user1"},
|
|
1008
|
+
}),
|
|
1009
|
+
docId: "doc-1",
|
|
1010
|
+
entry,
|
|
1011
|
+
io,
|
|
1012
|
+
logDebug: () => {},
|
|
1013
|
+
});
|
|
1014
|
+
|
|
1015
|
+
const deltas = io.emissions.filter((e: any) => e.event === "sync:delta");
|
|
1016
|
+
expect(deltas).toHaveLength(1);
|
|
1017
|
+
const receiver = io.sockets.sockets.get(deltas[0].socketId);
|
|
1018
|
+
expect(receiver.decodedToken.id).toBe("user1");
|
|
1019
|
+
});
|
|
1020
|
+
|
|
1021
|
+
it("C7: soft delete emits a delete delta with deleted true and NO data (tombstone stripped)", async () => {
|
|
1022
|
+
const entry = ownerEntry();
|
|
1023
|
+
const io = makeTrackedIo();
|
|
1024
|
+
io.addSocketToRoom(syncRoomForStream("sockStuff|owner:user1"), {admin: false, id: "user1"});
|
|
1025
|
+
|
|
1026
|
+
await emitSyncDeltaForChange({
|
|
1027
|
+
change: makeChange({
|
|
1028
|
+
fullDocument: {_id: "doc-1", _syncSeq: 3, deleted: true, name: "gone", ownerId: "user1"},
|
|
1029
|
+
operationType: "update",
|
|
1030
|
+
updateDescription: {updatedFields: {deleted: true}},
|
|
1031
|
+
}),
|
|
1032
|
+
docId: "doc-1",
|
|
1033
|
+
entry,
|
|
1034
|
+
io,
|
|
1035
|
+
logDebug: () => {},
|
|
1036
|
+
});
|
|
1037
|
+
|
|
1038
|
+
const deltas = io.emissions.filter((e: any) => e.event === "sync:delta");
|
|
1039
|
+
expect(deltas).toHaveLength(1);
|
|
1040
|
+
const delta = deltas[0].payload as SyncDelta;
|
|
1041
|
+
expect(delta.method).toBe("delete");
|
|
1042
|
+
expect(delta.deleted).toBe(true);
|
|
1043
|
+
expect(delta.seq).toBe(3);
|
|
1044
|
+
// C7: a tombstone delta carries no data (privacy + payload growth).
|
|
1045
|
+
expect(delta.data).toBeUndefined();
|
|
1046
|
+
});
|
|
1047
|
+
|
|
1048
|
+
it("C4: scope move emits a data-less tombstone (from the durable marker) to the previous stream and a create to the new stream", async () => {
|
|
1049
|
+
const entry = ownerEntry();
|
|
1050
|
+
await SyncScopeMove.deleteMany({});
|
|
1051
|
+
// C4: the tombstone is driven by a durable SyncScopeMove marker, not _syncPrevStream.
|
|
1052
|
+
await SyncScopeMove.create({
|
|
1053
|
+
collectionTag: "sockStuff",
|
|
1054
|
+
entityId: "doc-1",
|
|
1055
|
+
fromStream: "sockStuff|owner:user1",
|
|
1056
|
+
seq: 9,
|
|
1057
|
+
toStream: "sockStuff|owner:user2",
|
|
1058
|
+
});
|
|
1059
|
+
const io = makeTrackedIo();
|
|
1060
|
+
const oldRoom = syncRoomForStream("sockStuff|owner:user1");
|
|
1061
|
+
const newRoom = syncRoomForStream("sockStuff|owner:user2");
|
|
1062
|
+
io.addSocketToRoom(oldRoom, {admin: true, id: "admin"});
|
|
1063
|
+
io.addSocketToRoom(newRoom, {admin: true, id: "admin"});
|
|
1064
|
+
|
|
1065
|
+
await emitSyncDeltaForChange({
|
|
1066
|
+
change: makeChange({
|
|
1067
|
+
fullDocument: {
|
|
1068
|
+
_id: "doc-1",
|
|
1069
|
+
_syncSeq: 9,
|
|
1070
|
+
name: "moved",
|
|
1071
|
+
ownerId: "user2",
|
|
1072
|
+
},
|
|
1073
|
+
operationType: "update",
|
|
1074
|
+
updateDescription: {updatedFields: {ownerId: "user2"}},
|
|
1075
|
+
}),
|
|
1076
|
+
docId: "doc-1",
|
|
1077
|
+
entry,
|
|
1078
|
+
io,
|
|
1079
|
+
logDebug: () => {},
|
|
1080
|
+
});
|
|
1081
|
+
|
|
1082
|
+
const deltas = io.emissions.filter((e: any) => e.event === "sync:delta");
|
|
1083
|
+
expect(deltas).toHaveLength(2);
|
|
1084
|
+
|
|
1085
|
+
const tombstone = deltas.find((e: any) => e.room === oldRoom)?.payload as SyncDelta;
|
|
1086
|
+
expect(tombstone.method).toBe("delete");
|
|
1087
|
+
expect(tombstone.deleted).toBe(true);
|
|
1088
|
+
expect(tombstone.stream).toBe("sockStuff|owner:user1");
|
|
1089
|
+
expect(tombstone.seq).toBe(9);
|
|
1090
|
+
expect(tombstone.data).toBeUndefined();
|
|
1091
|
+
|
|
1092
|
+
const create = deltas.find((e: any) => e.room === newRoom)?.payload as SyncDelta;
|
|
1093
|
+
expect(create.method).toBe("create");
|
|
1094
|
+
expect(create.stream).toBe("sockStuff|owner:user2");
|
|
1095
|
+
expect((create.data as any).name).toBe("moved");
|
|
1096
|
+
await SyncScopeMove.deleteMany({});
|
|
1097
|
+
});
|
|
1098
|
+
|
|
1099
|
+
it("C4: a racing second write cannot suppress the tombstone (the marker is durable, not the post-image)", async () => {
|
|
1100
|
+
// Simulates the race the design fixes: a second write reset _syncPrevStream to null
|
|
1101
|
+
// before this change event was processed. With the OLD implementation the old stream
|
|
1102
|
+
// would never get a tombstone; with the marker it still does.
|
|
1103
|
+
const entry = ownerEntry();
|
|
1104
|
+
await SyncScopeMove.deleteMany({});
|
|
1105
|
+
await SyncScopeMove.create({
|
|
1106
|
+
collectionTag: "sockStuff",
|
|
1107
|
+
entityId: "doc-1",
|
|
1108
|
+
fromStream: "sockStuff|owner:user1",
|
|
1109
|
+
seq: 11,
|
|
1110
|
+
toStream: "sockStuff|owner:user2",
|
|
1111
|
+
});
|
|
1112
|
+
const io = makeTrackedIo();
|
|
1113
|
+
const oldRoom = syncRoomForStream("sockStuff|owner:user1");
|
|
1114
|
+
io.addSocketToRoom(oldRoom, {admin: true, id: "admin"});
|
|
1115
|
+
io.addSocketToRoom(syncRoomForStream("sockStuff|owner:user2"), {admin: true, id: "admin"});
|
|
1116
|
+
|
|
1117
|
+
await emitSyncDeltaForChange({
|
|
1118
|
+
change: makeChange({
|
|
1119
|
+
fullDocument: {
|
|
1120
|
+
_id: "doc-1",
|
|
1121
|
+
// _syncPrevStream is null (overwritten by the racing second write) — irrelevant now.
|
|
1122
|
+
_syncPrevStream: null,
|
|
1123
|
+
_syncSeq: 12,
|
|
1124
|
+
name: "moved then edited",
|
|
1125
|
+
ownerId: "user2",
|
|
1126
|
+
},
|
|
1127
|
+
operationType: "update",
|
|
1128
|
+
updateDescription: {updatedFields: {name: "moved then edited"}},
|
|
1129
|
+
}),
|
|
1130
|
+
docId: "doc-1",
|
|
1131
|
+
entry,
|
|
1132
|
+
io,
|
|
1133
|
+
logDebug: () => {},
|
|
1134
|
+
});
|
|
1135
|
+
|
|
1136
|
+
const deltas = io.emissions.filter((e: any) => e.event === "sync:delta");
|
|
1137
|
+
const tombstone = deltas.find((e: any) => e.room === oldRoom)?.payload as SyncDelta;
|
|
1138
|
+
expect(tombstone).toBeDefined();
|
|
1139
|
+
expect(tombstone.method).toBe("delete");
|
|
1140
|
+
expect(tombstone.stream).toBe("sockStuff|owner:user1");
|
|
1141
|
+
expect(tombstone.seq).toBe(11);
|
|
1142
|
+
await SyncScopeMove.deleteMany({});
|
|
1143
|
+
});
|
|
1144
|
+
|
|
1145
|
+
it("C4: no marker for the current stream means a plain update (no spurious tombstone)", async () => {
|
|
1146
|
+
const entry = ownerEntry();
|
|
1147
|
+
await SyncScopeMove.deleteMany({});
|
|
1148
|
+
const io = makeTrackedIo();
|
|
1149
|
+
io.addSocketToRoom(syncRoomForStream("sockStuff|owner:user1"), {admin: false, id: "user1"});
|
|
1150
|
+
|
|
1151
|
+
await emitSyncDeltaForChange({
|
|
1152
|
+
change: makeChange({
|
|
1153
|
+
fullDocument: {
|
|
1154
|
+
_id: "doc-1",
|
|
1155
|
+
_syncSeq: 4,
|
|
1156
|
+
name: "same stream",
|
|
1157
|
+
ownerId: "user1",
|
|
1158
|
+
},
|
|
1159
|
+
operationType: "update",
|
|
1160
|
+
updateDescription: {updatedFields: {name: "same stream"}},
|
|
1161
|
+
}),
|
|
1162
|
+
docId: "doc-1",
|
|
1163
|
+
entry,
|
|
1164
|
+
io,
|
|
1165
|
+
logDebug: () => {},
|
|
1166
|
+
});
|
|
1167
|
+
|
|
1168
|
+
const deltas = io.emissions.filter((e: any) => e.event === "sync:delta");
|
|
1169
|
+
expect(deltas).toHaveLength(1);
|
|
1170
|
+
expect((deltas[0].payload as SyncDelta).method).toBe("update");
|
|
1171
|
+
});
|
|
1172
|
+
|
|
1173
|
+
it("skips hard deletes (no post-image)", async () => {
|
|
1174
|
+
const entry = ownerEntry();
|
|
1175
|
+
const io = makeTrackedIo();
|
|
1176
|
+
io.addSocketToRoom(syncRoomForStream("sockStuff|owner:user1"), {admin: false, id: "user1"});
|
|
1177
|
+
|
|
1178
|
+
await emitSyncDeltaForChange({
|
|
1179
|
+
change: makeChange({operationType: "delete"}),
|
|
1180
|
+
docId: "doc-1",
|
|
1181
|
+
entry,
|
|
1182
|
+
io,
|
|
1183
|
+
logDebug: () => {},
|
|
1184
|
+
});
|
|
1185
|
+
|
|
1186
|
+
expect(io.emissions.filter((e: any) => e.event === "sync:delta")).toHaveLength(0);
|
|
1187
|
+
});
|
|
1188
|
+
|
|
1189
|
+
it("applies the sync responseHandler to delta data", async () => {
|
|
1190
|
+
clearSyncRegistry();
|
|
1191
|
+
registerSync({
|
|
1192
|
+
config: {
|
|
1193
|
+
responseHandler: (doc: Record<string, unknown>) => ({onlyName: doc.name}),
|
|
1194
|
+
scope: {type: "owner"},
|
|
1195
|
+
},
|
|
1196
|
+
model: SockStuffModel as any,
|
|
1197
|
+
options: permissiveOptions,
|
|
1198
|
+
routePath: "/sockStuff",
|
|
1199
|
+
});
|
|
1200
|
+
const entry = findSyncEntryByCollectionTag("sockStuff") as SyncRegistryEntry;
|
|
1201
|
+
const io = makeTrackedIo();
|
|
1202
|
+
io.addSocketToRoom(syncRoomForStream("sockStuff|owner:user1"), {admin: false, id: "user1"});
|
|
1203
|
+
|
|
1204
|
+
await emitSyncDeltaForChange({
|
|
1205
|
+
change: makeChange({
|
|
1206
|
+
fullDocument: {_id: "doc-1", _syncSeq: 1, name: "shaped", ownerId: "user1", secret: "x"},
|
|
1207
|
+
}),
|
|
1208
|
+
docId: "doc-1",
|
|
1209
|
+
entry,
|
|
1210
|
+
io,
|
|
1211
|
+
logDebug: () => {},
|
|
1212
|
+
});
|
|
1213
|
+
|
|
1214
|
+
const delta = io.emissions.find((e: any) => e.event === "sync:delta")?.payload as SyncDelta;
|
|
1215
|
+
expect(delta.data).toEqual({onlyName: "shaped"});
|
|
1216
|
+
});
|
|
1217
|
+
});
|
|
1218
|
+
|
|
1219
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
1220
|
+
// sync:delta — change stream integration (requires a replica set, like
|
|
1221
|
+
// realtime.test.ts's change event integration block)
|
|
1222
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
1223
|
+
|
|
1224
|
+
const hasReplicaSet = async (): Promise<boolean> => {
|
|
1225
|
+
try {
|
|
1226
|
+
const admin = mongoose.connection.db?.admin();
|
|
1227
|
+
const status = await admin?.command({replSetGetStatus: 1});
|
|
1228
|
+
return Boolean(status?.ok);
|
|
1229
|
+
} catch {
|
|
1230
|
+
return false;
|
|
1231
|
+
}
|
|
1232
|
+
};
|
|
1233
|
+
|
|
1234
|
+
/**
|
|
1235
|
+
* Start the watcher and give the change-stream cursor a moment to open so writes made
|
|
1236
|
+
* immediately afterwards are not missed (change streams only deliver post-open events).
|
|
1237
|
+
*/
|
|
1238
|
+
const startWatcherAndSettle = async (io: any): Promise<void> => {
|
|
1239
|
+
startChangeStreamWatcher(io, {}, true);
|
|
1240
|
+
await new Promise((resolve) => setTimeout(resolve, 300));
|
|
1241
|
+
};
|
|
1242
|
+
|
|
1243
|
+
const waitForDelta = async (
|
|
1244
|
+
io: any,
|
|
1245
|
+
predicate: (delta: SyncDelta, emission: any) => boolean,
|
|
1246
|
+
timeoutMs = 5000
|
|
1247
|
+
): Promise<void> => {
|
|
1248
|
+
const start = Date.now();
|
|
1249
|
+
while (Date.now() - start < timeoutMs) {
|
|
1250
|
+
const match = io.emissions.some(
|
|
1251
|
+
(e: any) => e.event === "sync:delta" && predicate(e.payload as SyncDelta, e)
|
|
1252
|
+
);
|
|
1253
|
+
if (match) {
|
|
1254
|
+
return;
|
|
1255
|
+
}
|
|
1256
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
1257
|
+
}
|
|
1258
|
+
};
|
|
1259
|
+
|
|
1260
|
+
describe("sync:delta — change stream integration", () => {
|
|
1261
|
+
let replicaSetAvailable = false;
|
|
1262
|
+
|
|
1263
|
+
beforeAll(async () => {
|
|
1264
|
+
await setupDb();
|
|
1265
|
+
replicaSetAvailable = await hasReplicaSet();
|
|
1266
|
+
});
|
|
1267
|
+
|
|
1268
|
+
beforeEach(async () => {
|
|
1269
|
+
clearRealtimeRegistry();
|
|
1270
|
+
registerAll();
|
|
1271
|
+
await Promise.all([
|
|
1272
|
+
SockStuffModel.collection.deleteMany({}),
|
|
1273
|
+
SockProjectModel.collection.deleteMany({}),
|
|
1274
|
+
SyncCounter.deleteMany({}),
|
|
1275
|
+
]);
|
|
1276
|
+
});
|
|
1277
|
+
|
|
1278
|
+
afterEach(async () => {
|
|
1279
|
+
await stopChangeStreamWatcher();
|
|
1280
|
+
clearRealtimeRegistry();
|
|
1281
|
+
clearSyncRegistry();
|
|
1282
|
+
});
|
|
1283
|
+
|
|
1284
|
+
it("create, update, and soft delete each produce exactly one delta with correct seq and stream", async () => {
|
|
1285
|
+
if (!replicaSetAvailable) {
|
|
1286
|
+
return;
|
|
1287
|
+
}
|
|
1288
|
+
const io = makeTrackedIo();
|
|
1289
|
+
io.addSocketToRoom(syncRoomForStream("sockStuff|owner:cs-user"), {admin: false, id: "cs-user"});
|
|
1290
|
+
await startWatcherAndSettle(io);
|
|
1291
|
+
|
|
1292
|
+
const doc = await SockStuffModel.create({name: "cs-create", ownerId: "cs-user"});
|
|
1293
|
+
const docId = String(doc._id);
|
|
1294
|
+
await waitForDelta(io, (d) => d.id === docId && d.method === "create");
|
|
1295
|
+
|
|
1296
|
+
doc.name = "cs-updated";
|
|
1297
|
+
await doc.save();
|
|
1298
|
+
await waitForDelta(io, (d) => d.id === docId && d.method === "update");
|
|
1299
|
+
|
|
1300
|
+
doc.deleted = true;
|
|
1301
|
+
await doc.save();
|
|
1302
|
+
await waitForDelta(io, (d) => d.id === docId && d.method === "delete");
|
|
1303
|
+
|
|
1304
|
+
const deltas = io.emissions
|
|
1305
|
+
.filter((e: any) => e.event === "sync:delta")
|
|
1306
|
+
.map((e: any) => e.payload as SyncDelta);
|
|
1307
|
+
|
|
1308
|
+
const creates = deltas.filter((d) => d.method === "create");
|
|
1309
|
+
const updates = deltas.filter((d) => d.method === "update");
|
|
1310
|
+
const deletes = deltas.filter((d) => d.method === "delete");
|
|
1311
|
+
expect(creates).toHaveLength(1);
|
|
1312
|
+
expect(updates).toHaveLength(1);
|
|
1313
|
+
expect(deletes).toHaveLength(1);
|
|
1314
|
+
|
|
1315
|
+
expect(creates[0].seq).toBe(1);
|
|
1316
|
+
expect(updates[0].seq).toBe(2);
|
|
1317
|
+
expect(deletes[0].seq).toBe(3);
|
|
1318
|
+
for (const delta of deltas) {
|
|
1319
|
+
expect(delta.stream).toBe("sockStuff|owner:cs-user");
|
|
1320
|
+
expect(delta.collection).toBe("sockStuff");
|
|
1321
|
+
}
|
|
1322
|
+
expect(deletes[0].deleted).toBe(true);
|
|
1323
|
+
expect((deletes[0].data as any).name).toBe("cs-updated");
|
|
1324
|
+
});
|
|
1325
|
+
|
|
1326
|
+
it("a socket subscribed to tenant org1 never receives org2's delta", async () => {
|
|
1327
|
+
if (!replicaSetAvailable) {
|
|
1328
|
+
return;
|
|
1329
|
+
}
|
|
1330
|
+
const io = makeTrackedIo();
|
|
1331
|
+
io.addSocketToRoom(syncRoomForStream("sockProjects|tenant:org1"), {admin: false, id: "u1"});
|
|
1332
|
+
await startWatcherAndSettle(io);
|
|
1333
|
+
|
|
1334
|
+
const org1Doc = await SockProjectModel.create({orgId: "org1", title: "org1 project"});
|
|
1335
|
+
const org2Doc = await SockProjectModel.create({orgId: "org2", title: "org2 project"});
|
|
1336
|
+
await waitForDelta(io, (d) => d.id === String(org1Doc._id));
|
|
1337
|
+
// Give the org2 event a chance to (incorrectly) arrive too.
|
|
1338
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
1339
|
+
|
|
1340
|
+
const deltas = io.emissions
|
|
1341
|
+
.filter((e: any) => e.event === "sync:delta")
|
|
1342
|
+
.map((e: any) => e.payload as SyncDelta);
|
|
1343
|
+
expect(deltas.some((d) => d.id === String(org1Doc._id))).toBe(true);
|
|
1344
|
+
expect(deltas.some((d) => d.id === String(org2Doc._id))).toBe(false);
|
|
1345
|
+
expect(deltas.every((d) => d.stream === "sockProjects|tenant:org1")).toBe(true);
|
|
1346
|
+
});
|
|
1347
|
+
|
|
1348
|
+
it("scope move emits a tombstone to the old stream and a create to the new stream", async () => {
|
|
1349
|
+
if (!replicaSetAvailable) {
|
|
1350
|
+
return;
|
|
1351
|
+
}
|
|
1352
|
+
const io = makeTrackedIo();
|
|
1353
|
+
const oldRoom = syncRoomForStream("sockProjects|tenant:org1");
|
|
1354
|
+
const newRoom = syncRoomForStream("sockProjects|tenant:org2");
|
|
1355
|
+
io.addSocketToRoom(oldRoom, {admin: true, id: "admin"});
|
|
1356
|
+
io.addSocketToRoom(newRoom, {admin: true, id: "admin"});
|
|
1357
|
+
|
|
1358
|
+
const doc = await SockProjectModel.create({orgId: "org1", title: "moving project"});
|
|
1359
|
+
const docId = String(doc._id);
|
|
1360
|
+
|
|
1361
|
+
await startWatcherAndSettle(io);
|
|
1362
|
+
|
|
1363
|
+
await SockProjectModel.findOneAndUpdate({_id: doc._id}, {$set: {orgId: "org2"}});
|
|
1364
|
+
await waitForDelta(io, (d, e) => d.id === docId && e.room === newRoom);
|
|
1365
|
+
await waitForDelta(io, (d, e) => d.id === docId && e.room === oldRoom);
|
|
1366
|
+
|
|
1367
|
+
const deltas = io.emissions.filter(
|
|
1368
|
+
(e: any) => e.event === "sync:delta" && (e.payload as SyncDelta).id === docId
|
|
1369
|
+
);
|
|
1370
|
+
const tombstones = deltas.filter((e: any) => e.room === oldRoom);
|
|
1371
|
+
const creates = deltas.filter((e: any) => e.room === newRoom);
|
|
1372
|
+
expect(tombstones).toHaveLength(1);
|
|
1373
|
+
expect(creates).toHaveLength(1);
|
|
1374
|
+
|
|
1375
|
+
const tombstone = tombstones[0].payload as SyncDelta;
|
|
1376
|
+
expect(tombstone.method).toBe("delete");
|
|
1377
|
+
expect(tombstone.deleted).toBe(true);
|
|
1378
|
+
expect(tombstone.stream).toBe("sockProjects|tenant:org1");
|
|
1379
|
+
expect(tombstone.data).toBeUndefined();
|
|
1380
|
+
|
|
1381
|
+
const create = creates[0].payload as SyncDelta;
|
|
1382
|
+
expect(create.method).toBe("create");
|
|
1383
|
+
expect(create.stream).toBe("sockProjects|tenant:org2");
|
|
1384
|
+
expect((create.data as any).orgId).toBe("org2");
|
|
1385
|
+
});
|
|
1386
|
+
|
|
1387
|
+
it("a model with both realtime and sync configs emits both event types", async () => {
|
|
1388
|
+
if (!replicaSetAvailable) {
|
|
1389
|
+
return;
|
|
1390
|
+
}
|
|
1391
|
+
registerRealtime({
|
|
1392
|
+
collectionName: SockStuffModel.collection.collectionName,
|
|
1393
|
+
config: {methods: ["create", "update", "delete"], roomStrategy: "model"},
|
|
1394
|
+
modelName: "SockStuff",
|
|
1395
|
+
options: permissiveOptions,
|
|
1396
|
+
routePath: "/sockStuff",
|
|
1397
|
+
});
|
|
1398
|
+
|
|
1399
|
+
const io = makeTrackedIo();
|
|
1400
|
+
io.addSocketToRoom("model:sockStuff", {admin: true, id: "admin"});
|
|
1401
|
+
io.addSocketToRoom(syncRoomForStream("sockStuff|owner:both-user"), {
|
|
1402
|
+
admin: false,
|
|
1403
|
+
id: "both-user",
|
|
1404
|
+
});
|
|
1405
|
+
await startWatcherAndSettle(io);
|
|
1406
|
+
|
|
1407
|
+
const doc = await SockStuffModel.create({name: "both", ownerId: "both-user"});
|
|
1408
|
+
const docId = String(doc._id);
|
|
1409
|
+
await waitForDelta(io, (d) => d.id === docId);
|
|
1410
|
+
|
|
1411
|
+
const legacy = io.emissions.filter(
|
|
1412
|
+
(e: any) => e.event === "sync" && e.payload?.id === docId && e.payload?.method === "create"
|
|
1413
|
+
);
|
|
1414
|
+
const deltas = io.emissions.filter(
|
|
1415
|
+
(e: any) => e.event === "sync:delta" && (e.payload as SyncDelta).id === docId
|
|
1416
|
+
);
|
|
1417
|
+
expect(legacy.length).toBeGreaterThanOrEqual(1);
|
|
1418
|
+
expect(deltas).toHaveLength(1);
|
|
1419
|
+
expect((deltas[0].payload as SyncDelta).seq).toBe(1);
|
|
1420
|
+
});
|
|
1421
|
+
|
|
1422
|
+
it("a sync-only model emits deltas even without a realtime registry entry", async () => {
|
|
1423
|
+
if (!replicaSetAvailable) {
|
|
1424
|
+
return;
|
|
1425
|
+
}
|
|
1426
|
+
const io = makeTrackedIo();
|
|
1427
|
+
io.addSocketToRoom(syncRoomForStream("sockStuff|owner:only-user"), {
|
|
1428
|
+
admin: false,
|
|
1429
|
+
id: "only-user",
|
|
1430
|
+
});
|
|
1431
|
+
await startWatcherAndSettle(io);
|
|
1432
|
+
|
|
1433
|
+
const doc = await SockStuffModel.create({name: "sync only", ownerId: "only-user"});
|
|
1434
|
+
await waitForDelta(io, (d) => d.id === String(doc._id));
|
|
1435
|
+
|
|
1436
|
+
const deltas = io.emissions.filter((e: any) => e.event === "sync:delta");
|
|
1437
|
+
expect(deltas).toHaveLength(1);
|
|
1438
|
+
expect(io.emissions.filter((e: any) => e.event === "sync")).toHaveLength(0);
|
|
1439
|
+
});
|
|
1440
|
+
});
|