Skip to content

Commit acf6014

Browse files
committed
fix(rest): answer the backfill door on the shared envelope pair; pin the truncated walk text
Claude-Session: https://claude.ai/code/session_016WV4cyrhYJgbkZHbbqud3F Co-authored-by: Claude <noreply@anthropic.com>
1 parent be390f7 commit acf6014

10 files changed

Lines changed: 167 additions & 40 deletions
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
---
2+
'@objectstack/rest': patch
3+
'@objectstack/client': patch
4+
'@objectstack/objectql': patch
5+
'@objectstack/cli': patch
6+
'@objectstack/metadata-protocol': patch
7+
---
8+
9+
feat(rest, client): a tenant-admin REST door for the record-currency code backfill
10+
11+
Clause-②: yes (widening)
12+
Metadata-protocol: none
13+
14+
An organization admin with no shell on the deployment can now run the record-currency code backfill (`os migrate record-currency-codes`) over HTTP: `POST /api/v1/meta/_migrate-record-currency-codes` with `{ object, field, code, apply? }`, or `client.meta.migrateRecordCurrencyCodes(...)` from the SDK.
15+
16+
- It fills the codeless rows of **the caller's current organization only**. There is no environment-wide form, and the body takes no organization: `organizationId`, `allOrganizations` or any other key outside the four is refused with `VALIDATION_ERROR` / 400. A request with no current organization is refused `403 FORBIDDEN`.
17+
- It requires `setup.write` in that organization (`403 FORBIDDEN` otherwise), and it is mounted behind `metadata.endpoints.maintenance` with the other maintenance routes.
18+
- Preview unless `apply` is `true`. The answer is the report the CLI prints under `--json`, and the code, field and object refusals are the CLI's.
19+
- The SDK method answers `unknown`: the report's named type lives in `@objectstack/objectql`.
20+
- The 409 `destructive_change` finding `currency_mode_to_record` now names this route beside the CLI command.
21+
- `@objectstack/objectql` now exports `RecordCurrencyBackfillOrganization` and `RecordCurrencyBackfillOrganizationsRefusal` from its entry.
22+
- A backfill walk stopped by `--max-records` no longer prints "nothing to backfill" for rows it did not examine. It says the walk is incomplete, and an unscoped run says its organization check saw only the rows examined.

