-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathbatch.zod.ts
More file actions
299 lines (264 loc) · 10.6 KB
/
Copy pathbatch.zod.ts
File metadata and controls
299 lines (264 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { z } from 'zod';
import { ApiErrorSchema, BaseResponseSchema, RecordDataSchema } from './contract.zod';
/**
* Batch Operations API
*
* Provides efficient bulk data operations with transaction support.
* Implements P0/P1 requirements for ObjectStack kernel.
*
* Features:
* - Batch create/update/delete operations
* - Atomic transaction support (all-or-none)
* - Partial success handling
* - Detailed error reporting per record
*
* Industry alignment: Salesforce Bulk API, Microsoft Dynamics Bulk Operations
*/
// ==========================================
// Batch Operation Types
// ==========================================
/**
* Batch Operation Type Enum
* Defines the type of batch operation to perform
*/
import { lazySchema } from '../shared/lazy-schema';
export const BatchOperationType = z.enum([
'create', // Batch insert
'update', // Batch update
'upsert', // Batch upsert (insert or update based on external ID)
'delete', // Batch delete
]);
export type BatchOperationType = z.infer<typeof BatchOperationType>;
// ==========================================
// Batch Request Schemas
// ==========================================
/**
* Batch Record Schema
* Individual record in a batch operation
*/
export const BatchRecordSchema = lazySchema(() => z.object({
id: z.string().optional().describe('Record ID (required for update/delete)'),
data: RecordDataSchema.optional().describe('Record data (required for create/update/upsert)'),
externalId: z.string().optional().describe('External ID for upsert matching'),
}));
export type BatchRecord = z.infer<typeof BatchRecordSchema>;
/**
* Batch Operation Options Schema
* Configuration options for batch operations
*/
export const BatchOptionsSchema = lazySchema(() => z.object({
atomic: z.boolean().optional().default(true).describe('If true, rollback entire batch on any failure (transaction mode)'),
returnRecords: z.boolean().optional().default(false).describe('If true, return full record data in response'),
continueOnError: z.boolean().optional().default(false).describe('If true (and atomic=false), continue processing remaining records after errors'),
validateOnly: z.boolean().optional().default(false).describe('If true, validate records without persisting changes (dry-run mode)'),
}));
export type BatchOptions = z.infer<typeof BatchOptionsSchema>;
/**
* Batch Update Request Schema
* Request payload for batch update operations
*
* @example
* // POST /api/v1/data/{object}/batch
* {
* "operation": "update",
* "records": [
* { "id": "1", "data": { "name": "Updated Name 1", "status": "active" } },
* { "id": "2", "data": { "name": "Updated Name 2", "status": "active" } }
* ],
* "options": {
* "atomic": true,
* "returnRecords": true
* }
* }
*/
export const BatchUpdateRequestSchema = lazySchema(() => z.object({
operation: BatchOperationType.describe('Type of batch operation'),
records: z.array(BatchRecordSchema).min(1).max(200).describe('Array of records to process (max 200 per batch)'),
options: BatchOptionsSchema.optional().describe('Batch operation options'),
}));
export type BatchUpdateRequest = z.input<typeof BatchUpdateRequestSchema>;
/**
* Simplified Batch Update Request (for updateMany API)
* Simplified request for batch updates without operation field
*
* @example
* // POST /api/v1/data/{object}/updateMany
* {
* "records": [
* { "id": "1", "data": { "name": "Updated Name 1" } },
* { "id": "2", "data": { "name": "Updated Name 2" } }
* ],
* "options": { "atomic": true }
* }
*/
export const UpdateManyRequestSchema = lazySchema(() => z.object({
records: z.array(BatchRecordSchema).min(1).max(200).describe('Array of records to update (max 200 per batch)'),
options: BatchOptionsSchema.optional().describe('Update options'),
}));
export type UpdateManyRequest = z.input<typeof UpdateManyRequestSchema>;
// ==========================================
// Batch Response Schemas
// ==========================================
/**
* Batch Operation Result Schema
* Result for a single record in a batch operation
*/
export const BatchOperationResultSchema = lazySchema(() => z.object({
id: z.string().optional().describe('Record ID if operation succeeded'),
success: z.boolean().describe('Whether this record was processed successfully'),
errors: z.array(ApiErrorSchema).optional().describe('Array of errors if operation failed'),
data: RecordDataSchema.optional().describe('Full record data (if returnRecords=true)'),
index: z.number().optional().describe('Index of the record in the request array'),
}));
export type BatchOperationResult = z.infer<typeof BatchOperationResultSchema>;
/**
* Batch Update Response Schema
* Response payload for batch operations
*
* @example Success Response
* {
* "success": true,
* "operation": "update",
* "total": 2,
* "succeeded": 2,
* "failed": 0,
* "results": [
* { "id": "1", "success": true, "index": 0 },
* { "id": "2", "success": true, "index": 1 }
* ],
* "meta": {
* "timestamp": "2026-01-29T12:00:00Z",
* "duration": 150
* }
* }
*
* @example Partial Success Response (atomic=false)
* {
* "success": false,
* "operation": "update",
* "total": 2,
* "succeeded": 1,
* "failed": 1,
* "results": [
* { "id": "1", "success": true, "index": 0 },
* {
* "success": false,
* "index": 1,
* "errors": [{ "code": "validation_error", "message": "Invalid email format" }]
* }
* ],
* "meta": {
* "timestamp": "2026-01-29T12:00:00Z"
* }
* }
*/
export const BatchUpdateResponseSchema = lazySchema(() => BaseResponseSchema.extend({
operation: BatchOperationType.optional().describe('Operation type that was performed'),
total: z.number().describe('Total number of records in the batch'),
succeeded: z.number().describe('Number of records that succeeded'),
failed: z.number().describe('Number of records that failed'),
results: z.array(BatchOperationResultSchema).describe('Detailed results for each record'),
}));
export type BatchUpdateResponse = z.infer<typeof BatchUpdateResponseSchema>;
// ==========================================
// Batch Delete Schemas
// ==========================================
/**
* Batch Delete Request Schema
* Simplified request for batch delete operations
*
* @example
* // POST /api/v1/data/{object}/deleteMany
* {
* "ids": ["1", "2", "3"],
* "options": { "atomic": true }
* }
*/
export const DeleteManyRequestSchema = lazySchema(() => z.object({
ids: z.array(z.string()).min(1).max(200).describe('Array of record IDs to delete (max 200)'),
options: BatchOptionsSchema.optional().describe('Delete options'),
}));
export type DeleteManyRequest = z.infer<typeof DeleteManyRequestSchema>;
// ==========================================
// API Contract Exports
// ==========================================
/**
* Batch API Contracts
* Standardized contracts for batch operations
*/
export const BatchApiContracts = {
batchOperation: {
input: BatchUpdateRequestSchema,
output: BatchUpdateResponseSchema,
},
updateMany: {
input: UpdateManyRequestSchema,
output: BatchUpdateResponseSchema,
},
deleteMany: {
input: DeleteManyRequestSchema,
output: BatchUpdateResponseSchema,
},
};
/**
* Batch Configuration Schema
*
* Configuration for enabling batch operations API.
*/
export const BatchConfigSchema = lazySchema(() => z.object({
/** Enable batch operations */
enabled: z.boolean().default(true).describe('Enable batch operations'),
/** Maximum records per batch */
maxRecordsPerBatch: z.number().int().min(1).max(1000).default(200).describe('Maximum records per batch'),
/** Default options */
defaultOptions: BatchOptionsSchema.optional().describe('Default batch options'),
}).passthrough()); // Allow additional properties
export type BatchConfig = z.infer<typeof BatchConfigSchema>;
// ==========================================
// Cross-Object Transactional Batch (issue #1604)
// ==========================================
/**
* A single operation in a cross-object transactional batch. Targets one object
* with a create/update/delete action. A value inside `data` may carry an
* intra-batch reference `{ $ref: <earlier op index> }` that the server resolves
* to that op's created id — so a child row can point at a parent created earlier
* in the SAME transaction (master-detail). See ADR-0034 / #1604.
*/
export const CrossObjectBatchOperationSchema = lazySchema(() => z.object({
object: z.string().min(1).describe('Target object (table) name'),
action: z.enum(['create', 'update', 'delete']).optional().default('create').describe('Operation to perform (default: create)'),
id: z.string().optional().describe('Target record id — required for update and delete'),
data: RecordDataSchema.optional().describe('Record payload for create/update; a value may be { $ref: <opIndex> } to reference an earlier op\'s created id'),
}));
export type CrossObjectBatchOperation = z.input<typeof CrossObjectBatchOperationSchema>;
/**
* Request payload for the cross-object transactional batch
* (`POST {basePath}/batch`). Every operation runs in ONE engine transaction —
* commit all or roll back all. `atomic` is accepted for contract symmetry but
* MUST be true (the endpoint is all-or-nothing by construction); a non-atomic
* per-object batch is served by `POST /data/:object/batch` instead.
*
* @example
* // POST /api/v1/batch — parent + child in one transaction (master-detail)
* {
* "operations": [
* { "object": "project", "action": "create", "data": { "name": "Apollo" } },
* { "object": "task", "action": "create", "data": { "title": "Kickoff", "project": { "$ref": 0 } } }
* ]
* }
*/
export const CrossObjectBatchRequestSchema = lazySchema(() => z.object({
operations: z.array(CrossObjectBatchOperationSchema).max(1000).describe('Ordered operations executed in one transaction'),
atomic: z.boolean().optional().default(true).describe('Always true — the cross-object batch is all-or-nothing'),
}));
export type CrossObjectBatchRequest = z.input<typeof CrossObjectBatchRequestSchema>;
/**
* Response for the cross-object transactional batch — one result per operation,
* index-aligned with the request `operations` (create/update echo the record,
* delete echoes the driver's delete result).
*/
export const CrossObjectBatchResponseSchema = lazySchema(() => z.object({
results: z.array(z.unknown()).describe('Per-operation result, index-aligned with the request operations'),
}));
export type CrossObjectBatchResponse = z.infer<typeof CrossObjectBatchResponseSchema>;