Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .changeset/35726-batch-refusal-failed-operation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
'@objectstack/rest': patch
'@object-ui/plugin-detail': patch
---

feat(rest): a refused cross-object batch names the operation that caused it, and a related list's multi-pick add names that record

Clause-②: yes (widening)
Metadata-protocol: none

`POST {basePath}/batch` (the cross-object transactional batch) now adds `failedOperation: { index, object }` to its refusal body when one operation is the cause: `index` is that operation's position in the request's `operations`, and `object` is the object it named. It rides beside the existing `error`, `code` and `userMessage`. It is present when an `update` or `delete` op is refused up front for naming no row (`400 VALIDATION_FAILED`), and when an op fails while the transaction runs (for example `404 RECORD_NOT_FOUND`, a `400 VALIDATION_FAILED` validation refusal, `400 BATCH_UNRESOLVED_REF`, `409 RESOURCE_CONFLICT`). It is absent when the request as a whole is refused (schema, `atomic: false`, size, no transaction), on the per-object API exposure and API-key management refusals, which are judged once per object and action, and on a failure after the last op ran.

The key is additive. The success body does not change, and the batch stays all or nothing: a refused batch writes no row. Through `@objectstack/client` the key reaches `err.details.failedOperation`, because the client hands a flat refusal body with no `details` of its own over as `err.details`. A refusal that carries its own `details` (a package-scoped `409 RESOURCE_CONFLICT` with `details.candidates`) still carries the key on the body, but the client exposes only its `details` there.

The related list's "Add" picker (`@object-ui/plugin-detail`) uses it: when a multi-pick add is refused for one picked record, the inline error names that record by the label the picker shows, followed by the server's reason. A refusal without an index inside the operations sent shows the server's reason alone, as before.
53 changes: 50 additions & 3 deletions packages/rest/src/batch-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,42 @@ function bulkReportStatus(report: unknown): 200 | 207 {
return typeof failed === 'number' && failed > 0 ? 207 : 200;
}

/**
* [#35726] The operation a refusal of the whole cross-object batch is FOR: its
* position in the request's `operations` and the object that op named. It
* rides the refusal body as `failedOperation`, beside `error` / `code` /
* `userMessage`, so a caller that sent several ops can say which one failed:
* the console's related-list add names the picked record at that index. A
* refusal's own sentence names the record for a not-found or a permission
* refusal, but a validation refusal names only the field.
*
* Present only when one op is the cause: an op refused up front for naming no
* row, and an op that threw while the transaction ran (the engine's refusal of
* that op, an unresolved `$ref`, a fault). Absent on a refusal of the request
* as a whole (schema, `atomic: false`, size, no transaction), on an
* object-level gate (API exposure, the API-key management rule: judged once per
* object and action, so no single op is the cause), and on a failure after the
* last op ran. Additive: the success body and the all-or-none outcome do not
* change (ADR-0119 D4); nothing is written either way.
*/
type FailedBatchOperation = { index: number; object: string };

/**
* `res` as the shared error door writes to it (`res.status(s).json(body)`),
* with `failedOperation` added to the JSON body. The door still decides the
* status, the code and the sentence; this adds one key to what it decided.
* With no failed operation it is `res` itself.
*/
function namingFailedOperation(res: any, failedOperation: FailedBatchOperation | undefined): any {
if (!failedOperation) return res;
const named = Object.create(res);
named.status = (code: number) => { res.status(code); return named; };
named.json = (body: unknown) => res.json(
body && typeof body === 'object' && !Array.isArray(body) ? { ...body, failedOperation } : body,
);
return named;
}

