@terreno/api 58.0.6 → 58.1.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.
Files changed (75) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/dist/actions.d.ts +6 -0
  3. package/dist/api.d.ts +21 -0
  4. package/dist/api.js +57 -32
  5. package/dist/bulk.d.ts +79 -0
  6. package/dist/bulk.js +449 -0
  7. package/dist/bulkOpenApi.d.ts +15 -0
  8. package/dist/bulkOpenApi.js +103 -0
  9. package/dist/bulkTransaction.d.ts +33 -0
  10. package/dist/bulkTransaction.js +126 -0
  11. package/dist/errors.d.ts +2 -0
  12. package/dist/errors.js +8 -6
  13. package/dist/index.d.ts +3 -2
  14. package/dist/index.js +6 -3
  15. package/dist/mcp/actionTools.js +2 -0
  16. package/dist/mcp/grantAccess.d.ts +27 -0
  17. package/dist/mcp/grantAccess.js +29 -0
  18. package/dist/mcp/oauth.js +86 -5
  19. package/dist/mcp/oauthMetadata.d.ts +32 -1
  20. package/dist/mcp/oauthMetadata.js +53 -2
  21. package/dist/mcp/registry.d.ts +8 -1
  22. package/dist/mcp/server.js +6 -1
  23. package/dist/mcp/toolGenerator.d.ts +5 -1
  24. package/dist/mcp/toolGenerator.js +11 -0
  25. package/dist/mcp/types.d.ts +11 -0
  26. package/dist/modelRouterWrites.d.ts +23 -0
  27. package/dist/modelRouterWrites.js +54 -0
  28. package/dist/openApi.d.ts +7 -0
  29. package/dist/openApi.js +6 -6
  30. package/dist/permissions.js +5 -4
  31. package/dist/rbac/access.js +2 -0
  32. package/dist/rbac/routes.js +1 -0
  33. package/dist/rbac/statements.d.ts +12 -1
  34. package/dist/rbac/statements.js +89 -1
  35. package/dist/rbac/types.d.ts +9 -2
  36. package/dist/sync/executors.d.ts +6 -4
  37. package/dist/sync/executors.js +6 -2
  38. package/package.json +6 -6
  39. package/src/actions.ts +6 -0
  40. package/src/api.ts +95 -33
  41. package/src/bulk.test.ts +1256 -0
  42. package/src/bulk.ts +680 -0
  43. package/src/bulkOpenApi.test.ts +172 -0
  44. package/src/bulkOpenApi.ts +126 -0
  45. package/src/bulkTransaction.test.ts +197 -0
  46. package/src/bulkTransaction.ts +149 -0
  47. package/src/errors.ts +2 -2
  48. package/src/index.ts +6 -0
  49. package/src/isolated/bulkAtomic.isolated.ts +630 -0
  50. package/src/isolated/bulkStandalone.isolated.ts +133 -0
  51. package/src/isolated/mongoTopology.isolated.ts +29 -0
  52. package/src/mcp/actionTools.ts +2 -0
  53. package/src/mcp/grantAccess.test.ts +107 -0
  54. package/src/mcp/grantAccess.ts +49 -0
  55. package/src/mcp/oauth.test.ts +327 -0
  56. package/src/mcp/oauth.ts +113 -5
  57. package/src/mcp/oauthMetadata.test.ts +125 -1
  58. package/src/mcp/oauthMetadata.ts +99 -2
  59. package/src/mcp/registry.ts +8 -1
  60. package/src/mcp/server.test.ts +419 -2
  61. package/src/mcp/server.ts +8 -1
  62. package/src/mcp/toolGenerator.ts +17 -0
  63. package/src/mcp/types.ts +12 -0
  64. package/src/modelRouterWrites.ts +72 -0
  65. package/src/openApi.ts +1 -1
  66. package/src/permissions.ts +5 -5
  67. package/src/rbac/access.ts +3 -1
  68. package/src/rbac/routes.test.ts +15 -0
  69. package/src/rbac/routes.ts +1 -0
  70. package/src/rbac/statements.test.ts +23 -0
  71. package/src/rbac/statements.ts +100 -1
  72. package/src/rbac/types.ts +9 -2
  73. package/src/sync/executors.test.ts +27 -0
  74. package/src/sync/executors.ts +12 -4
  75. package/src/tests/mongoTopology.ts +53 -0
