@terreno/api 58.0.5 → 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 +58 -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
package/src/bulk.ts ADDED
@@ -0,0 +1,680 @@
1
+ /**
2
+ * `POST /<route>/bulk` for modelRouter: many create/update/delete operations in one request.
3
+ *
4
+ * Every item runs through the same transport-agnostic executors as `POST /`, `PATCH /:id`, and
5
+ * `DELETE /:id` (`sync/executors.ts`), so it gets the router's method and object permissions,
6
+ * transformer, pre/post hooks, RBAC write guards, Mongoose validation, population, audit, and
7
+ * `responseHandler`. Hooks receive a per-item request whose `body` is the item's body and whose
8
+ * `params.id` is the item's id.
9
+ *
10
+ * Docs: docs/reference/api.md ("modelRouter bulk writes").
11
+ */
12
+ import type express from "express";
13
+ import type {Request, Response} from "express";
14
+ import type {Document, Model} from "mongoose";
15
+
16
+ import type {JSONValue, ModelRouterOptions} from "./api";
17
+ import {maybeRecordModelRouterAudit, snapshotAuditBefore} from "./audit/record";
18
+ import type {authenticateMiddleware} from "./auth";
19
+ import {bulkOpenApiMiddleware} from "./bulkOpenApi";
20
+ import {
21
+ enableTransactionAsyncLocalStorage,
22
+ isBulkCommitUnknownError,
23
+ isTransientTransactionError,
24
+ runInBulkTransaction,
25
+ supportsTransactions,
26
+ } from "./bulkTransaction";
27
+ import type {loadDocOr404} from "./docLoader";
28
+ import {
29
+ APIError,
30
+ type APIErrorBody,
31
+ errorMessage,
32
+ isAPIError,
33
+ logAndCaptureAPIError,
34
+ mongooseErrorToAPIError,
35
+ passthroughOrWrap,
36
+ serializeAPIError,
37
+ } from "./errors";
38
+ import {
39
+ conflictResponseBody,
40
+ methodPermissionDeniedError,
41
+ timestampConcurrencyCheck,
42
+ } from "./modelRouterWrites";
43
+ import type {checkPermissions} from "./permissions";
44
+ import type {
45
+ executeCreate,
46
+ executeDelete,
47
+ executeUpdate,
48
+ isExecutorConflictError,
49
+ runPostCreate,
50
+ runPostDelete,
51
+ runPostUpdate,
52
+ } from "./sync/executors";
53
+
54
+ /** The write operations a bulk request may carry. */
55
+ export type BulkMethod = "create" | "update" | "delete";
56
+
57
+ /** `ModelRouterOptions.bulk` object form. */
58
+ export interface ModelRouterBulkOptions {
59
+ /** Most operations one request may carry. Defaults to {@link DEFAULT_BULK_MAX_ITEMS}. */
60
+ maxItems?: number;
61
+ /** Operations this router accepts in a bulk request. Defaults to all three. */
62
+ methods?: BulkMethod[];
63
+ }
64
+
65
+ /** Default cap on operations per bulk request, matching the sync batch limit. */
66
+ const DEFAULT_BULK_MAX_ITEMS = 100;
67
+
68
+ const BULK_METHODS: BulkMethod[] = ["create", "update", "delete"];
69
+
70
+ interface ResolvedBulkOptions {
71
+ maxItems: number;
72
+ methods: BulkMethod[];
73
+ }
74
+
75
+ /** One parsed operation from the request envelope. */
76
+ type BulkOperation =
77
+ | {method: "create"; body: Record<string, unknown>}
78
+ | {method: "update"; id: string; body: Record<string, unknown>}
79
+ | {method: "delete"; id: string};
80
+
81
+ interface BulkRequest {
82
+ atomic: boolean;
83
+ operations: BulkOperation[];
84
+ }
85
+
86
+ /** One entry of the bulk response, in input order. */
87
+ interface BulkItemResult {
88
+ index: number;
89
+ method: BulkMethod;
90
+ id?: string;
91
+ status: number;
92
+ data?: JSONValue;
93
+ /** The body the single route would have sent for this failure (for a 409, the PATCH 409 body). */
94
+ error?: APIErrorBody | Record<string, unknown>;
95
+ }
96
+
97
+ type ResponseHandler<T> = NonNullable<ModelRouterOptions<T>["responseHandler"]>;
98
+
99
+ /** Validates one item body the way the single route's body validation middleware would. */
100
+ export type BulkBodyValidator = (args: {
101
+ method: "create" | "update";
102
+ body: Record<string, unknown>;
103
+ req: Request;
104
+ }) => Record<string, unknown>;
105
+
106
+ /**
107
+ * Runtime functions the bulk route needs from modules that themselves import `api.ts`. `api.ts`
108
+ * passes them in so this module never imports them at runtime (no import cycle).
109
+ */
110
+ export interface BulkRouteDeps {
111
+ authenticateMiddleware: typeof authenticateMiddleware;
112
+ checkPermissions: typeof checkPermissions;
113
+ executeCreate: typeof executeCreate;
114
+ executeDelete: typeof executeDelete;
115
+ executeUpdate: typeof executeUpdate;
116
+ isExecutorConflictError: typeof isExecutorConflictError;
117
+ loadDocOr404: typeof loadDocOr404;
118
+ runPostCreate: typeof runPostCreate;
119
+ runPostDelete: typeof runPostDelete;
120
+ runPostUpdate: typeof runPostUpdate;
121
+ }
122
+
123
+ /** Resolves `ModelRouterOptions.bulk` to concrete limits, or null when bulk is off. */
124
+ const resolveBulkOptions = (
125
+ bulk: boolean | ModelRouterBulkOptions | undefined
126
+ ): ResolvedBulkOptions | null => {
127
+ if (!bulk) {
128
+ return null;
129
+ }
130
+ const config = bulk === true ? {} : bulk;
131
+ return {
132
+ maxItems: config.maxItems ?? DEFAULT_BULK_MAX_ITEMS,
133
+ methods: config.methods ?? BULK_METHODS,
134
+ };
135
+ };
136
+
137
+ /**
138
+ * Throws at registration when bulk is enabled and a collection action already owns `/bulk`.
139
+ * Actions mount before CRUD and would silently shadow the bulk route.
140
+ */
141
+ export const assertNoBulkCollision = <T>(
142
+ options: Pick<ModelRouterOptions<T>, "bulk" | "collectionActions">
143
+ ): void => {
144
+ if (!resolveBulkOptions(options.bulk)) {
145
+ return;
146
+ }
147
+ if (options.collectionActions && Object.hasOwn(options.collectionActions, "bulk")) {
148
+ throw new APIError({
149
+ detail: "Rename the collection action or turn off `bulk` on this router.",
150
+ status: 500,
151
+ title: "collectionAction 'bulk' collides with the bulk endpoint on /bulk",
152
+ });
153
+ }
154
+ };
155
+
156
+ const envelopeError = (detail: string): APIError =>
157
+ new APIError({code: "bulk-invalid-request", detail, status: 400, title: "Invalid bulk request"});
158
+
159
+ const isPlainObject = (value: unknown): value is Record<string, unknown> =>
160
+ Boolean(value) && typeof value === "object" && !Array.isArray(value);
161
+
162
+ const parseOperation = (
163
+ raw: unknown,
164
+ index: number,
165
+ config: ResolvedBulkOptions
166
+ ): BulkOperation => {
167
+ if (!isPlainObject(raw)) {
168
+ throw envelopeError(`operations[${index}] must be an object`);
169
+ }
170
+ const method = raw.method;
171
+ if (typeof method !== "string" || !BULK_METHODS.includes(method as BulkMethod)) {
172
+ throw envelopeError(`operations[${index}].method must be one of ${BULK_METHODS.join(", ")}`);
173
+ }
174
+ if (!config.methods.includes(method as BulkMethod)) {
175
+ throw envelopeError(`operations[${index}].method '${method}' is not enabled for bulk`);
176
+ }
177
+ if (method !== "create" && (typeof raw.id !== "string" || raw.id.length === 0)) {
178
+ throw envelopeError(`operations[${index}].id is required for ${method}`);
179
+ }
180
+ if (method !== "delete" && !isPlainObject(raw.body)) {
181
+ throw envelopeError(`operations[${index}].body must be an object for ${method}`);
182
+ }
183
+ if (method === "create") {
184
+ return {body: raw.body as Record<string, unknown>, method};
185
+ }
186
+ if (method === "update") {
187
+ return {body: raw.body as Record<string, unknown>, id: raw.id as string, method};
188
+ }
189
+ return {id: raw.id as string, method: "delete"};
190
+ };
191
+
192
+ /** Parses and checks the whole envelope before any write. Throws a 400 on any defect. */
193
+ const parseBulkRequest = (body: unknown, config: ResolvedBulkOptions): BulkRequest => {
194
+ if (!isPlainObject(body)) {
195
+ throw envelopeError("Body must be an object with an operations array");
196
+ }
197
+ if (body.atomic !== undefined && typeof body.atomic !== "boolean") {
198
+ throw envelopeError("atomic must be a boolean");
199
+ }
200
+ const operations = body.operations;
201
+ if (!Array.isArray(operations)) {
202
+ throw envelopeError("operations must be an array");
203
+ }
204
+ if (operations.length === 0) {
205
+ throw envelopeError("operations must not be empty");
206
+ }
207
+ if (operations.length > config.maxItems) {
208
+ throw envelopeError(`operations may hold at most ${config.maxItems} items`);
209
+ }
210
+ return {
211
+ atomic: body.atomic ?? true,
212
+ operations: operations.map((raw, index) => parseOperation(raw, index, config)),
213
+ };
214
+ };
215
+
216
+ /**
217
+ * @internal Exported for tests.
218
+ * Maps any error from one item to the status and JSON body the single route's error middleware
219
+ * would send, and logs/captures it the same way.
220
+ */
221
+ export const toBulkItemError = (error: unknown): {status: number; body: APIErrorBody} => {
222
+ let apiError: APIError | null = isAPIError(error) ? error : null;
223
+ if (!apiError && error instanceof Error) {
224
+ apiError = mongooseErrorToAPIError(error);
225
+ }
226
+ if (!apiError) {
227
+ // Same client body as apiFallthroughErrorMiddleware: no internal message leaks to the caller.
228
+ apiError = new APIError({cause: error, status: 500, title: "Internal server error"});
229
+ }
230
+ logAndCaptureAPIError(apiError);
231
+ return {body: serializeAPIError(apiError), status: apiError.status};
232
+ };
233
+
234
+ /** The request a hook sees for one item: the real request with this item's body and id. */
235
+ const buildItemRequest = (req: Request, body: unknown, id?: string): Request => {
236
+ const itemReq = Object.create(req) as Request;
237
+ itemReq.body = body;
238
+ itemReq.params = id ? {...req.params, id} : {...req.params};
239
+ return itemReq;
240
+ };
241
+
242
+ interface ItemContext<T> {
243
+ deps: BulkRouteDeps;
244
+ model: Model<T>;
245
+ options: ModelRouterOptions<T>;
246
+ req: Request;
247
+ responseHandler: ResponseHandler<T>;
248
+ validateBody: BulkBodyValidator;
249
+ }
250
+
251
+ const serializeItem = async <T>(
252
+ ctx: ItemContext<T>,
253
+ doc: Document<unknown, unknown, unknown> & T,
254
+ method: "create" | "update",
255
+ itemReq: Request
256
+ ): Promise<JSONValue> => {
257
+ try {
258
+ return await ctx.responseHandler(doc, method, itemReq, ctx.options);
259
+ } catch (error: unknown) {
260
+ throw passthroughOrWrap(error, {
261
+ code: "response-handler-error",
262
+ title: "responseHandler error",
263
+ });
264
+ }
265
+ };
266
+
267
+ // Method permission before body validation, the same order as the single routes
268
+ // (permissionMiddleware, then validation), so an unpermitted caller gets 405, not schema details.
269
+ const assertMethodPermission = async <T>(
270
+ ctx: ItemContext<T>,
271
+ method: "create" | "update"
272
+ ): Promise<void> => {
273
+ if (await ctx.deps.checkPermissions(method, ctx.options.permissions[method], ctx.req.user)) {
274
+ return;
275
+ }
276
+ throw methodPermissionDeniedError({
277
+ method,
278
+ modelName: ctx.model.modelName,
279
+ userId: ctx.req.user?.id,
280
+ });
281
+ };
282
+
283
+ const hookErrorResult = (
284
+ error: unknown,
285
+ wrapper: {code: string; detail?: string; title: string},
286
+ result: {id: string; index: number; method: BulkMethod}
287
+ ): BulkItemResult => {
288
+ const {body, status} = toBulkItemError(passthroughOrWrap(error, {...wrapper, status: 400}));
289
+ return {...result, error: body, status};
290
+ };
291
+
292
+ /**
293
+ * An item whose write succeeded. `finish` runs the post hook, audit, and `responseHandler`;
294
+ * in atomic mode that happens only after the transaction commits.
295
+ */
296
+ interface WrittenItem {
297
+ finish: () => Promise<BulkItemResult>;
298
+ }
299
+
300
+ /** An item whose write was refused with a response body (an executor conflict). */
301
+ interface RefusedItem {
302
+ refused: BulkItemResult;
303
+ }
304
+
305
+ type ItemWrite = WrittenItem | RefusedItem;
306
+
307
+ const writeCreateItem = async <T>(
308
+ ctx: ItemContext<T>,
309
+ operation: Extract<BulkOperation, {method: "create"}>,
310
+ index: number
311
+ ): Promise<ItemWrite> => {
312
+ await assertMethodPermission(ctx, "create");
313
+ const itemReq = buildItemRequest(ctx.req, operation.body);
314
+ const body = ctx.validateBody({body: operation.body, method: "create", req: itemReq});
315
+ itemReq.body = body;
316
+ const {doc} = await ctx.deps.executeCreate<T>({
317
+ body,
318
+ model: ctx.model,
319
+ options: ctx.options,
320
+ req: itemReq,
321
+ skipPostHooks: true,
322
+ user: ctx.req.user,
323
+ });
324
+ const id = String(doc._id);
325
+ const finish = async (): Promise<BulkItemResult> => {
326
+ try {
327
+ await ctx.deps.runPostCreate({doc, options: ctx.options, request: itemReq});
328
+ } catch (error: unknown) {
329
+ return hookErrorResult(
330
+ error,
331
+ {code: "post-create-hook-error", title: "postCreate hook error"},
332
+ {id, index, method: "create"}
333
+ );
334
+ }
335
+ void maybeRecordModelRouterAudit({
336
+ after: doc,
337
+ audit: ctx.options.audit,
338
+ modelName: ctx.model.modelName,
339
+ operation: "create",
340
+ recordId: id,
341
+ req: itemReq,
342
+ verb: "created",
343
+ });
344
+ try {
345
+ const data = await serializeItem(ctx, doc, "create", itemReq);
346
+ return {data, id, index, method: "create", status: 201};
347
+ } catch (error: unknown) {
348
+ // The doc is written: keep its id so the client knows what exists before any retry.
349
+ return {...failedResult(error, "create", index), id};
350
+ }
351
+ };
352
+ return {finish};
353
+ };
354
+
355
+ const writeUpdateItem = async <T>(
356
+ ctx: ItemContext<T>,
357
+ operation: Extract<BulkOperation, {method: "update"}>,
358
+ index: number
359
+ ): Promise<ItemWrite> => {
360
+ const {id} = operation;
361
+ await assertMethodPermission(ctx, "update");
362
+ const itemReq = buildItemRequest(ctx.req, operation.body, id);
363
+ const body = ctx.validateBody({body: operation.body, method: "update", req: itemReq});
364
+ itemReq.body = body;
365
+
366
+ let result: Awaited<ReturnType<typeof executeUpdate<T>>>;
367
+ try {
368
+ result = await ctx.deps.executeUpdate<T>({
369
+ body,
370
+ concurrencyCheck: timestampConcurrencyCheck({bodyUpdatedAt: body._updatedAt}),
371
+ id,
372
+ model: ctx.model,
373
+ options: ctx.options,
374
+ req: itemReq,
375
+ skipPostHooks: true,
376
+ user: ctx.req.user,
377
+ });
378
+ } catch (error: unknown) {
379
+ if (!ctx.deps.isExecutorConflictError(error)) {
380
+ throw error;
381
+ }
382
+ // Exactly the body PATCH /:id sends for a conflict, including the current server doc.
383
+ const data = await serializeItem(
384
+ ctx,
385
+ error.doc as Document<unknown, unknown, unknown> & T,
386
+ "update",
387
+ itemReq
388
+ );
389
+ return {
390
+ refused: {
391
+ error: conflictResponseBody(data),
392
+ id,
393
+ index,
394
+ method: "update",
395
+ status: 409,
396
+ },
397
+ };
398
+ }
399
+
400
+ const {doc, cleanedBody, prevDoc} = result;
401
+ const finish = async (): Promise<BulkItemResult> => {
402
+ try {
403
+ await ctx.deps.runPostUpdate({
404
+ cleanedBody: cleanedBody as Partial<T>,
405
+ doc,
406
+ options: ctx.options,
407
+ prevDoc: prevDoc as T,
408
+ request: itemReq,
409
+ });
410
+ } catch (error: unknown) {
411
+ return hookErrorResult(
412
+ error,
413
+ {
414
+ code: "post-update-hook-error",
415
+ detail: `postUpdate hook error on ${id}: ${errorMessage(error)}`,
416
+ title: "postUpdate hook error",
417
+ },
418
+ {id, index, method: "update"}
419
+ );
420
+ }
421
+ void maybeRecordModelRouterAudit({
422
+ after: doc,
423
+ audit: ctx.options.audit,
424
+ before: snapshotAuditBefore({
425
+ audit: ctx.options.audit,
426
+ doc: prevDoc as {toJSON?: () => unknown},
427
+ }),
428
+ modelName: ctx.model.modelName,
429
+ operation: "update",
430
+ recordId: String(doc._id),
431
+ req: itemReq,
432
+ verb: "updated",
433
+ });
434
+ try {
435
+ const data = await serializeItem(ctx, doc, "update", itemReq);
436
+ return {data, id, index, method: "update", status: 200};
437
+ } catch (error: unknown) {
438
+ return {...failedResult(error, "update", index), id};
439
+ }
440
+ };
441
+ return {finish};
442
+ };
443
+
444
+ const writeDeleteItem = async <T>(
445
+ ctx: ItemContext<T>,
446
+ operation: Extract<BulkOperation, {method: "delete"}>,
447
+ index: number
448
+ ): Promise<ItemWrite> => {
449
+ const {id} = operation;
450
+ const itemReq = buildItemRequest(ctx.req, {}, id);
451
+ const {doc, prevDoc} = await ctx.deps.executeDelete<T>({
452
+ id,
453
+ model: ctx.model,
454
+ options: ctx.options,
455
+ req: itemReq,
456
+ skipPostHooks: true,
457
+ user: ctx.req.user,
458
+ });
459
+ if (!prevDoc) {
460
+ // executeDelete treats an already soft-deleted doc as an idempotent success for the sync
461
+ // channel (and then returns no prevDoc). DELETE /:id answers 404 there, so bulk does too:
462
+ // loading the tombstone through the normal loader throws that same 404.
463
+ await ctx.deps.loadDocOr404(ctx.model, id, ctx.options.populatePaths);
464
+ }
465
+ const finish = async (): Promise<BulkItemResult> => {
466
+ try {
467
+ await ctx.deps.runPostDelete({doc, options: ctx.options, request: itemReq});
468
+ } catch (error: unknown) {
469
+ return hookErrorResult(
470
+ error,
471
+ {code: "post-delete-hook-error", title: "postDelete hook error"},
472
+ {id, index, method: "delete"}
473
+ );
474
+ }
475
+ void maybeRecordModelRouterAudit({
476
+ audit: ctx.options.audit,
477
+ before: snapshotAuditBefore({
478
+ audit: ctx.options.audit,
479
+ doc: (prevDoc ?? doc) as {toJSON?: () => unknown},
480
+ }),
481
+ modelName: ctx.model.modelName,
482
+ operation: "delete",
483
+ recordId: String(doc._id),
484
+ req: itemReq,
485
+ verb: "deleted",
486
+ });
487
+ return {id, index, method: "delete", status: 204};
488
+ };
489
+ return {finish};
490
+ };
491
+
492
+ const writeItem = <T>(
493
+ ctx: ItemContext<T>,
494
+ operation: BulkOperation,
495
+ index: number
496
+ ): Promise<ItemWrite> => {
497
+ if (operation.method === "create") {
498
+ return writeCreateItem(ctx, operation, index);
499
+ }
500
+ if (operation.method === "update") {
501
+ return writeUpdateItem(ctx, operation, index);
502
+ }
503
+ return writeDeleteItem(ctx, operation, index);
504
+ };
505
+
506
+ const failedResult = (error: unknown, method: BulkMethod, index: number): BulkItemResult => {
507
+ const {body, status} = toBulkItemError(error);
508
+ return {error: body, index, method, status};
509
+ };
510
+
511
+ const failedItemResult = (
512
+ error: unknown,
513
+ operation: BulkOperation,
514
+ index: number
515
+ ): BulkItemResult => {
516
+ const result = failedResult(error, operation.method, index);
517
+ return operation.method === "create" ? result : {...result, id: operation.id};
518
+ };
519
+
520
+ /** Partial mode: each item commits on its own; a failure is recorded and the batch continues. */
521
+ const runPartial = async <T>(
522
+ ctx: ItemContext<T>,
523
+ operations: BulkOperation[]
524
+ ): Promise<BulkItemResult[]> => {
525
+ const results: BulkItemResult[] = [];
526
+ for (const [index, operation] of operations.entries()) {
527
+ try {
528
+ const written = await writeItem(ctx, operation, index);
529
+ results.push("refused" in written ? written.refused : await written.finish());
530
+ } catch (error: unknown) {
531
+ results.push(failedItemResult(error, operation, index));
532
+ }
533
+ }
534
+ return results;
535
+ };
536
+
537
+ /** Thrown inside the atomic transaction to abort it with one item's response. */
538
+ class BulkItemAbort extends Error {
539
+ constructor(readonly result: BulkItemResult) {
540
+ super("Bulk item failed");
541
+ }
542
+ }
543
+
544
+ const transactionConflictError = (cause: unknown): APIError =>
545
+ new APIError({
546
+ cause,
547
+ code: "bulk-transaction-conflict",
548
+ detail: "Another write touched the same documents. Nothing was written; retry the request.",
549
+ status: 409,
550
+ title: "Bulk transaction conflict",
551
+ });
552
+
553
+ /**
554
+ * Atomic mode: every item's write runs in one transaction. The first failure aborts it and
555
+ * becomes the whole response (that item's status and body plus `meta.index`). After a commit,
556
+ * post hooks, audit, and `responseHandler` run per item, in order.
557
+ */
558
+ const runAtomic = async <T>(
559
+ ctx: ItemContext<T>,
560
+ operations: BulkOperation[],
561
+ res: Response
562
+ ): Promise<void> => {
563
+ if (!(await supportsTransactions(ctx.model.db))) {
564
+ throw new APIError({
565
+ code: "bulk-atomic-unsupported",
566
+ detail: "Atomic bulk mode requires a replica set; send atomic:false for per-item writes.",
567
+ status: 400,
568
+ title: "Atomic bulk writes are not supported by this database",
569
+ });
570
+ }
571
+
572
+ let written: WrittenItem[];
573
+ try {
574
+ written = await runInBulkTransaction({
575
+ base: ctx.model.base,
576
+ connection: ctx.model.db,
577
+ fn: async (): Promise<WrittenItem[]> => {
578
+ const items: WrittenItem[] = [];
579
+ for (const [index, operation] of operations.entries()) {
580
+ let write: ItemWrite;
581
+ try {
582
+ write = await writeItem(ctx, operation, index);
583
+ } catch (error: unknown) {
584
+ if (isTransientTransactionError(error)) {
585
+ throw error;
586
+ }
587
+ throw new BulkItemAbort(failedItemResult(error, operation, index));
588
+ }
589
+ if ("refused" in write) {
590
+ throw new BulkItemAbort(write.refused);
591
+ }
592
+ items.push(write);
593
+ }
594
+ return items;
595
+ },
596
+ });
597
+ } catch (error: unknown) {
598
+ if (error instanceof BulkItemAbort) {
599
+ const {error: body, index, status} = error.result;
600
+ const errorBody = (body ?? {}) as Record<string, unknown>;
601
+ const meta = (errorBody.meta ?? {}) as Record<string, unknown>;
602
+ res.status(status).json({...errorBody, meta: {...meta, index}});
603
+ return;
604
+ }
605
+ if (isTransientTransactionError(error)) {
606
+ throw transactionConflictError(error);
607
+ }
608
+ if (isBulkCommitUnknownError(error)) {
609
+ throw new APIError({
610
+ cause: error,
611
+ code: "bulk-commit-unknown",
612
+ detail:
613
+ "The database did not confirm the commit. The writes may or may not have been applied; " +
614
+ "read the documents before retrying.",
615
+ status: 500,
616
+ title: "Bulk transaction outcome unknown",
617
+ });
618
+ }
619
+ throw error;
620
+ }
621
+
622
+ // The writes are committed: one item's post-commit failure (e.g. its responseHandler) must not
623
+ // hide the others' results or skip their post hooks and audit.
624
+ const results: BulkItemResult[] = [];
625
+ for (const [position, item] of written.entries()) {
626
+ try {
627
+ results.push(await item.finish());
628
+ } catch (error: unknown) {
629
+ results.push(failedItemResult(error, operations[position], position));
630
+ }
631
+ }
632
+ res.json({data: results});
633
+ };
634
+
635
+ /**
636
+ * Mounts `POST /bulk` on a modelRouter's router when `options.bulk` is set. Call with the
637
+ * collection actions, before user `endpoints` and the `/:id` routes.
638
+ */
639
+ export const registerBulkRoute = <T>({
640
+ deps,
641
+ router,
642
+ model,
643
+ options,
644
+ responseHandler,
645
+ validateBody,
646
+ }: {
647
+ deps: BulkRouteDeps;
648
+ router: express.Router;
649
+ model: Model<T>;
650
+ options: ModelRouterOptions<T>;
651
+ responseHandler: ResponseHandler<T>;
652
+ validateBody: BulkBodyValidator;
653
+ }): void => {
654
+ const config = resolveBulkOptions(options.bulk);
655
+ if (!config) {
656
+ return;
657
+ }
658
+ // Atomic requests join every Mongoose operation (hook writes included) to their transaction.
659
+ enableTransactionAsyncLocalStorage(model.base);
660
+ const ctxBase = {deps, model, options, responseHandler, validateBody};
661
+
662
+ router.post(
663
+ "/bulk",
664
+ deps.authenticateMiddleware(options.allowAnonymous),
665
+ bulkOpenApiMiddleware({model, options, ...config}),
666
+ async (req: Request, res: Response, next: express.NextFunction): Promise<void> => {
667
+ try {
668
+ const request = parseBulkRequest(req.body, config);
669
+ const ctx: ItemContext<T> = {...ctxBase, req};
670
+ if (request.atomic) {
671
+ await runAtomic(ctx, request.operations, res);
672
+ return;
673
+ }
674
+ res.json({data: await runPartial(ctx, request.operations)});
675
+ } catch (error: unknown) {
676
+ next(error);
677
+ }
678
+ }
679
+ );
680
+ };