/**
* Register batch operation endpoints — `RestServer#registerBatchEndpoints`'
* body, called by that method with the server as `this`. The method's own
Expand Down Expand Up @@ -227,6 +263,9 @@ export function registerBatchEndpoints(this: BatchRouteHost, basePath: string):
method: 'POST',
path: `${basePath}/batch`,
handler: async (req: any, res: any) => {
// [#35726] The op being run when a throw left the transaction; see
// {@link FailedBatchOperation}.
let failedOperation: FailedBatchOperation | undefined;
try {
const environmentId = isScoped ? req.params?.environmentId : undefined;
const context = await this.resolveExecCtx(environmentId, req);
Expand Down Expand Up @@ -340,9 +379,13 @@ export function registerBatchEndpoints(this: BatchRouteHost, basePath: string):
// conditionally, so surface it as a 400 up front. "Missing" is
// the address the op's arm would hand the engine naming no row
// (`namesNoRow`): a blank id gets the answer an absent one does.
for (const op of ops) {
for (const [index, op] of ops.entries()) {
if ((op.action === 'update' || op.action === 'delete') && namesNoRow(op.action, batchOpRowAddress(op, op.data))) {
res.status(400).json({ error: `Operation '${op.action}' on '${op.object}' requires an id`, code: 'VALIDATION_FAILED' });
res.status(400).json({
error: `Operation '${op.action}' on '${op.object}' requires an id`,
code: 'VALIDATION_FAILED',
failedOperation: { index, object: op.object } satisfies FailedBatchOperation,
});
return;
}
}
Expand Down Expand Up @@ -452,6 +495,7 @@ export function registerBatchEndpoints(this: BatchRouteHost, basePath: string):
entered = true;
const out: any[] = [];
for (const [index, op] of ops.entries()) {
failedOperation = { index, object: op.object };
const data = resolveRefs(op.data, out);
if (op.action === 'create') {
// [#3835] Go through the protocol's create ingress —
Expand Down Expand Up @@ -513,6 +557,8 @@ export function registerBatchEndpoints(this: BatchRouteHost, basePath: string):
out.push(await ql.delete(op.object, { where: { id: batchOpRowAddress(op, data) }, context: trxCtx }));
}
}
// Every op ran: a failure from here on (the commit) is no one op's.
failedOperation = undefined;
return out;
};
let results: any[];
Expand Down Expand Up @@ -542,7 +588,8 @@ export function registerBatchEndpoints(this: BatchRouteHost, basePath: string):
// keeps that one loud while staying quiet on the coded 4xx.
// [#32250] A package-scoped refusal names its candidates
// (`details.candidates`), as on every `/data` door.
handleRouteError(res, error, undefined, PACKAGE_SCOPED_CANDIDATES);
// [#35726] An op's own failure names that op (`failedOperation`).
handleRouteError(namingFailedOperation(res, failedOperation), error, undefined, PACKAGE_SCOPED_CANDIDATES);
}
},
metadata: {
Expand Down
140 changes: 140 additions & 0 deletions packages/rest/src/cross-object-batch-failed-operation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* [#35726] A refusal of the cross-object `POST {basePath}/batch` names the op
* that caused it: `failedOperation: { index, object }`, beside the `error` /
* `code` the shared error door answered, so a caller that sent several ops can
* say which one failed (the console's related-list add names the picked
* record at that index).
*
* Real engine (`ObjectQL`), real protocol, real `RestServer` route, over a
* SQLite driver that rolls back, so "nothing landed" is read from the table.
*
* Controls: a batch that commits carries no such key, and a refusal of the
* request as a whole (`atomic: false`) names no op. The route has no
* non-atomic run to pin: `atomic: false` is refused before any op runs.
*/

import { describe, it, expect, afterEach } from 'vitest';
import { ObjectQL } from '@objectstack/objectql';
import { SqlDriver } from '@objectstack/driver-sql';
import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol';
import { RestServer } from './rest-server';

const ALPHA = {
name: 'fop_alpha', label: 'Alpha', systemFields: false,
fields: {
id: { name: 'id', type: 'text' as const, primaryKey: true },
title: { name: 'title', type: 'text' as const },
},
};
const BETA = {
name: 'fop_beta', label: 'Beta', systemFields: false,
fields: {
id: { name: 'id', type: 'text' as const, primaryKey: true },
title: { name: 'title', type: 'text' as const, required: true },
},
};

const liveEngines: ObjectQL[] = [];
afterEach(async () => {
while (liveEngines.length) {
try { await liveEngines.pop()?.destroy(); } catch { /* noop */ }
}
});

function createMockServer() {
const noop = () => {};
return { get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} };
}

function makeRes() {
const res: any = {
write: () => true, end: () => {},
header: () => res,
status: (code: number) => { res._status = code; return res; },
json: (body: any) => { res._json = body; return res; },
};
return res;
}

async function boot() {
const engine = new ObjectQL();
liveEngines.push(engine);
engine.registerDriver(new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), true);
await engine.init();
engine.registry.registerObject(ALPHA as any);
engine.registry.registerObject(BETA as any);
await engine.syncSchemas();