@@ -0,0 +1,630 @@
1
+ /**
2
+ * Atomic (default) mode of `POST /<route>/bulk`. Isolated because atomic mode needs a Mongo
3
+ * transaction, so `useMongoTopology` swaps the default mongoose connection to an in-memory
4
+ * replica set for this process.
5
+ */
6
+ import {afterEach, beforeEach, describe, expect, it} from "bun:test";
7
+ import {expectAPIError} from "@terreno/test";
8
+ import type express from "express";
9
+ import {DateTime} from "luxon";
10
+ import mongoose from "mongoose";
11
+ import type TestAgent from "supertest/lib/agent";
12
+
13
+ import {modelRouter} from "../api";
14
+ import {AuditApp} from "../audit/auditApp";
15
+ import {flushAuditRecorderForTests, resetAuditRecorderForTests} from "../audit/record";
16
+ import {addAuthRoutes, setupAuth, type UserModel as UserMongooseModel} from "../auth";
17
+ import {apiUnauthorizedMiddleware} from "../errors";
18
+ import {Permissions} from "../permissions";
19
+ import {createdUpdatedPlugin, type IsDeleted, isDeletedPlugin} from "../plugins";
20
+ import {SyncCounter, SyncMutation} from "../sync/models";
21
+ import {clearSyncRegistry, registerSync} from "../sync/registry";
22
+ import {SyncApp} from "../sync/syncApp";
23
+ import {syncPlugin} from "../sync/syncSeqPlugin";
24
+ import {TerrenoApp} from "../terrenoApp";
25
+ import {authAsUser, type Food, FoodModel, getBaseServer, setupDb, UserModel} from "../tests";
26
+ import {useMongoTopology} from "../tests/mongoTopology";
27
+
28
+ interface AtomicSynced extends IsDeleted {
29
+ _id: string;
30
+ _syncSeq?: number;
31
+ name: string;
32
+ ownerId: string;
33
+ }
34
+
35
+ const atomicSyncedSchema = new mongoose.Schema<AtomicSynced>({
36
+ _id: {
37
+ default: (): string => new mongoose.Types.ObjectId().toHexString(),
38
+ description: "String id so the doc can be synced",
39
+ type: String,
40
+ },
41
+ name: {description: "The name of the item", required: true, type: String},
42
+ ownerId: {description: "The user who owns this item", required: true, type: String},
43
+ });
44
+ atomicSyncedSchema.plugin(isDeletedPlugin);
45
+ atomicSyncedSchema.plugin(createdUpdatedPlugin);
46
+ atomicSyncedSchema.plugin(syncPlugin);
47
+ const AtomicSyncedModel = mongoose.model<AtomicSynced>("AtomicSynced", atomicSyncedSchema);
48
+
49
+ useMongoTopology({topology: "replicaSet"});
50
+
51
+ const allPermissions = {
52
+ create: [Permissions.IsAuthenticated],
53
+ delete: [Permissions.IsAuthenticated],
54
+ list: [Permissions.IsAuthenticated],
55
+ read: [Permissions.IsAuthenticated],
56
+ update: [Permissions.IsAuthenticated],
57
+ };
58
+
59
+ type RouterOptions = Parameters<typeof modelRouter<Food>>[1];
60
+
61
+ interface BulkEntry {
62
+ data?: Record<string, unknown>;
63
+ error?: Record<string, unknown>;
64
+ id?: string;
65
+ index: number;
66
+ method: string;
67
+ status: number;
68
+ }
69
+
70
+ const bulkFoodNames = async (): Promise<string[]> => {
71
+ const docs = await FoodModel.find({name: /^bulk-/}).sort({name: 1});
72
+ return docs.map((doc) => doc.name as string);
73
+ };
74
+
75
+ /** Reads a food with the raw driver, outside any Mongoose transaction context. */
76
+ const readFoodOutsideTransaction = async (id: string): Promise<Record<string, unknown> | null> => {
77
+ const db = mongoose.connection.db;
78
+ if (!db) {
79
+ throw new Error("mongoose is not connected");
80
+ }
81
+ return db.collection("foods").findOne({_id: new mongoose.Types.ObjectId(id)});
82
+ };
83
+
84
+ const userIdFor = async (email: string): Promise<mongoose.Types.ObjectId> => {
85
+ const user = await UserModel.findOne({email});
86
+ return (user as unknown as {_id: mongoose.Types.ObjectId})._id;
87
+ };
88
+
89
+ const makeFood = async (
90
+ fields: Partial<Food> & {created?: Date} = {}
91
+ ): Promise<mongoose.HydratedDocument<Food>> =>
92
+ FoodModel.create({calories: 1, likesIds: [], name: "bulk-old", ...fields} as never);
93
+
94
+ /** The single route's error body with the failing item's index added to `meta`. */
95
+ const withIndex = (body: Record<string, unknown>, index: number): Record<string, unknown> => ({
96
+ ...body,
97
+ meta: {...((body.meta as Record<string, unknown> | undefined) ?? {}), index},
98
+ });
99
+
100
+ describe("modelRouter bulk atomic mode (replica set)", () => {
101
+ let app: express.Application;
102
+
103
+ const mountRouter = (
104
+ path: string,
105
+ model: mongoose.Model<never>,
106
+ options: Record<string, unknown>
107
+ ): void => {
108
+ app.use(
109
+ path,
110
+ modelRouter(model, {
111
+ bulk: true,
112
+ permissions: allPermissions,
113
+ ...options,
114
+ } as never)
115
+ );
116
+ app.use(apiUnauthorizedMiddleware);
117
+ // Terminal handler so an unmatched route answers 404 instead of hanging.
118
+ app.use((_req: express.Request, res: express.Response) => {
119
+ res.status(404).json({title: "Not Found"});
120
+ });
121
+ };
122
+
123
+ const mountFood = (options: Partial<RouterOptions> = {}): void => {
124
+ mountRouter("/food", FoodModel as never, options as Record<string, unknown>);
125
+ };
126
+
127
+ beforeEach(async () => {
128
+ process.env.REFRESH_TOKEN_SECRET = "testsecret1234";
129
+ await setupDb();
130
+ await Promise.all([
131
+ FoodModel.deleteMany({}),
132
+ AtomicSyncedModel.deleteMany({}),
133
+ SyncCounter.deleteMany({}),
134
+ SyncMutation.deleteMany({}),
135
+ ]);
136
+ clearSyncRegistry();
137
+ app = getBaseServer();
138
+ setupAuth(app, UserModel as unknown as UserMongooseModel);
139
+ addAuthRoutes(app, UserModel as unknown as UserMongooseModel);
140
+ });
141
+
142
+ afterEach(() => {
143
+ clearSyncRegistry();
144
+ });
145
+
146
+ it("turns on transactionAsyncLocalStorage on the model's Mongoose instance when bulk is enabled", () => {
147
+ modelRouter(FoodModel, {bulk: true, permissions: allPermissions} as RouterOptions);
148
+ expect(FoodModel.base.get("transactionAsyncLocalStorage")).toBe(true);
149
+ });
150
+
151
+ describe("success", () => {
152
+ it("commits 3 creates when the atomic key is absent", async () => {
153
+ mountFood({bulk: true} as Partial<RouterOptions>);
154
+ const agent = await authAsUser(app, "notAdmin");
155
+ const res = await agent
156
+ .post("/food/bulk")
157
+ .send({
158
+ operations: [
159
+ {body: {name: "bulk-a"}, method: "create"},
160
+ {body: {name: "bulk-b"}, method: "create"},
161
+ {body: {name: "bulk-c"}, method: "create"},
162
+ ],
163
+ })
164
+ .expect(200);
165
+ const entries = res.body.data as BulkEntry[];
166
+ expect(entries.map((entry) => entry.status)).toEqual([201, 201, 201]);
167
+ expect(entries.map((entry) => entry.index)).toEqual([0, 1, 2]);
168
+ expect(await bulkFoodNames()).toEqual(["bulk-a", "bulk-b", "bulk-c"]);
169
+ });
170
+
171
+ it("treats an explicit atomic:true the same as the default", async () => {
172
+ mountFood({bulk: true} as Partial<RouterOptions>);
173
+ const agent = await authAsUser(app, "notAdmin");
174
+ const res = await agent
175
+ .post("/food/bulk")
176
+ .send({
177
+ atomic: true,
178
+ operations: [
179
+ {body: {name: "bulk-a"}, method: "create"},
180
+ {body: {name: "bulk-b"}, method: "create"},
181
+ ],
182
+ })
183
+ .expect(200);
184
+ expect((res.body.data as BulkEntry[]).map((entry) => entry.status)).toEqual([201, 201]);
185
+ expect(await bulkFoodNames()).toEqual(["bulk-a", "bulk-b"]);
186
+ });
187
+
188
+ it("runs postCreate, postUpdate, and postDelete once per item, after the commit", async () => {
189
+ const seenCreate: (string | undefined)[] = [];
190
+ const seenUpdate: (number | undefined)[] = [];
191
+ const seenDelete: (string | null)[] = [];
192
+ mountFood({
193
+ bulk: true,
194
+ postCreate: async (doc: Food) => {
195
+ const committed = await readFoodOutsideTransaction(String(doc._id));
196
+ seenCreate.push(committed?.name as string | undefined);
197
+ },
198
+ postDelete: async (_req: express.Request, doc: Food) => {
199
+ const committed = await readFoodOutsideTransaction(String(doc._id));
200
+ seenDelete.push(committed === null ? null : "still-there");
201
+ },
202
+ postUpdate: async (doc: Food) => {
203
+ const committed = await readFoodOutsideTransaction(String(doc._id));
204
+ seenUpdate.push(committed?.calories as number | undefined);
205
+ },
206
+ } as Partial<RouterOptions>);
207
+ const agent = await authAsUser(app, "notAdmin");
208
+ const owner = await userIdFor("notAdmin@example.com");
209
+ const toUpdate = await makeFood({calories: 1, name: "bulk-update", ownerId: owner});
210
+ const toDelete = await makeFood({name: "bulk-delete", ownerId: owner});
211
+
212
+ const res = await agent
213
+ .post("/food/bulk")
214
+ .send({
215
+ operations: [
216
+ {body: {name: "bulk-new"}, method: "create"},
217
+ {body: {calories: 42}, id: toUpdate.id, method: "update"},
218
+ {id: toDelete.id, method: "delete"},
219
+ ],
220
+ })
221
+ .expect(200);
222
+
223
+ expect((res.body.data as BulkEntry[]).map((entry) => entry.status)).toEqual([201, 200, 204]);
224
+ // Each hook read the raw collection outside the transaction and saw the committed write.
225
+ expect(seenCreate).toEqual(["bulk-new"]);
226
+ expect(seenUpdate).toEqual([42]);
227
+ expect(seenDelete).toEqual([null]);
228
+ });
229
+
230
+ it("lets a later item's preCreate see an earlier item's uncommitted create", async () => {
231
+ let foundFromHook: string | null | undefined;
232
+ mountFood({
233
+ bulk: true,
234
+ preCreate: async (body: Partial<Food>) => {
235
+ if (body.name === "bulk-b") {
236
+ const earlier = await FoodModel.findOne({name: "bulk-a"});
237
+ foundFromHook = earlier ? String(earlier._id) : null;
238
+ }
239
+ return body as Food;
240
+ },
241
+ } as Partial<RouterOptions>);
242
+ const agent = await authAsUser(app, "notAdmin");
243
+ const res = await agent
244
+ .post("/food/bulk")
245
+ .send({
246
+ operations: [
247
+ {body: {name: "bulk-a"}, method: "create"},
248
+ {body: {name: "bulk-b"}, method: "create"},
249
+ ],
250
+ })
251
+ .expect(200);
252
+ const entries = res.body.data as BulkEntry[];
253
+ expect(entries.map((entry) => entry.status)).toEqual([201, 201]);
254
+ expect(foundFromHook).toBe(entries[0].id);
255
+ });
256
+
257
+ it("keeps both creates and reports post-create-hook-error on the item whose postCreate throws", async () => {
258
+ mountFood({
259
+ bulk: true,
260
+ postCreate: (doc: Food) => {
261
+ if (doc.name === "bulk-b") {
262
+ throw new Error("boom");
263
+ }
264
+ },
265
+ } as Partial<RouterOptions>);
266
+ const agent = await authAsUser(app, "notAdmin");
267
+ const res = await agent
268
+ .post("/food/bulk")
269
+ .send({
270
+ operations: [
271
+ {body: {name: "bulk-a"}, method: "create"},
272
+ {body: {name: "bulk-b"}, method: "create"},
273
+ ],
274
+ })
275
+ .expect(200);
276
+ const entries = res.body.data as BulkEntry[];
277
+ expect(entries[0].status).toBe(201);
278
+ expect(entries[1].status).toBe(400);
279
+ expect(entries[1].error?.code).toBe("post-create-hook-error");
280
+ expect(await bulkFoodNames()).toEqual(["bulk-a", "bulk-b"]);
281
+
282
+ const single = await agent.post("/food").send({name: "bulk-b"}).expect(400);
283
+ expect(entries[1].error).toEqual(single.body);
284
+ });
285
+ it("keeps reporting later items when one item's responseHandler throws after the commit", async () => {
286
+ const postCreated: string[] = [];
287
+ mountFood({
288
+ bulk: true,
289
+ postCreate: (doc: Food) => {
290
+ postCreated.push(doc.name as string);
291
+ },
292
+ responseHandler: async (value: unknown) => {
293
+ const doc = value as {name?: string; toJSON: () => Record<string, unknown>};
294
+ if (doc.name === "bulk-a") {
295
+ throw new Error("serializer exploded");
296
+ }
297
+ return doc.toJSON() as never;
298
+ },
299
+ } as Partial<RouterOptions>);
300
+ const agent = await authAsUser(app, "notAdmin");
301
+ const res = await agent
302
+ .post("/food/bulk")
303
+ .send({
304
+ operations: [
305
+ {body: {name: "bulk-a"}, method: "create"},
306
+ {body: {name: "bulk-b"}, method: "create"},
307
+ ],
308
+ })
309
+ .expect(200);
310
+ const entries = res.body.data as BulkEntry[];
311
+ const single = await agent.post("/food").send({name: "bulk-a"});
312
+ expect(entries[0].status).toBe(single.status);
313
+ expect(entries[0].error).toEqual(single.body);
314
+ expect(entries[0].id).toEqual(expect.any(String));
315
+ expect(entries[1].status).toBe(201);
316
+ expect(postCreated).toEqual(["bulk-a", "bulk-b", "bulk-a"]);
317
+ expect(await bulkFoodNames()).toEqual(["bulk-a", "bulk-a", "bulk-b"]);
318
+ });
319
+ });
320
+
321
+ describe("abort", () => {
322
+ it("returns 403 with meta.index 1 when preCreate returns null on item 2, and writes nothing", async () => {
323
+ let postCreateCalls = 0;
324
+ mountFood({
325
+ bulk: true,
326
+ postCreate: () => {
327
+ postCreateCalls += 1;
328
+ },
329
+ preCreate: (body: Partial<Food>) => (body.name === "bulk-b" ? null : (body as Food)),
330
+ } as Partial<RouterOptions>);
331
+ const agent = await authAsUser(app, "notAdmin");
332
+ const res = await agent.post("/food/bulk").send({
333
+ operations: [
334
+ {body: {name: "bulk-a"}, method: "create"},
335
+ {body: {name: "bulk-b"}, method: "create"},
336
+ {body: {name: "bulk-c"}, method: "create"},
337
+ ],
338
+ });
339
+
340
+ expectAPIError(res, {status: 403});
341
+ expect(res.body.meta?.index).toBe(1);
342
+ expect(res.body.data).toBeUndefined();
343
+ expect(await bulkFoodNames()).toEqual([]);
344
+ expect(postCreateCalls).toBe(0);
345
+
346
+ // The failing item's body is the single route's body plus meta.index.
347
+ const single = await agent.post("/food").send({name: "bulk-b"}).expect(403);
348
+ expect(res.body).toEqual(withIndex(single.body, 1));
349
+ });
350
+
351
+ it("records no AuditEvents for an aborted batch", async () => {
352
+ resetAuditRecorderForTests();
353
+ if (mongoose.connection.models.TerrenoAuditEvent) {
354
+ mongoose.connection.deleteModel("TerrenoAuditEvent");
355
+ }
356
+ await mongoose.connection.collection("auditevents").deleteMany({});
357
+ const auditApp = new TerrenoApp({
358
+ skipListen: true,
359
+ userModel: UserModel as unknown as UserMongooseModel,
360
+ })
361
+ .register(new AuditApp())
362
+ .build();
363
+ auditApp.use(
364
+ "/food",
365
+ modelRouter(FoodModel, {
366
+ audit: true,
367
+ bulk: true,
368
+ permissions: allPermissions,
369
+ preCreate: (body: Partial<Food>) => (body.name === "bulk-b" ? null : (body as Food)),
370
+ } as RouterOptions)
371
+ );
372
+ try {
373
+ const agent = await authAsUser(auditApp, "notAdmin");
374
+ const res = await agent.post("/food/bulk").send({
375
+ operations: [
376
+ {body: {name: "bulk-a"}, method: "create"},
377
+ {body: {name: "bulk-b"}, method: "create"},
378
+ {body: {name: "bulk-c"}, method: "create"},
379
+ ],
380
+ });
381
+ expectAPIError(res, {status: 403});
382
+ expect(res.body.meta?.index).toBe(1);
383
+
384
+ await flushAuditRecorderForTests();
385
+ const adminAgent = await authAsUser(auditApp, "admin");
386
+ const list = await adminAgent.get("/audit-events").expect(200);
387
+ expect(list.body.data).toHaveLength(0);
388
+ } finally {
389
+ resetAuditRecorderForTests();
390
+ if (mongoose.connection.models.TerrenoAuditEvent) {
391
+ mongoose.connection.deleteModel("TerrenoAuditEvent");
392
+ }
393
+ }
394
+ });
395
+
396
+ it("records one AuditEvent per item only after a committed batch", async () => {
397
+ resetAuditRecorderForTests();
398
+ if (mongoose.connection.models.TerrenoAuditEvent) {
399
+ mongoose.connection.deleteModel("TerrenoAuditEvent");
400
+ }
401
+ await mongoose.connection.collection("auditevents").deleteMany({});
402
+ const auditApp = new TerrenoApp({
403
+ skipListen: true,
404
+ userModel: UserModel as unknown as UserMongooseModel,
405
+ })
406
+ .register(new AuditApp())
407
+ .build();
408
+ auditApp.use(
409
+ "/food",
410
+ modelRouter(FoodModel, {
411
+ audit: true,
412
+ bulk: true,
413
+ permissions: allPermissions,
414
+ } as RouterOptions)
415
+ );
416
+ try {
417
+ const agent = await authAsUser(auditApp, "notAdmin");
418
+ await agent
419
+ .post("/food/bulk")
420
+ .send({
421
+ operations: [
422
+ {body: {name: "bulk-a"}, method: "create"},
423
+ {body: {name: "bulk-b"}, method: "create"},
424
+ ],
425
+ })
426
+ .expect(200);
427
+
428
+ await flushAuditRecorderForTests();
429
+ const adminAgent = await authAsUser(auditApp, "admin");
430
+ const list = await adminAgent.get("/audit-events?verb=created").expect(200);
431
+ const names = list.body.data.map((event: {after: {name: string}}) => event.after.name);
432
+ expect(names.sort()).toEqual(["bulk-a", "bulk-b"]);
433
+ } finally {
434
+ resetAuditRecorderForTests();
435
+ if (mongoose.connection.models.TerrenoAuditEvent) {
436
+ mongoose.connection.deleteModel("TerrenoAuditEvent");
437
+ }
438
+ }
439
+ });
440
+
441
+ it("returns 403 with meta.index 1 when update B is forbidden, and leaves update A unapplied", async () => {
442
+ mountFood({
443
+ bulk: true,
444
+ permissions: {...allPermissions, update: [Permissions.IsOwner]},
445
+ } as Partial<RouterOptions>);
446
+ const agent = await authAsUser(app, "notAdmin");
447
+ const owner = await userIdFor("notAdmin@example.com");
448
+ const other = await userIdFor("admin@example.com");
449
+ const mine = await makeFood({calories: 1, name: "bulk-mine", ownerId: owner});
450
+ const theirs = await makeFood({calories: 1, name: "bulk-theirs", ownerId: other});
451
+
452
+ const res = await agent.post("/food/bulk").send({
453
+ operations: [
454
+ {body: {calories: 2}, id: mine.id, method: "update"},
455
+ {body: {calories: 2}, id: theirs.id, method: "update"},
456
+ ],
457
+ });
458
+
459
+ expectAPIError(res, {status: 403});
460
+ expect(res.body.meta?.index).toBe(1);
461
+ expect(res.body.data).toBeUndefined();
462
+ expect((await FoodModel.findById(mine.id))?.calories).toBe(1);
463
+ expect((await FoodModel.findById(theirs.id))?.calories).toBe(1);
464
+ });
465
+
466
+ it("returns 400 with meta.index 1 for an invalid create after a delete, and keeps the deleted doc", async () => {
467
+ mountFood({bulk: true} as Partial<RouterOptions>);
468
+ const agent = await authAsUser(app, "notAdmin");
469
+ const owner = await userIdFor("notAdmin@example.com");
470
+ const doomed = await makeFood({name: "bulk-doomed", ownerId: owner});
471
+
472
+ const res = await agent.post("/food/bulk").send({
473
+ operations: [
474
+ {id: doomed.id, method: "delete"},
475
+ {body: {eatenBy: ["not-an-object-id"], name: "bulk-invalid"}, method: "create"},
476
+ ],
477
+ });
478
+
479
+ expectAPIError(res, {status: 400});
480
+ expect(res.body.meta?.index).toBe(1);
481
+ expect(res.body.meta?.fields).toBeDefined();
482
+ expect(await readFoodOutsideTransaction(doomed.id)).not.toBeNull();
483
+ expect(await bulkFoodNames()).toEqual(["bulk-doomed"]);
484
+ });
485
+
486
+ it("rolls back a write a preCreate hook made to another model when a later item aborts", async () => {
487
+ mountFood({
488
+ bulk: true,
489
+ preCreate: async (body: Partial<Food>) => {
490
+ if (body.name === "bulk-a") {
491
+ await UserModel.updateOne(
492
+ {email: "notAdmin@example.com"},
493
+ {$set: {name: "written-by-hook"}}
494
+ );
495
+ return body as Food;
496
+ }
497
+ return null;
498
+ },
499
+ } as Partial<RouterOptions>);
500
+ const agent = await authAsUser(app, "notAdmin");
501
+ const before = await UserModel.findOne({email: "notAdmin@example.com"});
502
+
503
+ const res = await agent.post("/food/bulk").send({
504
+ operations: [
505
+ {body: {name: "bulk-a"}, method: "create"},
506
+ {body: {name: "bulk-b"}, method: "create"},
507
+ ],
508
+ });
509
+
510
+ expectAPIError(res, {status: 403});
511
+ expect(res.body.meta?.index).toBe(1);
512
+ const after = await UserModel.findOne({email: "notAdmin@example.com"});
513
+ expect(after?.name).toBe(before?.name as string);
514
+ expect(after?.name).not.toBe("written-by-hook");
515
+ expect(await bulkFoodNames()).toEqual([]);
516
+ });
517
+
518
+ it("returns the PATCH 409 body plus meta.index for a stale _updatedAt, and applies no other item", async () => {
519
+ mountFood({bulk: true} as Partial<RouterOptions>);
520
+ const agent = await authAsUser(app, "notAdmin");
521
+ const owner = await userIdFor("notAdmin@example.com");
522
+ const created = DateTime.fromISO("2024-06-01T12:00:00.000Z").toJSDate();
523
+ const fresh = await makeFood({calories: 1, name: "bulk-fresh", ownerId: owner});
524
+ const stale = await makeFood({
525
+ calories: 1,
526
+ created,
527
+ name: "bulk-stale",
528
+ ownerId: owner,
529
+ } as never);
530
+ const staleAt = "2024-01-01T00:00:00.000Z";
531
+
532
+ const single = await agent
533
+ .patch(`/food/${stale.id}`)
534
+ .send({_updatedAt: staleAt, calories: 2})
535
+ .expect(409);
536
+
537
+ const res = await agent.post("/food/bulk").send({
538
+ operations: [
539
+ {body: {calories: 5}, id: fresh.id, method: "update"},
540
+ {body: {_updatedAt: staleAt, calories: 2}, id: stale.id, method: "update"},
541
+ {body: {name: "bulk-new"}, method: "create"},
542
+ ],
543
+ });
544
+
545
+ expect(res.status).toBe(409);
546
+ expect(res.body).toEqual(withIndex(single.body, 1));
547
+ expect((await FoodModel.findById(fresh.id))?.calories).toBe(1);
548
+ expect((await FoodModel.findById(stale.id))?.calories).toBe(1);
549
+ expect(await FoodModel.countDocuments({name: "bulk-new"})).toBe(0);
550
+ });
551
+
552
+ it("returns 409 bulk-transaction-conflict on a transient write conflict, without retrying hooks", async () => {
553
+ let preUpdateCalls = 0;
554
+ mountFood({
555
+ bulk: true,
556
+ preUpdate: async (body: Partial<Food>, req: express.Request) => {
557
+ preUpdateCalls += 1;
558
+ // Write the same doc outside the transaction after its snapshot began, so the
559
+ // transaction's own write to it hits a WriteConflict (TransientTransactionError).
560
+ const db = mongoose.connection.db;
561
+ if (!db) {
562
+ throw new Error("mongoose is not connected");
563
+ }
564
+ await db
565
+ .collection("foods")
566
+ .updateOne(
567
+ {_id: new mongoose.Types.ObjectId(String(req.params.id))},
568
+ {$set: {calories: 99}}
569
+ );
570
+ return body as Food;
571
+ },
572
+ } as Partial<RouterOptions>);
573
+ const agent = await authAsUser(app, "notAdmin");
574
+ const owner = await userIdFor("notAdmin@example.com");
575
+ const target = await makeFood({calories: 1, name: "bulk-target", ownerId: owner});
576
+
577
+ const res = await agent.post("/food/bulk").send({
578
+ operations: [
579
+ {body: {name: "bulk-new"}, method: "create"},
580
+ {body: {calories: 2}, id: target.id, method: "update"},
581
+ ],
582
+ });
583
+
584
+ expectAPIError(res, {code: "bulk-transaction-conflict", status: 409});
585
+ expect(preUpdateCalls).toBe(1);
586
+ expect(await FoodModel.countDocuments({name: "bulk-new"})).toBe(0);
587
+ // Only the hook's out-of-transaction write landed.
588
+ expect((await readFoodOutsideTransaction(target.id))?.calories).toBe(99);
589
+ });
590
+ });
591
+
592
+ describe("synced model", () => {
593
+ it("an aborted batch does not stall the sync stream for a later PATCH", async () => {
594
+ const options = {permissions: allPermissions, sync: {scope: {type: "owner"}}};
595
+ registerSync({
596
+ config: {scope: {type: "owner"}},
597
+ model: AtomicSyncedModel as never,
598
+ options: options as never,
599
+ routePath: "/synced",
600
+ });
601
+ new SyncApp().register(app);
602
+ mountRouter("/synced", AtomicSyncedModel as never, options);
603
+ const agent: TestAgent = await authAsUser(app, "notAdmin");
604
+ const owner = (await userIdFor("notAdmin@example.com")).toString();
605
+ const doc = await AtomicSyncedModel.create({name: "synced-a", ownerId: owner});
606
+ const stream = encodeURIComponent(`synced|owner:${owner}`);
607
+
608
+ const initial = await agent.get(`/sync/snapshot?stream=${stream}`).expect(200);
609
+ const cursor = initial.body.cursor as number;
610
+
611
+ const aborted = await agent.post("/synced/bulk").send({
612
+ operations: [
613
+ {body: {name: "synced-in-batch"}, id: doc.id, method: "update"},
614
+ {body: {ownerId: owner}, method: "create"},
615
+ ],
616
+ });
617
+ expectAPIError(aborted, {status: 400});
618
+ expect(aborted.body.meta?.index).toBe(1);
619
+ expect((await AtomicSyncedModel.findById(doc.id))?.name).toBe("synced-a");
620
+
621
+ await agent.patch(`/synced/${doc.id}`).send({name: "synced-patched"}).expect(200);
622
+
623
+ const delta = await agent.get(`/sync/snapshot?stream=${stream}&cursor=${cursor}`).expect(200);
624
+ const entity = (delta.body.entities as {data: {name: string} | null; id: string}[]).find(
625
+ (candidate) => candidate.id === doc.id
626
+ );
627
+ expect(entity?.data?.name).toBe("synced-patched");
628
+ });
629
+ });
630
+ });