@terreno/api 0.31.0 → 56.0.0-beta.2
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/dist/api.d.ts +10 -0
- package/dist/api.js +110 -361
- package/dist/auth.d.ts +26 -0
- package/dist/auth.js +121 -26
- package/dist/betterAuth.d.ts +5 -0
- package/dist/betterAuthSetup.js +23 -4
- package/dist/docLoader.js +12 -9
- package/dist/errors.d.ts +13 -0
- package/dist/errors.js +29 -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 +13 -0
- package/dist/plugins.js +47 -1
- package/dist/realtime/changeStreamWatcher.d.ts +100 -3
- package/dist/realtime/changeStreamWatcher.js +542 -137
- package/dist/realtime/realtimeApp.d.ts +2 -0
- package/dist/realtime/realtimeApp.js +83 -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 +54 -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 +899 -0
- package/dist/sync/types.d.ts +254 -0
- package/dist/sync/types.js +9 -0
- package/dist/terrenoApp.js +90 -27
- package/dist/vendor/wesleytodd-openapi/index.d.ts +1 -1
- package/dist/vendor/wesleytodd-openapi/lib/ui.d.ts +2 -1
- package/package.json +7 -6
- package/src/__tests__/openApiCompat.test.ts +20 -0
- package/src/api.errors.test.ts +32 -23
- package/src/api.test.ts +12 -0
- package/src/api.ts +87 -296
- package/src/auth.test.ts +202 -0
- package/src/auth.ts +134 -23
- package/src/betterAuth.ts +6 -0
- package/src/betterAuthSetup.test.ts +34 -0
- package/src/betterAuthSetup.ts +20 -1
- package/src/configuration.test.ts +59 -38
- package/src/configurationPlugin.test.ts +72 -42
- package/src/docLoader.ts +3 -1
- package/src/errors.ts +33 -0
- package/src/expressServer.test.ts +7 -1
- package/src/index.ts +42 -0
- package/src/middleware.test.ts +56 -1
- package/src/middleware.ts +15 -0
- package/src/openApiCompat.ts +99 -45
- package/src/permissions.test.ts +101 -17
- package/src/permissions.ts +49 -0
- package/src/plugins.test.ts +64 -0
- package/src/plugins.ts +56 -0
- package/src/realtime/changeStreamWatcher.ts +552 -114
- package/src/realtime/realtime.test.ts +157 -0
- package/src/realtime/realtimeApp.ts +82 -14
- package/src/realtime/realtimeAppSetup.test.ts +25 -27
- 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 +54 -0
- package/src/secretProviders.test.ts +7 -1
- package/src/secretProviders.ts +15 -3
- package/src/secretProvidersGcpClient.test.ts +66 -0
- package/src/sync/ensureSyncIndexes.test.ts +144 -0
- package/src/sync/executors.test.ts +882 -0
- package/src/sync/executors.ts +705 -0
- package/src/sync/integration.test.ts +1160 -0
- package/src/sync/loadHarness.ts +618 -0
- package/src/sync/models.ts +641 -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 +730 -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/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/dist/{__tests__/openApiCompat.test.d.ts → sync/loadHarness.d.ts} +0 -0
|
@@ -0,0 +1,1252 @@
|
|
|
1
|
+
// noExplicitAny: test model typing
|
|
2
|
+
// biome-ignore-all lint/suspicious/noExplicitAny: test model typing
|
|
3
|
+
import {beforeAll, beforeEach, describe, expect, it} from "bun:test";
|
|
4
|
+
import mongoose, {model, Schema} from "mongoose";
|
|
5
|
+
import type {ModelRouterOptions} from "../api";
|
|
6
|
+
import type {User} from "../auth";
|
|
7
|
+
import {APIError} from "../errors";
|
|
8
|
+
import {Permissions} from "../permissions";
|
|
9
|
+
import {createdUpdatedPlugin, type IsDeleted, isDeletedPlugin} from "../plugins";
|
|
10
|
+
import {setupDb} from "../tests";
|
|
11
|
+
import {computeStableFrontier, SyncCounter, SyncMutation} from "./models";
|
|
12
|
+
import {
|
|
13
|
+
applySyncMutation,
|
|
14
|
+
applySyncMutationBatch,
|
|
15
|
+
MAX_SYNC_MUTATIONS_PER_BATCH,
|
|
16
|
+
type SyncMutationOutcome,
|
|
17
|
+
validateSyncMutationBatch,
|
|
18
|
+
} from "./mutationHandler";
|
|
19
|
+
import {clearSyncRegistry, registerSync} from "./registry";
|
|
20
|
+
import {syncPlugin} from "./syncSeqPlugin";
|
|
21
|
+
import type {SyncMutateBatchResponse, SyncMutateRequest} from "./types";
|
|
22
|
+
|
|
23
|
+
interface MutStuff extends IsDeleted {
|
|
24
|
+
_id: string;
|
|
25
|
+
name: string;
|
|
26
|
+
ownerId: string;
|
|
27
|
+
created: Date;
|
|
28
|
+
_syncSeq?: number;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const mutStuffSchema = new Schema<MutStuff>({
|
|
32
|
+
name: {description: "The name of the item", required: true, type: String},
|
|
33
|
+
ownerId: {description: "The user who owns this item", type: String},
|
|
34
|
+
});
|
|
35
|
+
mutStuffSchema.plugin(isDeletedPlugin);
|
|
36
|
+
mutStuffSchema.plugin(createdUpdatedPlugin);
|
|
37
|
+
mutStuffSchema.plugin(syncPlugin);
|
|
38
|
+
const MutStuffModel = model<MutStuff>("MutStuff", mutStuffSchema);
|
|
39
|
+
|
|
40
|
+
const owner = {_id: "mut-owner", admin: false, id: "mut-owner"} as unknown as User;
|
|
41
|
+
const stranger = {_id: "mut-stranger", admin: false, id: "mut-stranger"} as unknown as User;
|
|
42
|
+
|
|
43
|
+
const ownerOptions = {
|
|
44
|
+
permissions: {
|
|
45
|
+
create: [Permissions.IsAuthenticated],
|
|
46
|
+
delete: [Permissions.IsOwner],
|
|
47
|
+
list: [Permissions.IsAny],
|
|
48
|
+
read: [Permissions.IsAny],
|
|
49
|
+
update: [Permissions.IsOwner],
|
|
50
|
+
},
|
|
51
|
+
} as unknown as ModelRouterOptions<any>;
|
|
52
|
+
|
|
53
|
+
const registerMutStuff = (overrides: Partial<Record<string, unknown>> = {}): void => {
|
|
54
|
+
clearSyncRegistry();
|
|
55
|
+
registerSync({
|
|
56
|
+
config: {scope: {type: "owner"}, ...(overrides.config as object)},
|
|
57
|
+
model: MutStuffModel as any,
|
|
58
|
+
options: (overrides.options as ModelRouterOptions<any>) ?? ownerOptions,
|
|
59
|
+
routePath: "/mutStuff",
|
|
60
|
+
});
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const expectAck = (outcome: SyncMutationOutcome) => {
|
|
64
|
+
expect(outcome.type).toBe("ack");
|
|
65
|
+
if (outcome.type !== "ack") {
|
|
66
|
+
throw new Error("expected ack");
|
|
67
|
+
}
|
|
68
|
+
return outcome.ack;
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
const expectNack = (outcome: SyncMutationOutcome) => {
|
|
72
|
+
expect(outcome.type).toBe("nack");
|
|
73
|
+
if (outcome.type !== "nack") {
|
|
74
|
+
throw new Error("expected nack");
|
|
75
|
+
}
|
|
76
|
+
return outcome.nack;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
describe("applySyncMutation", () => {
|
|
80
|
+
beforeAll(async () => {
|
|
81
|
+
await setupDb();
|
|
82
|
+
// The shared test database can be dropped by another test file mid-suite
|
|
83
|
+
// (configurationPlugin.test.ts drops it in an afterAll); rebuild the unique indexes
|
|
84
|
+
// the idempotency tests depend on.
|
|
85
|
+
await Promise.all([SyncCounter.ensureIndexes(), SyncMutation.ensureIndexes()]);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
beforeEach(async () => {
|
|
89
|
+
registerMutStuff();
|
|
90
|
+
await Promise.all([
|
|
91
|
+
MutStuffModel.collection.deleteMany({}),
|
|
92
|
+
SyncCounter.deleteMany({}),
|
|
93
|
+
SyncMutation.deleteMany({}),
|
|
94
|
+
]);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
describe("successful mutations", () => {
|
|
98
|
+
it("applies a create and acks with the new id and seq", async () => {
|
|
99
|
+
const outcome = await applySyncMutation({
|
|
100
|
+
mutation: {
|
|
101
|
+
collection: "mutStuff",
|
|
102
|
+
data: {name: "created", ownerId: owner.id},
|
|
103
|
+
mutationId: "m-create-1",
|
|
104
|
+
operation: "create",
|
|
105
|
+
},
|
|
106
|
+
user: owner,
|
|
107
|
+
});
|
|
108
|
+
const ack = expectAck(outcome);
|
|
109
|
+
expect(ack.mutationId).toBe("m-create-1");
|
|
110
|
+
expect(ack.seq).toBe(1);
|
|
111
|
+
|
|
112
|
+
const saved = await MutStuffModel.findById(ack.id);
|
|
113
|
+
expect(saved?.name).toBe("created");
|
|
114
|
+
expect(saved?._syncSeq).toBe(1);
|
|
115
|
+
|
|
116
|
+
const row = await SyncMutation.findOne({mutationId: "m-create-1"});
|
|
117
|
+
expect(row?.status).toBe("applied");
|
|
118
|
+
expect(row?.resultId).toBe(ack.id);
|
|
119
|
+
expect(row?.resultSeq).toBe(1);
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
it("honors a client-generated id on create", async () => {
|
|
123
|
+
const id = new mongoose.Types.ObjectId().toString();
|
|
124
|
+
const outcome = await applySyncMutation({
|
|
125
|
+
mutation: {
|
|
126
|
+
collection: "mutStuff",
|
|
127
|
+
data: {name: "client id", ownerId: owner.id},
|
|
128
|
+
id,
|
|
129
|
+
mutationId: "m-create-id",
|
|
130
|
+
operation: "create",
|
|
131
|
+
},
|
|
132
|
+
user: owner,
|
|
133
|
+
});
|
|
134
|
+
expect(expectAck(outcome).id).toBe(id);
|
|
135
|
+
expect(await MutStuffModel.findById(id)).not.toBeNull();
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
it("applies an update with a matching baseVersion and advances the seq", async () => {
|
|
139
|
+
const doc = await MutStuffModel.create({name: "original", ownerId: owner.id});
|
|
140
|
+
expect(doc._syncSeq).toBe(1);
|
|
141
|
+
|
|
142
|
+
const outcome = await applySyncMutation({
|
|
143
|
+
mutation: {
|
|
144
|
+
baseVersion: 1,
|
|
145
|
+
collection: "mutStuff",
|
|
146
|
+
data: {name: "changed"},
|
|
147
|
+
id: doc._id.toString(),
|
|
148
|
+
mutationId: "m-update-1",
|
|
149
|
+
operation: "update",
|
|
150
|
+
},
|
|
151
|
+
user: owner,
|
|
152
|
+
});
|
|
153
|
+
const ack = expectAck(outcome);
|
|
154
|
+
expect(ack.id).toBe(doc._id.toString());
|
|
155
|
+
expect(ack.seq).toBe(2);
|
|
156
|
+
const saved = await MutStuffModel.findById(doc._id);
|
|
157
|
+
expect(saved?.name).toBe("changed");
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
it("applies a delete as a soft-delete tombstone and acks with the new seq", async () => {
|
|
161
|
+
const doc = await MutStuffModel.create({name: "victim", ownerId: owner.id});
|
|
162
|
+
const outcome = await applySyncMutation({
|
|
163
|
+
mutation: {
|
|
164
|
+
collection: "mutStuff",
|
|
165
|
+
id: doc._id.toString(),
|
|
166
|
+
mutationId: "m-delete-1",
|
|
167
|
+
operation: "delete",
|
|
168
|
+
},
|
|
169
|
+
user: owner,
|
|
170
|
+
});
|
|
171
|
+
const ack = expectAck(outcome);
|
|
172
|
+
expect(ack.seq).toBe(2);
|
|
173
|
+
const tombstones = await MutStuffModel.find({_id: doc._id, deleted: true});
|
|
174
|
+
expect(tombstones).toHaveLength(1);
|
|
175
|
+
});
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
describe("idempotency", () => {
|
|
179
|
+
it("returns the recorded ack for a duplicate mutationId without re-applying", async () => {
|
|
180
|
+
const mutation: SyncMutateRequest = {
|
|
181
|
+
collection: "mutStuff",
|
|
182
|
+
data: {name: "once", ownerId: owner.id},
|
|
183
|
+
mutationId: "m-dup-1",
|
|
184
|
+
operation: "create",
|
|
185
|
+
};
|
|
186
|
+
const first = expectAck(await applySyncMutation({mutation, user: owner}));
|
|
187
|
+
const second = expectAck(await applySyncMutation({mutation, user: owner}));
|
|
188
|
+
|
|
189
|
+
expect(second).toEqual(first);
|
|
190
|
+
expect(await MutStuffModel.countDocuments({name: "once"})).toBe(1);
|
|
191
|
+
expect(await SyncMutation.countDocuments({mutationId: "m-dup-1"})).toBe(1);
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
it("applies exactly once when two deliveries race on the same mutationId", async () => {
|
|
195
|
+
const mutation: SyncMutateRequest = {
|
|
196
|
+
collection: "mutStuff",
|
|
197
|
+
data: {name: "raced", ownerId: owner.id},
|
|
198
|
+
mutationId: "m-race-1",
|
|
199
|
+
operation: "create",
|
|
200
|
+
};
|
|
201
|
+
const [a, b] = await Promise.all([
|
|
202
|
+
applySyncMutation({mutation, user: owner}),
|
|
203
|
+
applySyncMutation({mutation, user: owner}),
|
|
204
|
+
]);
|
|
205
|
+
const ackA = expectAck(a);
|
|
206
|
+
const ackB = expectAck(b);
|
|
207
|
+
expect(ackA).toEqual(ackB);
|
|
208
|
+
expect(await MutStuffModel.countDocuments({name: "raced"})).toBe(1);
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
it("returns the recorded conflict nack for a duplicate conflicted mutation", async () => {
|
|
212
|
+
const doc = await MutStuffModel.create({name: "server v1", ownerId: owner.id});
|
|
213
|
+
doc.name = "server v2";
|
|
214
|
+
await doc.save(); // seq 2
|
|
215
|
+
|
|
216
|
+
const mutation: SyncMutateRequest = {
|
|
217
|
+
baseVersion: 1,
|
|
218
|
+
collection: "mutStuff",
|
|
219
|
+
data: {name: "stale client"},
|
|
220
|
+
id: doc._id.toString(),
|
|
221
|
+
mutationId: "m-dup-conflict",
|
|
222
|
+
operation: "update",
|
|
223
|
+
};
|
|
224
|
+
const first = expectNack(await applySyncMutation({mutation, user: owner}));
|
|
225
|
+
const second = expectNack(await applySyncMutation({mutation, user: owner}));
|
|
226
|
+
|
|
227
|
+
expect(first.code).toBe("conflict");
|
|
228
|
+
expect(second.code).toBe("conflict");
|
|
229
|
+
expect(second.serverSeq).toBe(first.serverSeq);
|
|
230
|
+
expect((second.serverDoc as {name: string}).name).toBe("server v2");
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
it("returns the recorded nack for a duplicate failed mutation", async () => {
|
|
234
|
+
const mutation: SyncMutateRequest = {
|
|
235
|
+
collection: "mutStuff",
|
|
236
|
+
data: {ownerId: owner.id}, // missing required name
|
|
237
|
+
mutationId: "m-dup-failed",
|
|
238
|
+
operation: "create",
|
|
239
|
+
};
|
|
240
|
+
const first = expectNack(await applySyncMutation({mutation, user: owner}));
|
|
241
|
+
expect(first.code).toBe("validation");
|
|
242
|
+
|
|
243
|
+
const second = expectNack(await applySyncMutation({mutation, user: owner}));
|
|
244
|
+
expect(second.code).toBe("validation");
|
|
245
|
+
expect(second.message).toBe(first.message);
|
|
246
|
+
expect(await SyncMutation.countDocuments({mutationId: "m-dup-failed"})).toBe(1);
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
it("nacks unauthorized when the mutationId was claimed by another user", async () => {
|
|
250
|
+
const mutation: SyncMutateRequest = {
|
|
251
|
+
collection: "mutStuff",
|
|
252
|
+
data: {name: "mine", ownerId: owner.id},
|
|
253
|
+
mutationId: "m-cross-user",
|
|
254
|
+
operation: "create",
|
|
255
|
+
};
|
|
256
|
+
expectAck(await applySyncMutation({mutation, user: owner}));
|
|
257
|
+
|
|
258
|
+
const nack = expectNack(await applySyncMutation({mutation, user: stranger}));
|
|
259
|
+
expect(nack.code).toBe("unauthorized");
|
|
260
|
+
expect(nack.message).toContain("another user");
|
|
261
|
+
// The original outcome is untouched.
|
|
262
|
+
const row = await SyncMutation.findOne({mutationId: "m-cross-user"});
|
|
263
|
+
expect(row?.status).toBe("applied");
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
it("nacks error when a claimed mutation stays pending past the poll timeout", async () => {
|
|
267
|
+
await SyncMutation.create({
|
|
268
|
+
mutationId: "m-stuck",
|
|
269
|
+
status: "pending",
|
|
270
|
+
userId: String(owner.id),
|
|
271
|
+
});
|
|
272
|
+
const nack = expectNack(
|
|
273
|
+
await applySyncMutation({
|
|
274
|
+
mutation: {
|
|
275
|
+
collection: "mutStuff",
|
|
276
|
+
data: {name: "stuck", ownerId: owner.id},
|
|
277
|
+
mutationId: "m-stuck",
|
|
278
|
+
operation: "create",
|
|
279
|
+
},
|
|
280
|
+
user: owner,
|
|
281
|
+
})
|
|
282
|
+
);
|
|
283
|
+
expect(nack.code).toBe("error");
|
|
284
|
+
expect(nack.message).toContain("still in flight");
|
|
285
|
+
// The row is left pending for the owning delivery to finalize.
|
|
286
|
+
const row = await SyncMutation.findOne({mutationId: "m-stuck"});
|
|
287
|
+
expect(row?.status).toBe("pending");
|
|
288
|
+
expect(await MutStuffModel.countDocuments({name: "stuck"})).toBe(0);
|
|
289
|
+
});
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
describe("C5 lease takeover (FIX 6)", () => {
|
|
293
|
+
/** Simulate a crash: a `pending` row whose claimedAt is older than the lease. */
|
|
294
|
+
const createStalePendingRow = async (mutationId: string, staleForMs: number): Promise<void> => {
|
|
295
|
+
await SyncMutation.create({
|
|
296
|
+
claimedAt: new Date(Date.now() - staleForMs),
|
|
297
|
+
mutationId,
|
|
298
|
+
status: "pending",
|
|
299
|
+
userId: String(owner.id),
|
|
300
|
+
});
|
|
301
|
+
};
|
|
302
|
+
|
|
303
|
+
it("retries and succeeds after the lease expires when the write never landed (create)", async () => {
|
|
304
|
+
await createStalePendingRow("m-lease-create", 90_000);
|
|
305
|
+
const ack = expectAck(
|
|
306
|
+
await applySyncMutation({
|
|
307
|
+
mutation: {
|
|
308
|
+
collection: "mutStuff",
|
|
309
|
+
data: {name: "recovered", ownerId: owner.id},
|
|
310
|
+
mutationId: "m-lease-create",
|
|
311
|
+
operation: "create",
|
|
312
|
+
},
|
|
313
|
+
user: owner,
|
|
314
|
+
})
|
|
315
|
+
);
|
|
316
|
+
expect(ack.seq).toBe(1);
|
|
317
|
+
expect(await MutStuffModel.countDocuments({name: "recovered"})).toBe(1);
|
|
318
|
+
const row = await SyncMutation.findOne({mutationId: "m-lease-create"});
|
|
319
|
+
expect(row?.status).toBe("applied");
|
|
320
|
+
});
|
|
321
|
+
|
|
322
|
+
it("does NOT take over a pending row within the lease window (regression guard)", async () => {
|
|
323
|
+
await createStalePendingRow("m-lease-fresh", 5_000); // well under SYNC_MUTATION_LEASE_MS
|
|
324
|
+
const nack = expectNack(
|
|
325
|
+
await applySyncMutation({
|
|
326
|
+
mutation: {
|
|
327
|
+
collection: "mutStuff",
|
|
328
|
+
data: {name: "should not apply", ownerId: owner.id},
|
|
329
|
+
mutationId: "m-lease-fresh",
|
|
330
|
+
operation: "create",
|
|
331
|
+
},
|
|
332
|
+
user: owner,
|
|
333
|
+
})
|
|
334
|
+
);
|
|
335
|
+
expect(nack.code).toBe("error");
|
|
336
|
+
expect(nack.message).toContain("still in flight");
|
|
337
|
+
expect(await MutStuffModel.countDocuments({name: "should not apply"})).toBe(0);
|
|
338
|
+
});
|
|
339
|
+
|
|
340
|
+
it("create: tolerates the write having already landed (E11000 on the same _id) and reads back the doc as the ack", async () => {
|
|
341
|
+
const entityId = new mongoose.Types.ObjectId().toHexString();
|
|
342
|
+
// Simulate the crash: the doc write from the FIRST attempt landed, but
|
|
343
|
+
// the process died before finalizing the ledger row `applied`.
|
|
344
|
+
await MutStuffModel.create({_id: entityId, name: "already written", ownerId: owner.id});
|
|
345
|
+
await createStalePendingRow("m-lease-create-e11000", 90_000);
|
|
346
|
+
|
|
347
|
+
const ack = expectAck(
|
|
348
|
+
await applySyncMutation({
|
|
349
|
+
mutation: {
|
|
350
|
+
collection: "mutStuff",
|
|
351
|
+
data: {name: "already written", ownerId: owner.id},
|
|
352
|
+
id: entityId,
|
|
353
|
+
mutationId: "m-lease-create-e11000",
|
|
354
|
+
operation: "create",
|
|
355
|
+
},
|
|
356
|
+
user: owner,
|
|
357
|
+
})
|
|
358
|
+
);
|
|
359
|
+
expect(ack.id).toBe(entityId);
|
|
360
|
+
expect(ack.seq).toBe(1);
|
|
361
|
+
// Exactly one document — the retry did not double-create.
|
|
362
|
+
expect(await MutStuffModel.countDocuments({_id: entityId})).toBe(1);
|
|
363
|
+
const row = await SyncMutation.findOne({mutationId: "m-lease-create-e11000"});
|
|
364
|
+
expect(row?.status).toBe("applied");
|
|
365
|
+
expect(row?.resultId).toBe(entityId);
|
|
366
|
+
});
|
|
367
|
+
|
|
368
|
+
it("update: tolerates the write having already landed (seq already advanced by exactly this mutation) and reads back the doc as the ack", async () => {
|
|
369
|
+
const doc = await MutStuffModel.create({name: "v1", ownerId: owner.id});
|
|
370
|
+
// Simulate the crash: the update write from the FIRST attempt landed
|
|
371
|
+
// (seq advanced 1 -> 2 with the new name), but the ledger row was
|
|
372
|
+
// never finalized.
|
|
373
|
+
doc.name = "v2 (already written)";
|
|
374
|
+
await doc.save();
|
|
375
|
+
expect(doc._syncSeq).toBe(2);
|
|
376
|
+
await createStalePendingRow("m-lease-update", 90_000);
|
|
377
|
+
|
|
378
|
+
const ack = expectAck(
|
|
379
|
+
await applySyncMutation({
|
|
380
|
+
mutation: {
|
|
381
|
+
baseVersion: 1, // the client's original (pre-write) baseVersion
|
|
382
|
+
collection: "mutStuff",
|
|
383
|
+
data: {name: "v2 (already written)"},
|
|
384
|
+
id: doc._id.toString(),
|
|
385
|
+
mutationId: "m-lease-update",
|
|
386
|
+
operation: "update",
|
|
387
|
+
},
|
|
388
|
+
user: owner,
|
|
389
|
+
})
|
|
390
|
+
);
|
|
391
|
+
expect(ack.seq).toBe(2);
|
|
392
|
+
const saved = await MutStuffModel.findById(doc._id);
|
|
393
|
+
expect(saved?.name).toBe("v2 (already written)");
|
|
394
|
+
expect(saved?._syncSeq).toBe(2); // not bumped again
|
|
395
|
+
const row = await SyncMutation.findOne({mutationId: "m-lease-update"});
|
|
396
|
+
expect(row?.status).toBe("applied");
|
|
397
|
+
});
|
|
398
|
+
|
|
399
|
+
it("update: a GENUINE conflict (someone else wrote, not this mutation) still nacks even via lease takeover", async () => {
|
|
400
|
+
const doc = await MutStuffModel.create({name: "v1", ownerId: owner.id});
|
|
401
|
+
doc.name = "someone else's edit";
|
|
402
|
+
await doc.save(); // seq 2, but NOT from this mutation
|
|
403
|
+
await createStalePendingRow("m-lease-genuine-conflict", 90_000);
|
|
404
|
+
|
|
405
|
+
const nack = expectNack(
|
|
406
|
+
await applySyncMutation({
|
|
407
|
+
mutation: {
|
|
408
|
+
baseVersion: 1,
|
|
409
|
+
collection: "mutStuff",
|
|
410
|
+
data: {name: "my conflicting edit"},
|
|
411
|
+
id: doc._id.toString(),
|
|
412
|
+
mutationId: "m-lease-genuine-conflict",
|
|
413
|
+
operation: "update",
|
|
414
|
+
},
|
|
415
|
+
user: owner,
|
|
416
|
+
})
|
|
417
|
+
);
|
|
418
|
+
expect(nack.code).toBe("conflict");
|
|
419
|
+
expect(nack.serverSeq).toBe(2);
|
|
420
|
+
});
|
|
421
|
+
|
|
422
|
+
it("replay after lease expiry returns the recorded ack for a subsequent duplicate delivery", async () => {
|
|
423
|
+
await createStalePendingRow("m-lease-replay", 90_000);
|
|
424
|
+
const first = expectAck(
|
|
425
|
+
await applySyncMutation({
|
|
426
|
+
mutation: {
|
|
427
|
+
collection: "mutStuff",
|
|
428
|
+
data: {name: "replay me", ownerId: owner.id},
|
|
429
|
+
mutationId: "m-lease-replay",
|
|
430
|
+
operation: "create",
|
|
431
|
+
},
|
|
432
|
+
user: owner,
|
|
433
|
+
})
|
|
434
|
+
);
|
|
435
|
+
// A later duplicate delivery of the SAME mutationId (e.g. the
|
|
436
|
+
// original client's transport retry finally reaches the server) reads
|
|
437
|
+
// back the exact recorded outcome instead of double-applying.
|
|
438
|
+
const second = expectAck(
|
|
439
|
+
await applySyncMutation({
|
|
440
|
+
mutation: {
|
|
441
|
+
collection: "mutStuff",
|
|
442
|
+
data: {name: "replay me", ownerId: owner.id},
|
|
443
|
+
mutationId: "m-lease-replay",
|
|
444
|
+
operation: "create",
|
|
445
|
+
},
|
|
446
|
+
user: owner,
|
|
447
|
+
})
|
|
448
|
+
);
|
|
449
|
+
expect(second).toEqual(first);
|
|
450
|
+
expect(await MutStuffModel.countDocuments({name: "replay me"})).toBe(1);
|
|
451
|
+
});
|
|
452
|
+
|
|
453
|
+
it("post-hook throw after a committed write: doc changed AND ack returned AND ledger applied (M5)", async () => {
|
|
454
|
+
registerMutStuff({
|
|
455
|
+
options: {
|
|
456
|
+
...ownerOptions,
|
|
457
|
+
postCreate: () => {
|
|
458
|
+
throw new Error("webhook unreachable");
|
|
459
|
+
},
|
|
460
|
+
},
|
|
461
|
+
});
|
|
462
|
+
const outcome = await applySyncMutation({
|
|
463
|
+
mutation: {
|
|
464
|
+
collection: "mutStuff",
|
|
465
|
+
data: {name: "post-hook throws", ownerId: owner.id},
|
|
466
|
+
mutationId: "m-posthook-throw",
|
|
467
|
+
operation: "create",
|
|
468
|
+
},
|
|
469
|
+
user: owner,
|
|
470
|
+
});
|
|
471
|
+
// Still a full ack, not a nack — the write committed regardless of the
|
|
472
|
+
// post-hook's fate.
|
|
473
|
+
const ack = expectAck(outcome);
|
|
474
|
+
expect(ack.warning).toContain("webhook unreachable");
|
|
475
|
+
expect(await MutStuffModel.countDocuments({name: "post-hook throws"})).toBe(1);
|
|
476
|
+
const row = await SyncMutation.findOne({mutationId: "m-posthook-throw"});
|
|
477
|
+
expect(row?.status).toBe("applied");
|
|
478
|
+
});
|
|
479
|
+
|
|
480
|
+
it("post-hook throw on update also returns ack+warning with the ledger applied", async () => {
|
|
481
|
+
const doc = await MutStuffModel.create({name: "before", ownerId: owner.id});
|
|
482
|
+
registerMutStuff({
|
|
483
|
+
options: {
|
|
484
|
+
...ownerOptions,
|
|
485
|
+
postUpdate: () => {
|
|
486
|
+
throw new Error("notification failed");
|
|
487
|
+
},
|
|
488
|
+
},
|
|
489
|
+
});
|
|
490
|
+
const outcome = await applySyncMutation({
|
|
491
|
+
mutation: {
|
|
492
|
+
baseVersion: 1,
|
|
493
|
+
collection: "mutStuff",
|
|
494
|
+
data: {name: "after"},
|
|
495
|
+
id: doc._id.toString(),
|
|
496
|
+
mutationId: "m-posthook-update-throw",
|
|
497
|
+
operation: "update",
|
|
498
|
+
},
|
|
499
|
+
user: owner,
|
|
500
|
+
});
|
|
501
|
+
const ack = expectAck(outcome);
|
|
502
|
+
expect(ack.warning).toContain("notification failed");
|
|
503
|
+
const saved = await MutStuffModel.findById(doc._id);
|
|
504
|
+
expect(saved?.name).toBe("after");
|
|
505
|
+
const row = await SyncMutation.findOne({mutationId: "m-posthook-update-throw"});
|
|
506
|
+
expect(row?.status).toBe("applied");
|
|
507
|
+
});
|
|
508
|
+
|
|
509
|
+
it("no warning field when the post-hook succeeds", async () => {
|
|
510
|
+
let called = false;
|
|
511
|
+
registerMutStuff({
|
|
512
|
+
options: {
|
|
513
|
+
...ownerOptions,
|
|
514
|
+
postCreate: () => {
|
|
515
|
+
called = true;
|
|
516
|
+
},
|
|
517
|
+
},
|
|
518
|
+
});
|
|
519
|
+
const ack = expectAck(
|
|
520
|
+
await applySyncMutation({
|
|
521
|
+
mutation: {
|
|
522
|
+
collection: "mutStuff",
|
|
523
|
+
data: {name: "clean post-hook", ownerId: owner.id},
|
|
524
|
+
mutationId: "m-posthook-ok",
|
|
525
|
+
operation: "create",
|
|
526
|
+
},
|
|
527
|
+
user: owner,
|
|
528
|
+
})
|
|
529
|
+
);
|
|
530
|
+
expect(called).toBe(true);
|
|
531
|
+
expect(ack.warning).toBeUndefined();
|
|
532
|
+
});
|
|
533
|
+
});
|
|
534
|
+
|
|
535
|
+
describe("conflicts", () => {
|
|
536
|
+
it("nacks conflict with the canonical server doc on a stale baseVersion", async () => {
|
|
537
|
+
const doc = await MutStuffModel.create({name: "v1", ownerId: owner.id});
|
|
538
|
+
doc.name = "v2";
|
|
539
|
+
await doc.save(); // seq 2
|
|
540
|
+
|
|
541
|
+
const nack = expectNack(
|
|
542
|
+
await applySyncMutation({
|
|
543
|
+
mutation: {
|
|
544
|
+
baseVersion: 1,
|
|
545
|
+
collection: "mutStuff",
|
|
546
|
+
data: {name: "stale"},
|
|
547
|
+
id: doc._id.toString(),
|
|
548
|
+
mutationId: "m-conflict-1",
|
|
549
|
+
operation: "update",
|
|
550
|
+
},
|
|
551
|
+
user: owner,
|
|
552
|
+
})
|
|
553
|
+
);
|
|
554
|
+
expect(nack.code).toBe("conflict");
|
|
555
|
+
expect(nack.serverSeq).toBe(2);
|
|
556
|
+
expect((nack.serverDoc as {name: string}).name).toBe("v2");
|
|
557
|
+
|
|
558
|
+
const saved = await MutStuffModel.findById(doc._id);
|
|
559
|
+
expect(saved?.name).toBe("v2");
|
|
560
|
+
const row = await SyncMutation.findOne({mutationId: "m-conflict-1"});
|
|
561
|
+
expect(row?.status).toBe("conflicted");
|
|
562
|
+
expect(row?.nackCode).toBe("conflict");
|
|
563
|
+
expect(row?.resultSeq).toBe(2);
|
|
564
|
+
// Task 9.21: the ledger stores only the pointer, never document data.
|
|
565
|
+
expect(row?.resultId).toBe(doc._id.toString());
|
|
566
|
+
const rowFields = (row?.toObject() ?? {}) as unknown as Record<string, unknown>;
|
|
567
|
+
expect(rowFields.serverDoc).toBeUndefined();
|
|
568
|
+
});
|
|
569
|
+
|
|
570
|
+
it("serializes the conflict server doc through the sync responseHandler", async () => {
|
|
571
|
+
registerMutStuff({
|
|
572
|
+
config: {
|
|
573
|
+
responseHandler: (doc: Record<string, unknown>) => ({redacted: `x-${doc.name}`}),
|
|
574
|
+
scope: {type: "owner"},
|
|
575
|
+
},
|
|
576
|
+
});
|
|
577
|
+
const doc = await MutStuffModel.create({name: "secret", ownerId: owner.id});
|
|
578
|
+
const nack = expectNack(
|
|
579
|
+
await applySyncMutation({
|
|
580
|
+
mutation: {
|
|
581
|
+
baseVersion: 99,
|
|
582
|
+
collection: "mutStuff",
|
|
583
|
+
data: {name: "stale"},
|
|
584
|
+
id: doc._id.toString(),
|
|
585
|
+
mutationId: "m-conflict-serialized",
|
|
586
|
+
operation: "update",
|
|
587
|
+
},
|
|
588
|
+
user: owner,
|
|
589
|
+
})
|
|
590
|
+
);
|
|
591
|
+
expect(nack.code).toBe("conflict");
|
|
592
|
+
expect(nack.serverDoc).toEqual({redacted: "x-secret"});
|
|
593
|
+
});
|
|
594
|
+
|
|
595
|
+
it("nacks conflict without a server doc when serialization fails", async () => {
|
|
596
|
+
registerMutStuff({
|
|
597
|
+
config: {
|
|
598
|
+
responseHandler: () => {
|
|
599
|
+
throw new Error("serializer exploded");
|
|
600
|
+
},
|
|
601
|
+
scope: {type: "owner"},
|
|
602
|
+
},
|
|
603
|
+
});
|
|
604
|
+
const doc = await MutStuffModel.create({name: "unserializable", ownerId: owner.id});
|
|
605
|
+
const nack = expectNack(
|
|
606
|
+
await applySyncMutation({
|
|
607
|
+
mutation: {
|
|
608
|
+
baseVersion: 99,
|
|
609
|
+
collection: "mutStuff",
|
|
610
|
+
data: {name: "stale"},
|
|
611
|
+
id: doc._id.toString(),
|
|
612
|
+
mutationId: "m-conflict-serialize-fail",
|
|
613
|
+
operation: "update",
|
|
614
|
+
},
|
|
615
|
+
user: owner,
|
|
616
|
+
})
|
|
617
|
+
);
|
|
618
|
+
expect(nack.code).toBe("conflict");
|
|
619
|
+
expect(nack.serverSeq).toBe(1);
|
|
620
|
+
expect(nack.serverDoc).toBeUndefined();
|
|
621
|
+
const row = await SyncMutation.findOne({mutationId: "m-conflict-serialize-fail"});
|
|
622
|
+
expect(row?.status).toBe("conflicted");
|
|
623
|
+
});
|
|
624
|
+
|
|
625
|
+
it("Task 9.13: two concurrent updates with the SAME baseVersion produce one ack and one conflict", async () => {
|
|
626
|
+
const doc = await MutStuffModel.create({name: "start", ownerId: owner.id});
|
|
627
|
+
const id = doc._id.toString();
|
|
628
|
+
const baseVersion = doc._syncSeq as number;
|
|
629
|
+
|
|
630
|
+
const [a, b] = await Promise.all([
|
|
631
|
+
applySyncMutation({
|
|
632
|
+
mutation: {
|
|
633
|
+
baseVersion,
|
|
634
|
+
collection: "mutStuff",
|
|
635
|
+
data: {name: "writer A"},
|
|
636
|
+
id,
|
|
637
|
+
mutationId: "m-race-a",
|
|
638
|
+
operation: "update",
|
|
639
|
+
},
|
|
640
|
+
user: owner,
|
|
641
|
+
}),
|
|
642
|
+
applySyncMutation({
|
|
643
|
+
mutation: {
|
|
644
|
+
baseVersion,
|
|
645
|
+
collection: "mutStuff",
|
|
646
|
+
data: {name: "writer B"},
|
|
647
|
+
id,
|
|
648
|
+
mutationId: "m-race-b",
|
|
649
|
+
operation: "update",
|
|
650
|
+
},
|
|
651
|
+
user: owner,
|
|
652
|
+
}),
|
|
653
|
+
]);
|
|
654
|
+
|
|
655
|
+
const acks = [a, b].filter((outcome) => outcome.type === "ack");
|
|
656
|
+
const nacks = [a, b].filter((outcome) => outcome.type === "nack");
|
|
657
|
+
expect(acks).toHaveLength(1);
|
|
658
|
+
expect(nacks).toHaveLength(1);
|
|
659
|
+
if (nacks[0].type !== "nack") {
|
|
660
|
+
throw new Error("expected a nack");
|
|
661
|
+
}
|
|
662
|
+
expect(nacks[0].nack.code).toBe("conflict");
|
|
663
|
+
|
|
664
|
+
// The winner's edit survived: the loser never overwrote it.
|
|
665
|
+
const saved = await MutStuffModel.findById(id);
|
|
666
|
+
const winner = acks[0].type === "ack" ? acks[0].ack : undefined;
|
|
667
|
+
expect(saved?._syncSeq).toBe(winner?.seq);
|
|
668
|
+
expect(["writer A", "writer B"]).toContain(saved?.name ?? "");
|
|
669
|
+
// The conflict reports the CURRENT server state, not the loser's rejected edit.
|
|
670
|
+
expect((nacks[0].nack.serverDoc as {name: string} | undefined)?.name).toBe(saved?.name);
|
|
671
|
+
expect(nacks[0].nack.serverSeq).toBe(saved?._syncSeq);
|
|
672
|
+
});
|
|
673
|
+
|
|
674
|
+
it("Task 9.13: the version-conflicted loser releases its seq claim so the frontier still advances", async () => {
|
|
675
|
+
const doc = await MutStuffModel.create({name: "start", ownerId: owner.id});
|
|
676
|
+
const id = doc._id.toString();
|
|
677
|
+
const baseVersion = doc._syncSeq as number;
|
|
678
|
+
const stream = `mutStuff|owner:${owner.id}`;
|
|
679
|
+
|
|
680
|
+
await Promise.all([
|
|
681
|
+
applySyncMutation({
|
|
682
|
+
mutation: {
|
|
683
|
+
baseVersion,
|
|
684
|
+
collection: "mutStuff",
|
|
685
|
+
data: {name: "A"},
|
|
686
|
+
id,
|
|
687
|
+
mutationId: "m-frontier-a",
|
|
688
|
+
operation: "update",
|
|
689
|
+
},
|
|
690
|
+
user: owner,
|
|
691
|
+
}),
|
|
692
|
+
applySyncMutation({
|
|
693
|
+
mutation: {
|
|
694
|
+
baseVersion,
|
|
695
|
+
collection: "mutStuff",
|
|
696
|
+
data: {name: "B"},
|
|
697
|
+
id,
|
|
698
|
+
mutationId: "m-frontier-b",
|
|
699
|
+
operation: "update",
|
|
700
|
+
},
|
|
701
|
+
user: owner,
|
|
702
|
+
}),
|
|
703
|
+
]);
|
|
704
|
+
|
|
705
|
+
const counter = await SyncCounter.findOne({stream});
|
|
706
|
+
expect(counter?.pending ?? []).toHaveLength(0);
|
|
707
|
+
// A claim released rather than stranded means the frontier reaches the head.
|
|
708
|
+
expect(await computeStableFrontier({stream})).toBe(counter?.seq as number);
|
|
709
|
+
});
|
|
710
|
+
});
|
|
711
|
+
|
|
712
|
+
describe("permissions", () => {
|
|
713
|
+
it("nacks unauthorized when a non-owner updates a document", async () => {
|
|
714
|
+
const doc = await MutStuffModel.create({name: "owned", ownerId: owner.id});
|
|
715
|
+
const nack = expectNack(
|
|
716
|
+
await applySyncMutation({
|
|
717
|
+
mutation: {
|
|
718
|
+
baseVersion: 1,
|
|
719
|
+
collection: "mutStuff",
|
|
720
|
+
data: {name: "hijacked"},
|
|
721
|
+
id: doc._id.toString(),
|
|
722
|
+
mutationId: "m-perm-1",
|
|
723
|
+
operation: "update",
|
|
724
|
+
},
|
|
725
|
+
user: stranger,
|
|
726
|
+
})
|
|
727
|
+
);
|
|
728
|
+
expect(nack.code).toBe("unauthorized");
|
|
729
|
+
const saved = await MutStuffModel.findById(doc._id);
|
|
730
|
+
expect(saved?.name).toBe("owned");
|
|
731
|
+
const row = await SyncMutation.findOne({mutationId: "m-perm-1"});
|
|
732
|
+
expect(row?.status).toBe("failed");
|
|
733
|
+
expect(row?.nackCode).toBe("unauthorized");
|
|
734
|
+
});
|
|
735
|
+
|
|
736
|
+
it("nacks unauthorized for method-level (405) denials", async () => {
|
|
737
|
+
registerMutStuff({
|
|
738
|
+
options: {
|
|
739
|
+
permissions: {
|
|
740
|
+
create: [Permissions.IsAdmin],
|
|
741
|
+
delete: [Permissions.IsAdmin],
|
|
742
|
+
list: [Permissions.IsAdmin],
|
|
743
|
+
read: [Permissions.IsAdmin],
|
|
744
|
+
update: [Permissions.IsAdmin],
|
|
745
|
+
},
|
|
746
|
+
} as unknown as ModelRouterOptions<any>,
|
|
747
|
+
});
|
|
748
|
+
const nack = expectNack(
|
|
749
|
+
await applySyncMutation({
|
|
750
|
+
mutation: {
|
|
751
|
+
collection: "mutStuff",
|
|
752
|
+
data: {name: "nope", ownerId: owner.id},
|
|
753
|
+
mutationId: "m-perm-2",
|
|
754
|
+
operation: "create",
|
|
755
|
+
},
|
|
756
|
+
user: owner,
|
|
757
|
+
})
|
|
758
|
+
);
|
|
759
|
+
expect(nack.code).toBe("unauthorized");
|
|
760
|
+
});
|
|
761
|
+
|
|
762
|
+
it("nacks unauthorized when a non-owner deletes a document", async () => {
|
|
763
|
+
const doc = await MutStuffModel.create({name: "keep", ownerId: owner.id});
|
|
764
|
+
const nack = expectNack(
|
|
765
|
+
await applySyncMutation({
|
|
766
|
+
mutation: {
|
|
767
|
+
collection: "mutStuff",
|
|
768
|
+
id: doc._id.toString(),
|
|
769
|
+
mutationId: "m-perm-3",
|
|
770
|
+
operation: "delete",
|
|
771
|
+
},
|
|
772
|
+
user: stranger,
|
|
773
|
+
})
|
|
774
|
+
);
|
|
775
|
+
expect(nack.code).toBe("unauthorized");
|
|
776
|
+
const saved = await MutStuffModel.findById(doc._id);
|
|
777
|
+
expect(saved?.deleted).toBe(false);
|
|
778
|
+
});
|
|
779
|
+
});
|
|
780
|
+
|
|
781
|
+
describe("validation", () => {
|
|
782
|
+
it("nacks validation when a required field is missing", async () => {
|
|
783
|
+
const nack = expectNack(
|
|
784
|
+
await applySyncMutation({
|
|
785
|
+
mutation: {
|
|
786
|
+
collection: "mutStuff",
|
|
787
|
+
data: {ownerId: owner.id},
|
|
788
|
+
mutationId: "m-invalid-1",
|
|
789
|
+
operation: "create",
|
|
790
|
+
},
|
|
791
|
+
user: owner,
|
|
792
|
+
})
|
|
793
|
+
);
|
|
794
|
+
expect(nack.code).toBe("validation");
|
|
795
|
+
const row = await SyncMutation.findOne({mutationId: "m-invalid-1"});
|
|
796
|
+
expect(row?.status).toBe("failed");
|
|
797
|
+
expect(row?.nackCode).toBe("validation");
|
|
798
|
+
});
|
|
799
|
+
|
|
800
|
+
it("nacks validation for an unknown collection", async () => {
|
|
801
|
+
const nack = expectNack(
|
|
802
|
+
await applySyncMutation({
|
|
803
|
+
mutation: {
|
|
804
|
+
collection: "nope",
|
|
805
|
+
data: {name: "x"},
|
|
806
|
+
mutationId: "m-invalid-2",
|
|
807
|
+
operation: "create",
|
|
808
|
+
},
|
|
809
|
+
user: owner,
|
|
810
|
+
})
|
|
811
|
+
);
|
|
812
|
+
expect(nack.code).toBe("validation");
|
|
813
|
+
expect(nack.message).toContain("Unknown sync collection");
|
|
814
|
+
});
|
|
815
|
+
|
|
816
|
+
it("nacks validation when update or delete is missing an id", async () => {
|
|
817
|
+
for (const operation of ["update", "delete"] as const) {
|
|
818
|
+
const nack = expectNack(
|
|
819
|
+
await applySyncMutation({
|
|
820
|
+
mutation: {
|
|
821
|
+
collection: "mutStuff",
|
|
822
|
+
data: {name: "x"},
|
|
823
|
+
mutationId: `m-noid-${operation}`,
|
|
824
|
+
operation,
|
|
825
|
+
},
|
|
826
|
+
user: owner,
|
|
827
|
+
})
|
|
828
|
+
);
|
|
829
|
+
expect(nack.code).toBe("validation");
|
|
830
|
+
expect(nack.message).toContain("id is required");
|
|
831
|
+
}
|
|
832
|
+
});
|
|
833
|
+
|
|
834
|
+
it("nacks validation when mutationId or collection is missing", async () => {
|
|
835
|
+
const noMutationId = expectNack(
|
|
836
|
+
await applySyncMutation({
|
|
837
|
+
mutation: {collection: "mutStuff", operation: "create"} as SyncMutateRequest,
|
|
838
|
+
user: owner,
|
|
839
|
+
})
|
|
840
|
+
);
|
|
841
|
+
expect(noMutationId.code).toBe("validation");
|
|
842
|
+
expect(noMutationId.mutationId).toBe("");
|
|
843
|
+
|
|
844
|
+
const noCollection = expectNack(
|
|
845
|
+
await applySyncMutation({
|
|
846
|
+
mutation: {mutationId: "m-nocoll", operation: "create"} as SyncMutateRequest,
|
|
847
|
+
user: owner,
|
|
848
|
+
})
|
|
849
|
+
);
|
|
850
|
+
expect(noCollection.code).toBe("validation");
|
|
851
|
+
expect(noCollection.message).toContain("collection");
|
|
852
|
+
});
|
|
853
|
+
|
|
854
|
+
it("nacks validation for an unknown operation", async () => {
|
|
855
|
+
const nack = expectNack(
|
|
856
|
+
await applySyncMutation({
|
|
857
|
+
mutation: {
|
|
858
|
+
collection: "mutStuff",
|
|
859
|
+
mutationId: "m-badop",
|
|
860
|
+
operation: "upsert",
|
|
861
|
+
} as unknown as SyncMutateRequest,
|
|
862
|
+
user: owner,
|
|
863
|
+
})
|
|
864
|
+
);
|
|
865
|
+
expect(nack.code).toBe("validation");
|
|
866
|
+
expect(nack.message).toContain("Unknown operation");
|
|
867
|
+
});
|
|
868
|
+
|
|
869
|
+
it("nacks validation when the target document does not exist", async () => {
|
|
870
|
+
const nack = expectNack(
|
|
871
|
+
await applySyncMutation({
|
|
872
|
+
mutation: {
|
|
873
|
+
baseVersion: 0,
|
|
874
|
+
collection: "mutStuff",
|
|
875
|
+
data: {name: "ghost"},
|
|
876
|
+
id: new mongoose.Types.ObjectId().toString(),
|
|
877
|
+
mutationId: "m-missing-doc",
|
|
878
|
+
operation: "update",
|
|
879
|
+
},
|
|
880
|
+
user: owner,
|
|
881
|
+
})
|
|
882
|
+
);
|
|
883
|
+
expect(nack.code).toBe("validation");
|
|
884
|
+
});
|
|
885
|
+
});
|
|
886
|
+
|
|
887
|
+
describe("errors", () => {
|
|
888
|
+
it("nacks error for unexpected server failures and records the message", async () => {
|
|
889
|
+
registerMutStuff({
|
|
890
|
+
options: {
|
|
891
|
+
...ownerOptions,
|
|
892
|
+
preCreate: () => {
|
|
893
|
+
throw new APIError({status: 500, title: "database exploded"});
|
|
894
|
+
},
|
|
895
|
+
} as unknown as ModelRouterOptions<any>,
|
|
896
|
+
});
|
|
897
|
+
const nack = expectNack(
|
|
898
|
+
await applySyncMutation({
|
|
899
|
+
mutation: {
|
|
900
|
+
collection: "mutStuff",
|
|
901
|
+
data: {name: "boom", ownerId: owner.id},
|
|
902
|
+
mutationId: "m-error-1",
|
|
903
|
+
operation: "create",
|
|
904
|
+
},
|
|
905
|
+
user: owner,
|
|
906
|
+
})
|
|
907
|
+
);
|
|
908
|
+
expect(nack.code).toBe("error");
|
|
909
|
+
expect(nack.message).toBe("database exploded");
|
|
910
|
+
// Task 9.18: an error-class outcome is NOT recorded — it is non-deterministic, so
|
|
911
|
+
// leaving it on the ledger would make the nack sticky for the 30-day TTL.
|
|
912
|
+
expect(await SyncMutation.countDocuments({mutationId: "m-error-1"})).toBe(0);
|
|
913
|
+
});
|
|
914
|
+
|
|
915
|
+
it("Task 9.18: a transient error-class failure re-executes on replay of the same mutationId", async () => {
|
|
916
|
+
let attempts = 0;
|
|
917
|
+
registerMutStuff({
|
|
918
|
+
options: {
|
|
919
|
+
...ownerOptions,
|
|
920
|
+
preCreate: (body: unknown) => {
|
|
921
|
+
attempts += 1;
|
|
922
|
+
if (attempts === 1) {
|
|
923
|
+
throw new APIError({status: 500, title: "transient DB hiccup"});
|
|
924
|
+
}
|
|
925
|
+
return body;
|
|
926
|
+
},
|
|
927
|
+
} as unknown as ModelRouterOptions<any>,
|
|
928
|
+
});
|
|
929
|
+
const mutation: SyncMutateRequest = {
|
|
930
|
+
collection: "mutStuff",
|
|
931
|
+
data: {name: "retried", ownerId: owner.id},
|
|
932
|
+
mutationId: "m-transient-retry",
|
|
933
|
+
operation: "create",
|
|
934
|
+
};
|
|
935
|
+
const first = expectNack(await applySyncMutation({mutation, user: owner}));
|
|
936
|
+
expect(first.code).toBe("error");
|
|
937
|
+
|
|
938
|
+
// The client's durable outbox resends the SAME mutationId; it must genuinely re-run.
|
|
939
|
+
const ack = expectAck(await applySyncMutation({mutation, user: owner}));
|
|
940
|
+
expect(attempts).toBe(2);
|
|
941
|
+
const saved = await MutStuffModel.findById(ack.id);
|
|
942
|
+
expect(saved?.name).toBe("retried");
|
|
943
|
+
const row = await SyncMutation.findOne({mutationId: "m-transient-retry"});
|
|
944
|
+
expect(row?.status).toBe("applied");
|
|
945
|
+
});
|
|
946
|
+
|
|
947
|
+
it("Task 9.18: a deterministic validation failure stays recorded and is NOT re-executed", async () => {
|
|
948
|
+
let attempts = 0;
|
|
949
|
+
registerMutStuff({
|
|
950
|
+
options: {
|
|
951
|
+
...ownerOptions,
|
|
952
|
+
preCreate: () => {
|
|
953
|
+
attempts += 1;
|
|
954
|
+
throw new APIError({status: 400, title: "name is not allowed"});
|
|
955
|
+
},
|
|
956
|
+
} as unknown as ModelRouterOptions<any>,
|
|
957
|
+
});
|
|
958
|
+
const mutation: SyncMutateRequest = {
|
|
959
|
+
collection: "mutStuff",
|
|
960
|
+
data: {name: "rejected", ownerId: owner.id},
|
|
961
|
+
mutationId: "m-terminal-sticky",
|
|
962
|
+
operation: "create",
|
|
963
|
+
};
|
|
964
|
+
expect(expectNack(await applySyncMutation({mutation, user: owner})).code).toBe("validation");
|
|
965
|
+
expect(expectNack(await applySyncMutation({mutation, user: owner})).code).toBe("validation");
|
|
966
|
+
expect(attempts).toBe(1);
|
|
967
|
+
const row = await SyncMutation.findOne({mutationId: "m-terminal-sticky"});
|
|
968
|
+
expect(row?.status).toBe("failed");
|
|
969
|
+
});
|
|
970
|
+
|
|
971
|
+
it("nacks error when a non-APIError escapes the executor pipeline", async () => {
|
|
972
|
+
registerMutStuff({
|
|
973
|
+
options: {
|
|
974
|
+
permissions: {
|
|
975
|
+
create: [
|
|
976
|
+
() => {
|
|
977
|
+
throw new Error("permission crashed");
|
|
978
|
+
},
|
|
979
|
+
],
|
|
980
|
+
delete: [Permissions.IsOwner],
|
|
981
|
+
list: [Permissions.IsAny],
|
|
982
|
+
read: [Permissions.IsAny],
|
|
983
|
+
update: [Permissions.IsOwner],
|
|
984
|
+
},
|
|
985
|
+
} as unknown as ModelRouterOptions<any>,
|
|
986
|
+
});
|
|
987
|
+
const nack = expectNack(
|
|
988
|
+
await applySyncMutation({
|
|
989
|
+
mutation: {
|
|
990
|
+
collection: "mutStuff",
|
|
991
|
+
data: {name: "crash", ownerId: owner.id},
|
|
992
|
+
mutationId: "m-plain-error",
|
|
993
|
+
operation: "create",
|
|
994
|
+
},
|
|
995
|
+
user: owner,
|
|
996
|
+
})
|
|
997
|
+
);
|
|
998
|
+
expect(nack.code).toBe("error");
|
|
999
|
+
expect(nack.message).toContain("permission crashed");
|
|
1000
|
+
// Task 9.18: error-class outcomes release the claim rather than recording it.
|
|
1001
|
+
expect(await SyncMutation.countDocuments({mutationId: "m-plain-error"})).toBe(0);
|
|
1002
|
+
});
|
|
1003
|
+
});
|
|
1004
|
+
});
|
|
1005
|
+
|
|
1006
|
+
describe("validateSyncMutationBatch", () => {
|
|
1007
|
+
it("accepts a batch within the size limit with no duplicate ids", () => {
|
|
1008
|
+
const mutations: SyncMutateRequest[] = Array.from({length: 10}, (_v, i) => ({
|
|
1009
|
+
collection: "mutStuff",
|
|
1010
|
+
data: {name: `item ${i}`},
|
|
1011
|
+
mutationId: `batch-ok-${i}`,
|
|
1012
|
+
operation: "create",
|
|
1013
|
+
}));
|
|
1014
|
+
expect(validateSyncMutationBatch(mutations)).toEqual({ok: true});
|
|
1015
|
+
});
|
|
1016
|
+
|
|
1017
|
+
it("rejects a batch exceeding the maximum size", () => {
|
|
1018
|
+
const mutations: SyncMutateRequest[] = Array.from(
|
|
1019
|
+
{length: MAX_SYNC_MUTATIONS_PER_BATCH + 1},
|
|
1020
|
+
(_v, i) => ({
|
|
1021
|
+
collection: "mutStuff",
|
|
1022
|
+
data: {},
|
|
1023
|
+
mutationId: `batch-oversized-${i}`,
|
|
1024
|
+
operation: "create",
|
|
1025
|
+
})
|
|
1026
|
+
);
|
|
1027
|
+
const outcome = validateSyncMutationBatch(mutations);
|
|
1028
|
+
expect(outcome.ok).toBe(false);
|
|
1029
|
+
if (outcome.ok) {
|
|
1030
|
+
throw new Error("expected rejection");
|
|
1031
|
+
}
|
|
1032
|
+
expect(outcome.response.results).toHaveLength(1);
|
|
1033
|
+
const [result] = outcome.response.results;
|
|
1034
|
+
expect(result.type).toBe("nack");
|
|
1035
|
+
if (result.type !== "nack") {
|
|
1036
|
+
throw new Error("expected nack");
|
|
1037
|
+
}
|
|
1038
|
+
expect(result.nack.code).toBe("validation");
|
|
1039
|
+
expect(result.nack.message).toContain(String(MAX_SYNC_MUTATIONS_PER_BATCH));
|
|
1040
|
+
});
|
|
1041
|
+
|
|
1042
|
+
it("rejects a batch with an intra-batch duplicate mutationId", () => {
|
|
1043
|
+
const mutations: SyncMutateRequest[] = [
|
|
1044
|
+
{collection: "mutStuff", data: {}, mutationId: "dup-1", operation: "create"},
|
|
1045
|
+
{collection: "mutStuff", data: {}, mutationId: "dup-2", operation: "create"},
|
|
1046
|
+
{collection: "mutStuff", data: {}, mutationId: "dup-1", operation: "create"},
|
|
1047
|
+
];
|
|
1048
|
+
const outcome = validateSyncMutationBatch(mutations);
|
|
1049
|
+
expect(outcome.ok).toBe(false);
|
|
1050
|
+
if (outcome.ok) {
|
|
1051
|
+
throw new Error("expected rejection");
|
|
1052
|
+
}
|
|
1053
|
+
const [result] = outcome.response.results;
|
|
1054
|
+
expect(result.type).toBe("nack");
|
|
1055
|
+
if (result.type !== "nack") {
|
|
1056
|
+
throw new Error("expected nack");
|
|
1057
|
+
}
|
|
1058
|
+
expect(result.nack.code).toBe("validation");
|
|
1059
|
+
expect(result.nack.mutationId).toBe("dup-1");
|
|
1060
|
+
});
|
|
1061
|
+
});
|
|
1062
|
+
|
|
1063
|
+
describe("applySyncMutationBatch", () => {
|
|
1064
|
+
beforeAll(async () => {
|
|
1065
|
+
await setupDb();
|
|
1066
|
+
await Promise.all([SyncCounter.ensureIndexes(), SyncMutation.ensureIndexes()]);
|
|
1067
|
+
});
|
|
1068
|
+
|
|
1069
|
+
beforeEach(async () => {
|
|
1070
|
+
registerMutStuff();
|
|
1071
|
+
await Promise.all([
|
|
1072
|
+
MutStuffModel.collection.deleteMany({}),
|
|
1073
|
+
SyncCounter.deleteMany({}),
|
|
1074
|
+
SyncMutation.deleteMany({}),
|
|
1075
|
+
]);
|
|
1076
|
+
});
|
|
1077
|
+
|
|
1078
|
+
const create = (mutationId: string, name: string): SyncMutateRequest => ({
|
|
1079
|
+
collection: "mutStuff",
|
|
1080
|
+
data: {name, ownerId: owner.id},
|
|
1081
|
+
mutationId,
|
|
1082
|
+
operation: "create",
|
|
1083
|
+
});
|
|
1084
|
+
|
|
1085
|
+
it("applies every mutation strictly serially and returns one result per mutation", async () => {
|
|
1086
|
+
const mutations = Array.from({length: 10}, (_v, i) => create(`batch-serial-${i}`, `item ${i}`));
|
|
1087
|
+
const response = await applySyncMutationBatch({mutations, user: owner});
|
|
1088
|
+
expect(response.results).toHaveLength(10);
|
|
1089
|
+
expect(response.results.every((r) => r.type === "ack")).toBe(true);
|
|
1090
|
+
// Order proof: seqs are strictly increasing in request order (strictly serial,
|
|
1091
|
+
// no parallelism).
|
|
1092
|
+
const seqs = response.results.map((r) => (r.type === "ack" ? r.ack.seq : -1));
|
|
1093
|
+
expect(seqs).toEqual([...seqs].sort((a, b) => a - b));
|
|
1094
|
+
expect(new Set(seqs).size).toBe(10);
|
|
1095
|
+
});
|
|
1096
|
+
|
|
1097
|
+
it("stops at the first conflict: results shorter than the request, later mutations unledgered", async () => {
|
|
1098
|
+
const doc = await MutStuffModel.create({name: "server v1", ownerId: owner.id});
|
|
1099
|
+
doc.name = "server v2";
|
|
1100
|
+
await doc.save(); // seq 2
|
|
1101
|
+
|
|
1102
|
+
const mutations: SyncMutateRequest[] = [
|
|
1103
|
+
create("batch-conflict-1", "item 1"),
|
|
1104
|
+
create("batch-conflict-2", "item 2"),
|
|
1105
|
+
create("batch-conflict-3", "item 3"),
|
|
1106
|
+
{
|
|
1107
|
+
baseVersion: 1, // stale — server is at seq 2
|
|
1108
|
+
collection: "mutStuff",
|
|
1109
|
+
data: {name: "stale write"},
|
|
1110
|
+
id: String(doc._id),
|
|
1111
|
+
mutationId: "batch-conflict-4",
|
|
1112
|
+
operation: "update",
|
|
1113
|
+
},
|
|
1114
|
+
create("batch-conflict-5", "item 5"),
|
|
1115
|
+
create("batch-conflict-6", "item 6"),
|
|
1116
|
+
create("batch-conflict-7", "item 7"),
|
|
1117
|
+
create("batch-conflict-8", "item 8"),
|
|
1118
|
+
create("batch-conflict-9", "item 9"),
|
|
1119
|
+
create("batch-conflict-10", "item 10"),
|
|
1120
|
+
];
|
|
1121
|
+
|
|
1122
|
+
const response = await applySyncMutationBatch({mutations, user: owner});
|
|
1123
|
+
expect(response.results).toHaveLength(4);
|
|
1124
|
+
expect(response.results.slice(0, 3).every((r) => r.type === "ack")).toBe(true);
|
|
1125
|
+
const fourth = response.results[3];
|
|
1126
|
+
expect(fourth.type).toBe("nack");
|
|
1127
|
+
if (fourth.type !== "nack") {
|
|
1128
|
+
throw new Error("expected nack");
|
|
1129
|
+
}
|
|
1130
|
+
expect(fourth.nack.code).toBe("conflict");
|
|
1131
|
+
|
|
1132
|
+
// Mutations 5-10 were never attempted: no ledger row exists for them, and no
|
|
1133
|
+
// document was created for them.
|
|
1134
|
+
for (const mutationId of [
|
|
1135
|
+
"batch-conflict-5",
|
|
1136
|
+
"batch-conflict-6",
|
|
1137
|
+
"batch-conflict-7",
|
|
1138
|
+
"batch-conflict-8",
|
|
1139
|
+
"batch-conflict-9",
|
|
1140
|
+
"batch-conflict-10",
|
|
1141
|
+
]) {
|
|
1142
|
+
expect(await SyncMutation.findOne({mutationId})).toBeNull();
|
|
1143
|
+
}
|
|
1144
|
+
expect(await MutStuffModel.countDocuments({name: {$in: ["item 5", "item 6", "item 10"]}})).toBe(
|
|
1145
|
+
0
|
|
1146
|
+
);
|
|
1147
|
+
|
|
1148
|
+
// Resending mutations 4-10 as a new batch: #4 (the boundary mutation) reads
|
|
1149
|
+
// back its recorded conflict from the ledger idempotently; 5-10 apply.
|
|
1150
|
+
const resend = mutations.slice(3);
|
|
1151
|
+
const resendResponse = await applySyncMutationBatch({mutations: resend, user: owner});
|
|
1152
|
+
expect(resendResponse.results).toHaveLength(1);
|
|
1153
|
+
const [resentFourth] = resendResponse.results;
|
|
1154
|
+
expect(resentFourth.type).toBe("nack");
|
|
1155
|
+
if (resentFourth.type !== "nack") {
|
|
1156
|
+
throw new Error("expected nack");
|
|
1157
|
+
}
|
|
1158
|
+
expect(resentFourth.nack.code).toBe("conflict");
|
|
1159
|
+
|
|
1160
|
+
// The client, having recorded #4 as conflicted, resends only 5-10 next.
|
|
1161
|
+
const tail = mutations.slice(4);
|
|
1162
|
+
const tailResponse = await applySyncMutationBatch({mutations: tail, user: owner});
|
|
1163
|
+
expect(tailResponse.results).toHaveLength(6);
|
|
1164
|
+
expect(tailResponse.results.every((r) => r.type === "ack")).toBe(true);
|
|
1165
|
+
for (const name of ["item 5", "item 6", "item 7", "item 8", "item 9", "item 10"]) {
|
|
1166
|
+
expect(await MutStuffModel.countDocuments({name})).toBe(1);
|
|
1167
|
+
}
|
|
1168
|
+
});
|
|
1169
|
+
|
|
1170
|
+
it("a whole-batch duplicate resend is idempotent: all results served from the ledger, docs written once", async () => {
|
|
1171
|
+
const mutations = Array.from({length: 5}, (_v, i) => create(`batch-dup-${i}`, `dup ${i}`));
|
|
1172
|
+
const first = await applySyncMutationBatch({mutations, user: owner});
|
|
1173
|
+
expect(first.results.every((r) => r.type === "ack")).toBe(true);
|
|
1174
|
+
|
|
1175
|
+
const second: SyncMutateBatchResponse = await applySyncMutationBatch({mutations, user: owner});
|
|
1176
|
+
expect(second.results).toHaveLength(5);
|
|
1177
|
+
expect(second).toEqual(first);
|
|
1178
|
+
|
|
1179
|
+
for (let i = 0; i < 5; i++) {
|
|
1180
|
+
expect(await MutStuffModel.countDocuments({name: `dup ${i}`})).toBe(1);
|
|
1181
|
+
}
|
|
1182
|
+
});
|
|
1183
|
+
|
|
1184
|
+
it("order proof: create, update, delete for one entity in one batch works", async () => {
|
|
1185
|
+
const entityId = new mongoose.Types.ObjectId().toString();
|
|
1186
|
+
const mutations: SyncMutateRequest[] = [
|
|
1187
|
+
{
|
|
1188
|
+
collection: "mutStuff",
|
|
1189
|
+
data: {name: "v1", ownerId: owner.id},
|
|
1190
|
+
id: entityId,
|
|
1191
|
+
mutationId: "order-create",
|
|
1192
|
+
operation: "create",
|
|
1193
|
+
},
|
|
1194
|
+
{
|
|
1195
|
+
baseVersion: 1,
|
|
1196
|
+
collection: "mutStuff",
|
|
1197
|
+
data: {name: "v2"},
|
|
1198
|
+
id: entityId,
|
|
1199
|
+
mutationId: "order-update",
|
|
1200
|
+
operation: "update",
|
|
1201
|
+
},
|
|
1202
|
+
{
|
|
1203
|
+
baseVersion: 2,
|
|
1204
|
+
collection: "mutStuff",
|
|
1205
|
+
id: entityId,
|
|
1206
|
+
mutationId: "order-delete",
|
|
1207
|
+
operation: "delete",
|
|
1208
|
+
},
|
|
1209
|
+
];
|
|
1210
|
+
const response = await applySyncMutationBatch({mutations, user: owner});
|
|
1211
|
+
expect(response.results).toHaveLength(3);
|
|
1212
|
+
expect(response.results.every((r) => r.type === "ack")).toBe(true);
|
|
1213
|
+
const seqs = response.results.map((r) => (r.type === "ack" ? r.ack.seq : -1));
|
|
1214
|
+
expect(seqs).toEqual([1, 2, 3]);
|
|
1215
|
+
const tombstones = await MutStuffModel.find({_id: entityId, deleted: true});
|
|
1216
|
+
expect(tombstones).toHaveLength(1);
|
|
1217
|
+
});
|
|
1218
|
+
|
|
1219
|
+
it("order proof reversed: a failing first mutation halts before the second/third are touched", async () => {
|
|
1220
|
+
const entityId = new mongoose.Types.ObjectId().toString();
|
|
1221
|
+
const mutations: SyncMutateRequest[] = [
|
|
1222
|
+
// Update against a non-existent document fails first.
|
|
1223
|
+
{
|
|
1224
|
+
baseVersion: 0,
|
|
1225
|
+
collection: "mutStuff",
|
|
1226
|
+
data: {name: "nope"},
|
|
1227
|
+
id: entityId,
|
|
1228
|
+
mutationId: "reversed-update",
|
|
1229
|
+
operation: "update",
|
|
1230
|
+
},
|
|
1231
|
+
{
|
|
1232
|
+
collection: "mutStuff",
|
|
1233
|
+
data: {name: "v1", ownerId: owner.id},
|
|
1234
|
+
id: entityId,
|
|
1235
|
+
mutationId: "reversed-create",
|
|
1236
|
+
operation: "create",
|
|
1237
|
+
},
|
|
1238
|
+
{
|
|
1239
|
+
collection: "mutStuff",
|
|
1240
|
+
id: entityId,
|
|
1241
|
+
mutationId: "reversed-delete",
|
|
1242
|
+
operation: "delete",
|
|
1243
|
+
},
|
|
1244
|
+
];
|
|
1245
|
+
const response = await applySyncMutationBatch({mutations, user: owner});
|
|
1246
|
+
expect(response.results).toHaveLength(1);
|
|
1247
|
+
expect(response.results[0].type).toBe("nack");
|
|
1248
|
+
expect(await SyncMutation.findOne({mutationId: "reversed-create"})).toBeNull();
|
|
1249
|
+
expect(await SyncMutation.findOne({mutationId: "reversed-delete"})).toBeNull();
|
|
1250
|
+
expect(await MutStuffModel.findById(entityId)).toBeNull();
|
|
1251
|
+
});
|
|
1252
|
+
});
|