const protocol = new ObjectStackProtocolImplementation(engine as any);
const rest = new RestServer(
createMockServer() as any, protocol as any, { api: { requireAuth: false } } as any,
undefined, undefined, undefined, undefined, // kernelManager, envRegistry, defaultEnvIdProvider, authServiceProvider
(async () => engine) as any, // objectQLProvider (positional arg #8)
);
(rest as any).resolveExecCtx = async () => ({ userId: 'test-user' });
rest.registerRoutes();
const route = rest.getRoutes().find((r: any) => r.method === 'POST' && r.path === '/api/v1/batch');
expect(route, 'POST /api/v1/batch').toBeDefined();
const batch = async (operations: unknown[], extra: Record<string, unknown> = {}) => {
const res = makeRes();
await route!.handler({ method: 'POST', params: {}, query: {}, headers: {}, body: { operations, ...extra } } as any, res);
return { status: res._status ?? 200, body: res._json };
};
const rows = async (object: string) => (await engine.find(object, {})) as any[];
return { batch, rows };
}

describe('[#35726] a refused cross-object batch names the op that failed', () => {
it('3 ops, the 2nd addresses no row: index 1 and its object, and nothing lands', async () => {
const ctx = await boot();
const answer = await ctx.batch([
{ object: 'fop_alpha', action: 'create', data: { id: 'a-1', title: 'First' } },
{ object: 'fop_beta', action: 'update', id: 'no-such-row', data: { title: 'Second' } },
{ object: 'fop_alpha', action: 'create', data: { id: 'a-2', title: 'Third' } },
]);
expect(answer.status).toBe(404);
expect(answer.body.code).toBe('RECORD_NOT_FOUND');
expect(answer.body.failedOperation).toEqual({ index: 1, object: 'fop_beta' });
expect(await ctx.rows('fop_alpha')).toEqual([]);
expect(await ctx.rows('fop_beta')).toEqual([]);
});

it('3 ops, the 2nd misses a required field: index 1 beside the validation refusal, and nothing lands', async () => {
const ctx = await boot();
const answer = await ctx.batch([
{ object: 'fop_alpha', action: 'create', data: { id: 'a-1', title: 'First' } },
{ object: 'fop_beta', action: 'create', data: { id: 'b-1' } },
{ object: 'fop_alpha', action: 'create', data: { id: 'a-2', title: 'Third' } },
]);
expect(answer.status).toBe(400);
expect(answer.body.code).toBe('VALIDATION_FAILED');
expect(answer.body.failedOperation).toEqual({ index: 1, object: 'fop_beta' });
expect(await ctx.rows('fop_alpha')).toEqual([]);
expect(await ctx.rows('fop_beta')).toEqual([]);
});

it('control: a batch that commits carries no failedOperation', async () => {
const ctx = await boot();
const answer = await ctx.batch([
{ object: 'fop_alpha', action: 'create', data: { id: 'a-1', title: 'First' } },
{ object: 'fop_beta', action: 'create', data: { id: 'b-1', title: 'Second' } },
{ object: 'fop_alpha', action: 'create', data: { id: 'a-2', title: 'Third' } },
]);
expect(answer.status).toBe(200);
expect(answer.body).not.toHaveProperty('failedOperation');
expect(answer.body.results.map((r: any) => r.id)).toEqual(['a-1', 'b-1', 'a-2']);
});

it('control: a refusal of the request as a whole (atomic: false) names no op', async () => {
const ctx = await boot();
const answer = await ctx.batch([
{ object: 'fop_alpha', action: 'create', data: { id: 'a-1', title: 'First' } },
], { atomic: false });
expect(answer.status).toBe(400);
expect(answer.body.code).toBe('BATCH_NOT_ATOMIC');
expect(answer.body).not.toHaveProperty('failedOperation');
expect(await ctx.rows('fop_alpha')).toEqual([]);
});
});
7 changes: 5 additions & 2 deletions packages/rest/src/rest-batch-blank-id.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,12 @@ async function boot() {
}

