-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathrest-batch-endpoint.test.ts
More file actions
232 lines (205 loc) · 10.6 KB
/
Copy pathrest-batch-endpoint.test.ts
File metadata and controls
232 lines (205 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
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
//
// Cross-object transactional batch route (POST {basePath}/batch, issue #1604 /
// ADR-0034). Engine-level atomicity is covered in
// objectql/src/engine-ambient-transaction.test.ts; this suite is the
// REST-boundary contract ADR-0034 flagged as missing: request validation,
// per-op API-exposure enforcement, $ref resolution, and error surfacing.
import { describe, it, expect, vi } from 'vitest';
import { RestServer } from './rest-server';
// ── helpers ──────────────────────────────────────────────────────────────────
function mockServer() {
return {
get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn(), patch: vi.fn(),
use: vi.fn(), listen: vi.fn().mockResolvedValue(undefined), close: vi.fn().mockResolvedValue(undefined),
};
}
function mockRes() {
const res: any = { statusCode: 200, body: undefined };
res.status = vi.fn((c: number) => { res.statusCode = c; return res; });
res.json = vi.fn((b: any) => { res.body = b; return res; });
res.end = vi.fn(() => res);
return res;
}
/**
* A fake ObjectQL whose `transaction(cb)` runs the callback and rethrows on
* failure (mirroring commit-on-success / rollback-on-throw). `insert` returns a
* freshly-minted id so `$ref` resolution and index-aligned results are testable.
*/
function makeQl(overrides: Partial<Record<'insert' | 'update' | 'delete', any>> = {}) {
let seq = 0;
const ql: any = {
transaction: vi.fn(async (cb: any, ctx: any) => cb({ __trx: true, ctx })),
insert: overrides.insert ?? vi.fn(async (_object: string, data: any) => ({ id: `id_${++seq}`, ...data })),
update: overrides.update ?? vi.fn(async (_object: string, data: any) => ({ ...data })),
delete: overrides.delete ?? vi.fn(async (_object: string, arg: any) => ({ success: true, id: arg?.where?.id })),
};
return ql;
}
/** Build a RestServer with an optional ObjectQL provider and object metadata. */
function buildServer(opts: { ql?: any; objects?: any[] } = {}) {
const server = mockServer();
const protocol: any = {
getDiscovery: vi.fn().mockResolvedValue({ version: 'v0', endpoints: {} }),
getMetaTypes: vi.fn().mockResolvedValue([]),
getMetaItems: vi.fn().mockResolvedValue(opts.objects ?? []),
};
const objectQLProvider = opts.ql ? async () => opts.ql : undefined;
const rest = new RestServer(
server as any, protocol as any, { api: { requireAuth: false } } as any,
undefined, undefined, undefined, undefined, // kernelManager, envRegistry, defaultEnvIdProvider, authServiceProvider
objectQLProvider, // objectQLProvider (positional arg #8)
);
rest.registerRoutes();
const route = rest.getRoutes().find(
(r) => r.method === 'POST' && (r.metadata?.summary ?? '').startsWith('Cross-object'),
);
return { route, protocol };
}
/** POST a body at the cross-object batch route and return the mock response. */
async function post(route: any, body: any) {
const res = mockRes();
await route!.handler({ method: 'POST', params: {}, headers: {}, body } as any, res);
return res;
}
// ── registration ─────────────────────────────────────────────────────────────
describe('POST {basePath}/batch — cross-object transactional batch', () => {
it('registers the route under the data/batch tags', () => {
const { route } = buildServer({ ql: makeQl() });
expect(route).toBeTruthy();
expect(route!.metadata?.tags).toEqual(expect.arrayContaining(['data', 'batch']));
});
it('returns 501 when the runtime has no transactional ObjectQL', async () => {
const { route } = buildServer({}); // no ql provider
const res = await post(route, { operations: [{ object: 'account', data: {} }] });
expect(res.statusCode).toBe(501);
});
// ── happy path ───────────────────────────────────────────────────────────
it('commits multiple ops in one transaction and returns index-aligned results', async () => {
const ql = makeQl();
const { route } = buildServer({ ql });
const res = await post(route, {
operations: [
{ object: 'project', action: 'create', data: { name: 'Apollo' } },
{ object: 'task', action: 'create', data: { title: 'Kickoff' } },
],
});
expect(res.statusCode).toBe(200);
expect(ql.transaction).toHaveBeenCalledTimes(1);
expect(ql.insert).toHaveBeenCalledTimes(2);
expect(res.body.results).toHaveLength(2);
expect(res.body.results[0]).toMatchObject({ id: 'id_1', name: 'Apollo' });
expect(res.body.results[1]).toMatchObject({ id: 'id_2', title: 'Kickoff' });
});
it('resolves { $ref: <opIndex> } to an earlier create\'s id (master-detail)', async () => {
const ql = makeQl();
const { route } = buildServer({ ql });
const res = await post(route, {
operations: [
{ object: 'project', action: 'create', data: { name: 'Apollo' } },
{ object: 'task', action: 'create', data: { title: 'Kickoff', project: { $ref: 0 } } },
],
});
expect(res.statusCode).toBe(200);
// The child's FK was rewritten from { $ref: 0 } to the parent's generated id.
const childData = ql.insert.mock.calls[1][1];
expect(childData.project).toBe('id_1');
});
it('defaults a missing action to create', async () => {
const ql = makeQl();
const { route } = buildServer({ ql });
const res = await post(route, { operations: [{ object: 'account', data: { name: 'X' } }] });
expect(res.statusCode).toBe(200);
expect(ql.insert).toHaveBeenCalledTimes(1);
});
it('returns an empty result set for zero operations without opening a transaction', async () => {
const ql = makeQl();
const { route } = buildServer({ ql });
const res = await post(route, { operations: [] });
expect(res.statusCode).toBe(200);
expect(res.body).toEqual({ results: [] });
expect(ql.transaction).not.toHaveBeenCalled();
});
// ── atomicity / rollback surfacing ────────────────────────────────────────
it('surfaces a failing op with its mapped status (atomic rollback, not partial success)', async () => {
const insert = vi.fn()
.mockResolvedValueOnce({ id: 'id_1', name: 'Apollo' })
.mockRejectedValueOnce(Object.assign(new Error('bad'), { code: 'VALIDATION_FAILED', name: 'ValidationError' }));
const ql = makeQl({ insert });
const { route } = buildServer({ ql });
const res = await post(route, {
operations: [
{ object: 'project', action: 'create', data: { name: 'Apollo' } },
{ object: 'task', action: 'create', data: {} },
],
});
expect(res.statusCode).toBe(400);
expect(res.body.code).toBe('VALIDATION_FAILED');
// No success envelope is returned when the transaction threw.
expect(res.body.results).toBeUndefined();
});
it('rejects an unresolvable $ref with 400 BATCH_UNRESOLVED_REF', async () => {
const ql = makeQl();
const { route } = buildServer({ ql });
const res = await post(route, {
operations: [{ object: 'task', action: 'create', data: { project: { $ref: 5 } } }],
});
expect(res.statusCode).toBe(400);
expect(res.body.code).toBe('BATCH_UNRESOLVED_REF');
});
// ── per-object API-exposure enforcement (ADR-0049) ────────────────────────
it('blocks a write to an API-disabled object with 404 before opening a transaction', async () => {
const ql = makeQl();
const { route } = buildServer({ ql, objects: [{ name: 'secret', enable: { apiEnabled: false } }] });
const res = await post(route, { operations: [{ object: 'secret', action: 'create', data: {} }] });
expect(res.statusCode).toBe(404);
expect(res.body.code).toBe('OBJECT_API_DISABLED');
expect(ql.transaction).not.toHaveBeenCalled();
});
it('blocks an operation absent from the apiMethods whitelist with 405', async () => {
const ql = makeQl();
const { route } = buildServer({ ql, objects: [{ name: 'ledger', enable: { apiMethods: ['read'] } }] });
const res = await post(route, { operations: [{ object: 'ledger', action: 'create', data: {} }] });
expect(res.statusCode).toBe(405);
expect(res.body.code).toBe('OBJECT_API_METHOD_NOT_ALLOWED');
expect(ql.transaction).not.toHaveBeenCalled();
});
it('allows an operation that IS in the apiMethods whitelist', async () => {
const ql = makeQl();
const { route } = buildServer({ ql, objects: [{ name: 'ledger', enable: { apiMethods: ['create', 'read'] } }] });
const res = await post(route, { operations: [{ object: 'ledger', action: 'create', data: { amount: 1 } }] });
expect(res.statusCode).toBe(200);
expect(ql.transaction).toHaveBeenCalledTimes(1);
});
// ── request validation ────────────────────────────────────────────────────
it('rejects a non-atomic request (this endpoint is always atomic)', async () => {
const ql = makeQl();
const { route } = buildServer({ ql });
const res = await post(route, { operations: [{ object: 'account', data: {} }], atomic: false });
expect(res.statusCode).toBe(400);
expect(res.body.code).toBe('BATCH_NOT_ATOMIC');
expect(ql.transaction).not.toHaveBeenCalled();
});
it('rejects an update op with no id', async () => {
const ql = makeQl();
const { route } = buildServer({ ql });
const res = await post(route, { operations: [{ object: 'account', action: 'update', data: { name: 'X' } }] });
expect(res.statusCode).toBe(400);
expect(res.body.code).toBe('VALIDATION_FAILED');
expect(ql.transaction).not.toHaveBeenCalled();
});
it('rejects a malformed operation (missing object) with 400', async () => {
const ql = makeQl();
const { route } = buildServer({ ql });
const res = await post(route, { operations: [{ action: 'create', data: {} }] });
expect(res.statusCode).toBe(400);
expect(res.body.code).toBe('VALIDATION_FAILED');
});
it('rejects an unknown action with 400', async () => {
const ql = makeQl();
const { route } = buildServer({ ql });
const res = await post(route, { operations: [{ object: 'account', action: 'frobnicate', data: {} }] });
expect(res.statusCode).toBe(400);
expect(res.body.code).toBe('VALIDATION_FAILED');
});
});