‎content/docs/data-modeling/currency.mdx‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,10 @@ naming no organization there is refused before any write and lists each organiza
148148
codeless row count, and `--all-organizations` writes the one code into every
149149
organization's rows when it really is right for all of them. See
150150
[`os migrate record-currency-codes`](/docs/deployment/cli#os-migrate-record-currency-codes).
151+
With no shell on the deployment (a hosted organization), an organization admin holding
152+
`setup.write` runs the same backfill for their current organization's rows with
153+
`POST /api/v1/meta/_migrate-record-currency-codes` and the body
154+
`{ "object", "field", "code", "apply" }`, a preview unless `apply` is `true`.
151155

152156
### Aggregating a record-mode amount
153157

‎content/docs/deployment/cli.mdx‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1663,6 +1663,40 @@ every write turns a blank code into a code, so a second run finds nothing to wri
16631663
Re-running until the report says zero *is* the verification, which is why this
16641664
command records no flag.
16651665
1666+
A walk that reaches `--max-records` stops there: the report says `truncated: true`, the
1667+
text says the walk is incomplete, and the command never prints "nothing to backfill"
1668+
for rows it did not examine. Re-run without the cap to finish.
1669+
1670+
**Without shell access, use the route.** An organization admin on a hosted deployment
1671+
cannot reach its database from a shell. The same backfill is exposed over HTTP, for the
1672+
rows of **the caller's current organization only**:
1673+
1674+
```http
1675+
POST /api/v1/meta/_migrate-record-currency-codes
1676+
Content-Type: application/json
1677+
1678+
{ "object": "opportunity", "field": "amount", "code": "USD", "apply": true }
1679+
```
1680+
1681+
or from the SDK:
1682+
1683+
```ts
1684+
const preview = await client.meta.migrateRecordCurrencyCodes({ object: 'opportunity', field: 'amount', code: 'USD' });
1685+
const result = await client.meta.migrateRecordCurrencyCodes({ object: 'opportunity', field: 'amount', code: 'USD', apply: true });
1686+
```
1687+
1688+
It answers `{ "success": true, "data": … }` with, as `data`, the report this command
1689+
prints under `--json` (its `report` member), and
1690+
takes the same posture: **preview unless `apply` is literally `true`**. It is the
1691+
`--org` run for the caller's current organization: there is no environment-wide form,
1692+
and the body takes no organization (`organizationId` or `allOrganizations` in it is
1693+
refused with `VALIDATION_ERROR` / 400, as is any other key outside `object`, `field`,
1694+
`code` and `apply`). A request with no current organization is refused `403`. It
1695+
requires the `setup.write` capability in that organization and answers `403`
1696+
otherwise; the code, field and object refusals are the command's. It is mounted with
1697+
the other maintenance routes, so `metadata.endpoints.maintenance: false` takes it away.
1698+
There is no Setup button for it yet: that is separate UI work.
1699+
16661700
#### `os migrate recompute-home-amounts`
16671701
16681702
A record-mode amount that declares a home amount is converted into the organization's home

‎packages/cli/src/commands/migrate/record-currency-codes.test.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,20 @@ describe('os migrate record-currency-codes', () => {
316316
expect(lines.find((line) => line.startsWith('Dry run —'))).toBe(`${DRY_RUN_LINE} ${JOURNAL_MODE_SWITCH_NOTE}`);
317317
}, RUN_TIMEOUT);
318318

319+
it('a walk --max-records cut short says it is incomplete, never "nothing to backfill"', async () => {
320+
boot(POSTGRES_CONFIG);
321+
vi.mocked(backfillRecordCurrencyCodes).mockResolvedValue({
322+
...REPORT, organizationId: 'org_a', allOrganizations: false, organizations: [],
323+
scannedRecords: 2, codeless: 0, skippedCodePresent: 2, sampleRecordIds: [], truncated: true,
324+
} as any);
325+
await MigrateRecordCurrencyCodes.run([...NAMING, '--org', 'org_a', '--max-records', '2'], { root: CLI_ROOT });
326+
const text = printedLines().join('\n');
327+
expect(text).toContain('No codeless opportunity.amount amount among the 2 row(s) examined.');
328+
expect(text).toContain('Walk incomplete — 2 row(s) examined, 0 codeless.');
329+
expect(text).not.toContain('Nothing to backfill');
330+
expect(text).not.toContain('nothing to backfill');
331+
}, RUN_TIMEOUT);
332+
319333
it('on PostgreSQL the dry-run line names no switch', async () => {
320334
boot(POSTGRES_CONFIG);
321335
await MigrateRecordCurrencyCodes.run(NAMING, { root: CLI_ROOT });

‎packages/client/src/meta-automation-descriptors.test.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -114,17 +114,17 @@ describe('client.automation descriptors (#3563 PR-5)', () => {
114114
describe('client.meta.migrateRecordCurrencyCodes (ADR-0144 record-currency code backfill)', () => {
115115
it('POSTs the three names to the backfill door, a preview unless apply is true', async () => {
116116
const report = { object: 'deal', organizationId: 'org_a', codeless: 2, written: 0, applied: false, truncated: false };
117-
const { client, fetchMock } = createMockClient(report);
117+
const { client, fetchMock } = createMockClient({ success: true, data: report });
118118
const out = await client.meta.migrateRecordCurrencyCodes({ object: 'deal', field: 'amount', code: 'USD' });
119119
expect(String(fetchMock.mock.calls[0][0])).toBe('http://localhost:3000/api/v1/meta/_migrate-record-currency-codes');
120120
expect(fetchMock.mock.calls[0][1]?.method).toBe('POST');
121121
expect(JSON.parse(String(fetchMock.mock.calls[0][1]?.body))).toEqual({ object: 'deal', field: 'amount', code: 'USD' });
122-
// The REST door answers the report BARE; it reaches the caller as it was sent.
122+
// The REST door answers the report as the `data` of the shared envelope; the caller gets the report.
123123
expect(out).toEqual(report);
124124
});
125125

126126
it('sends apply only when it is true, and never an organization', async () => {
127-
const { client, fetchMock } = createMockClient({ applied: true });
127+
const { client, fetchMock } = createMockClient({ success: true, data: { applied: true } });
128128
await client.meta.migrateRecordCurrencyCodes({ object: 'deal', field: 'amount', code: 'USD', apply: true });
129129
await client.meta.migrateRecordCurrencyCodes({ object: 'deal', field: 'amount', code: 'USD', apply: false });
130130
const bodies = fetchMock.mock.calls.map((c: unknown[]) => JSON.parse(String((c[1] as { body?: unknown })?.body)));

‎packages/objectql/src/protocol-destructive-currency-mode.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,9 @@ describe('ObjectStackProtocolImplementation - currency_mode_to_record', () => {
104104
expect(message).toContain('fall into the null group of a grouped aggregate');
105105
expect(message).toContain('sit outside every currency-paired filter');
106106
expect(message).toContain(`os migrate record-currency-codes --object ${object} --field amount --code <ISO 4217 code>`);
107+
// …and, for an organization admin with no shell, the REST door beside it.
108+
expect(message).toContain('`POST /api/v1/meta/_migrate-record-currency-codes`');
109+
expect(message).toContain(`{ "object": "${object}", "field": "amount", "code": "<ISO 4217 code>" }`);
107110
// It reads no row of the object: the only reads are the
108111
// metadata store's own (the row this save overwrites).
109112
for (const verb of ['find', 'findOne', 'count', 'aggregate'] as const) {

‎packages/objectql/src/record-currency-backfill.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,31 @@ describe('backfillRecordCurrencyCodes — rows stored before the switch to recor
194194
);
195195
});
196196

197+
it('a walk the cap cuts short says so, and never claims every row was examined', async () => {
198+
// Two coded rows first, so the capped walk meets no codeless row at all.
199+
stored('c1', { amount: 1, currency_code: 'EUR' });
200+
stored('c2', { amount: 2, currency_code: 'EUR' });
201+
stored('c3', { amount: 3 });
202+
const capped = await backfillRecordCurrencyCodes(engine, quietLogger, {
203+
object: 'deal', field: 'amount', code: 'USD', maxRecords: 2,
204+
});
205+
expect(capped).toMatchObject({ scannedRecords: 2, codeless: 0, truncated: true });
206+
const lines = formatRecordCurrencyBackfillReport(capped);
207+
expect(lines).toContain('No codeless deal.amount amount among the 2 row(s) examined.');
208+
expect(lines.some((l) => l.includes('nothing to backfill'))).toBe(false);
209+
expect(lines).toContain('⚠ Walk incomplete — some rows were not examined; re-run without the cap to finish.');
210+
// The run was unscoped, so its one-organization verdict saw only those rows.
211+
expect(lines.some((l) => l.includes('The organization check saw only the rows examined'))).toBe(true);
212+
expect(recordCurrencyBackfillComplete(capped)).toBe(false);
213+
214+
// A scoped run names its organization, so it owes no organization-check line.
215+
const scoped = formatRecordCurrencyBackfillReport({ ...capped, organizationId: 'org_a' });
216+
expect(scoped.some((l) => l.includes('The organization check'))).toBe(false);
217+
// The same walk, uncapped, is complete and says so.
218+
const whole = await backfillRecordCurrencyCodes(engine, quietLogger, { object: 'deal', field: 'amount', code: 'USD' });
219+
expect(whole).toMatchObject({ scannedRecords: 3, codeless: 1, truncated: false });
220+
});
221+
197222
it('a code that is not an ISO 4217 member is refused before any row is read', async () => {
198223
seedMixed();
199224
for (const code of ['usd', 'XYZ', 'US', ' USD', '']) {

‎packages/rest/src/meta-record-currency-backfill-route.test.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,9 @@ function boot(
139139
if (!route) throw new Error(`POST ${PATH} is not registered`);
140140
const res = mockRes();
141141
await route.handler({ params: {}, query: {}, headers: {}, body }, res);
142-
return { status: res.statusCode as number, body: res.json.mock.calls.at(-1)?.[0] as any };
142+
const raw = res.json.mock.calls.at(-1)?.[0] as any;
143+
// `body` is the payload of `{ success: true, data }`, or the refusal envelope itself.
144+
return { status: res.statusCode as number, raw, body: raw?.success === true ? raw.data : raw };
143145
},
144146
};
145147
}
@@ -182,6 +184,8 @@ describe('POST /meta/_migrate-record-currency-codes — the caller\'s organizati
182184
it('a preview counts the caller\'s organization\'s rows only, and writes nothing', async () => {
183185
const answer = await boot(engine, ADMIN_A).call({ object: 'deal', field: 'amount', code: 'USD' });
184186
expect(answer.status).toBe(200);
187+
// The report is the `data` of the shared envelope, and nothing rides beside it.
188+
expect(Object.keys(answer.raw).sort()).toEqual(['data', 'success']);
185189
expect(answer.body).toMatchObject({
186190
object: 'deal', organizationId: 'org_a', allOrganizations: false, field: 'amount', codeField: 'currency_code',
187191
code: 'USD', scannedRecords: 3, codeless: 2, written: 0, skippedCodePresent: 1, applied: false,
@@ -297,6 +301,8 @@ describe('POST /meta/_migrate-record-currency-codes — the caller\'s organizati
297301
it('the backfill\'s own refusals answer with its status and code, before any row is read', async () => {
298302
const notIso = await boot(engine, ADMIN_A).call({ object: 'deal', field: 'amount', code: 'usd', apply: true });
299303
expect({ status: notIso.status, code: notIso.body?.error?.code }).toEqual({ status: 400, code: 'INVALID_FIELD' });
304+
expect(notIso.raw).toMatchObject({ success: false });
305+
expect(notIso.body.error.details?.fields?.[0]).toMatchObject({ field: 'currency_code', code: 'INVALID_FIELD' });
300306
const notRecord = await boot(engine, ADMIN_A).call({ object: 'deal', field: 'name', code: 'USD', apply: true });
301307
expect({ status: notRecord.status, code: notRecord.body?.error?.code }).toEqual({ status: 400, code: 'INVALID_FIELD' });
302308
const noObject = await boot(engine, ADMIN_A).call({ object: 'no_such_object', field: 'amount', code: 'USD' });

‎packages/rest/src/meta-record-currency-backfill-route.ts‎

Lines changed: 54 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -54,17 +54,23 @@
5454
* to load. `scripts/check-undeclared-dep-imports.mjs` ledgers that probe
5555
* against this file.
5656
*
57-
* ## Errors
57+
* ## The envelope, and errors
5858
*
59-
* Only codes the registry already carries: `FORBIDDEN` (capability, no current
60-
* organization), `VALIDATION_ERROR` (the body), `NOT_IMPLEMENTED` (no engine),
61-
* and the backfill's own refusals (`INVALID_FIELD` for a field that is not a
59+
* Born on the shared pair (`sendOk` / `sendError`, `@objectstack/types`): the
60+
* report is the `data` of `{ success: true, data }`, the payload the CLI's
61+
* `--json` prints as its `report`, and every refusal is
62+
* `{ success: false, error: { code, message } }`. Only codes the registry
63+
* already carries: `FORBIDDEN` (capability, no current organization),
64+
* `VALIDATION_ERROR` (the body), `NOT_IMPLEMENTED` (no engine), and the
65+
* backfill's own refusals (`INVALID_FIELD` for a field that is not a
6266
* record-mode amount or a code outside ISO 4217, the object-not-found answer),
63-
* each answered through `handleRouteError` with the status the function gave.
67+
* answered with the status and code the function threw, resolved by the shared
68+
* `resolveThrownHttpError`. Anything else is a fault: `sendServerFault` logs
69+
* the throw and answers the route's generic text.
6470
*/
6571

6672
import { rethrowAuthzStoreUnavailable } from '@objectstack/core';
67-
import { handleRouteError } from './error-response.js';
73+
import { demotedDeclaredCode, resolveThrownHttpError, sendError, sendOk, sendServerFault } from '@objectstack/types';
6874
import { logWarn } from './log.js';
6975
import type { MetaRouteScope } from './meta-collection-routes.js';
7076
import { wiredEngineOrLoud, type RestServer } from './rest-server.js';
@@ -144,28 +150,22 @@ export function registerMetaRecordCurrencyBackfillRoute(
144150
const ctx = await this.resolveExecCtx(environmentId, req).catch(rethrowAuthzStoreUnavailable);
145151
const held = new Set<string>(Array.isArray(ctx?.systemPermissions) ? ctx.systemPermissions : []);
146152
if (!ctx?.isSystem && !held.has(RECORD_CURRENCY_BACKFILL_CAPABILITY)) {
147-
res.status(403).json({
148-
error: {
149-
code: 'FORBIDDEN',
150-
message:
151-
'Backfilling record currency codes requires the `setup.write` capability in your ' +
152-
'current organization.',
153-
},
154-
});
155-
return;
153+
return sendError(
154+
res,
155+
403,
156+
'FORBIDDEN',
157+
'Backfilling record currency codes requires the `setup.write` capability in your current organization.',
158+
);
156159
}
157160
const organizationId = typeof ctx?.tenantId === 'string' && ctx.tenantId !== '' ? ctx.tenantId : undefined;
158161
if (organizationId === undefined) {
159-
res.status(403).json({
160-
error: {
161-
code: 'FORBIDDEN',
162-
message:
163-
'This request has no current organization, and the backfill fills the rows of the ' +
164-
'caller\'s current organization only: select the organization whose rows you mean ' +
165-
'and retry. Nothing was read.',
166-
},
167-
});
168-
return;
162+
return sendError(
163+
res,
164+
403,
165+
'FORBIDDEN',
166+
'This request has no current organization, and the backfill fills the rows of the caller\'s ' +
167+
'current organization only: select the organization whose rows you mean and retry. Nothing was read.',
168+
);
169169
}
170170
const body = readBody(req.body);
171171
const ql: any = await wiredEngineOrLoud(
@@ -184,21 +184,40 @@ export function registerMetaRecordCurrencyBackfillRoute(
184184
|| typeof ql?.find !== 'function'
185185
|| typeof ql?.update !== 'function'
186186
) {
187-
res.status(501).json({
188-
error: {
189-
code: 'NOT_IMPLEMENTED',
190-
message: 'The record currency code backfill is not available in this runtime: it has no data engine.',
191-
},
192-
});
193-
return;
187+
return sendError(
188+
res,
189+
501,
190+
'NOT_IMPLEMENTED',
191+
'The record currency code backfill is not available in this runtime: it has no data engine.',
192+
);
194193
}
195194
// Per-row failures are in the report the caller receives; the
196195
// log line is the operator's copy.
197196
const logger = { info: () => {}, warn: (message: string) => logWarn(message) };
198197
const report = await backfill(ql, logger, { ...body, organizationId });
199-
res.json(report);
200-
} catch (error: any) {
201-
handleRouteError(res, error);
198+
return sendOk(res, report);
199+
} catch (error: unknown) {
200+
// A refusal the body judge or the backfill DECLARED (a 4xx with
201+
// its code) is the caller's answer; anything else is a fault.
202+
const thrown = resolveThrownHttpError(error);
203+
if (thrown.declaredStatus !== undefined && thrown.status >= 400 && thrown.status < 500) {
204+
const field = (error as { field?: unknown } | null)?.field;
205+
const declaredCode = demotedDeclaredCode(thrown);
206+
return sendError(res, thrown.status, thrown.code, thrown.message, {
207+
...(typeof field === 'string'
208+
? { details: { fields: [{ field, code: thrown.code, message: thrown.message }] } }
209+
: {}),
210+
...(declaredCode !== undefined ? { declaredCode } : {}),
211+
});
212+
}
213+
const status = thrown.declaredStatus !== undefined && thrown.status >= 500 ? thrown.status : 500;
214+
return sendServerFault(
215+
res,
216+
status,
217+
status === 500 ? 'INTERNAL_ERROR' : thrown.code,
218+
'Backfilling record currency codes failed.',
219+
error,
220+
);
202221
}
203222
},
204223
metadata: {

0 commit comments

Comments
 (0)