const O = 'blank_id_task';
const missingId = (action: 'update' | 'delete') => ({
// [#35726] The refusal names the op it is for (`failedOperation`): its index in
// `operations` and its object.
const missingId = (action: 'update' | 'delete', index = 0) => ({
error: `Operation '${action}' on '${O}' requires an id`,
code: 'VALIDATION_FAILED',
failedOperation: { index, object: O },
});

/** Every op here names no row the engine could address; the arm is the op's own. */
Expand Down Expand Up @@ -131,7 +134,7 @@ describe('POST /api/v1/batch: an update or delete op that names no row answers t
{ object: O, action: 'create', data: { id: 'row-2', title: 'New' } },
{ object: O, action: 'update', id: '', data: { title: 'Changed' } },
]);
expect({ status: res.status, body: res.body }).toEqual({ status: 400, body: missingId('update') });
expect({ status: res.status, body: res.body }).toEqual({ status: 400, body: missingId('update', 1) });
expect(ctx.transaction).not.toHaveBeenCalled();
expect(await ctx.row('row-2')).toBeFalsy();
});
Expand Down
12 changes: 7 additions & 5 deletions packages/rest/src/rest-batch-endpoint.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -432,6 +432,8 @@ describe('POST {basePath}/batch — a package-scoped refusal names its candidate
candidates: CANDIDATES,
};
const REFUSAL = { ...BASE, message: packageScopedRefusalMessage(BASE) };
/** [#35726] The refusal names the one op it is for. */
const FAILED = { failedOperation: { index: 0, object: 'account' } };

/** A refusal of the class's shape, carrying `candidates` as given. */
const shaped = (candidates: unknown): Error => Object.assign(new Error(REFUSAL.message), {
Expand All @@ -456,19 +458,19 @@ describe('POST {basePath}/batch — a package-scoped refusal names its candidate
it('the class, thrown by a create op: 409 RESOURCE_CONFLICT with details.candidates', async () => {
const res = await refuse(new PackageScopedNameRefusedError(REFUSAL));
expect(res.statusCode).toBe(409);
expect(res.body).toEqual({ error: REFUSAL.message, code: 'RESOURCE_CONFLICT', details: { candidates: CANDIDATES } });
expect(res.body).toEqual({ error: REFUSAL.message, code: 'RESOURCE_CONFLICT', details: { candidates: CANDIDATES }, ...FAILED });
});

it('the class, thrown by an update op: the same answer', async () => {
const res = await refuse(new PackageScopedNameRefusedError(REFUSAL), 'update');
expect(res.statusCode).toBe(409);
expect(res.body).toEqual({ error: REFUSAL.message, code: 'RESOURCE_CONFLICT', details: { candidates: CANDIDATES } });
expect(res.body).toEqual({ error: REFUSAL.message, code: 'RESOURCE_CONFLICT', details: { candidates: CANDIDATES }, ...FAILED });
});

it('a plain error of the class\'s shape: the same answer', async () => {
const res = await refuse(shaped(CANDIDATES));
expect(res.statusCode).toBe(409);
expect(res.body).toEqual({ error: REFUSAL.message, code: 'RESOURCE_CONFLICT', details: { candidates: CANDIDATES } });
expect(res.body).toEqual({ error: REFUSAL.message, code: 'RESOURCE_CONFLICT', details: { candidates: CANDIDATES }, ...FAILED });
});

it('a holder of each of the four kinds is answered as it was thrown', async () => {
Expand All @@ -493,13 +495,13 @@ describe('POST {basePath}/batch — a package-scoped refusal names its candidate
it(`a list holding ${name}: 409 RESOURCE_CONFLICT with no details`, async () => {
const res = await refuse(shaped(candidates));
expect(res.statusCode).toBe(409);
expect(res.body).toEqual({ error: REFUSAL.message, code: 'RESOURCE_CONFLICT' });
expect(res.body).toEqual({ error: REFUSAL.message, code: 'RESOURCE_CONFLICT', ...FAILED });
});
}

it('CONTROL: a RESOURCE_CONFLICT thrown with no refusal carries no details', async () => {
const res = await refuse(Object.assign(new Error('The record is in conflict.'), { code: 'RESOURCE_CONFLICT', status: 409 }));
expect(res.statusCode).toBe(409);
expect(res.body).toEqual({ error: 'The record is in conflict.', code: 'RESOURCE_CONFLICT' });
expect(res.body).toEqual({ error: 'The record is in conflict.', code: 'RESOURCE_CONFLICT', ...FAILED });
});
});
Loading
Loading