Skip to content

Commit 3dfbfdb

Browse files
committed
fix(service-print, spec): the print door's 5xx sentences follow the request's language
serverAnswerFor answered fixed English for 503, 504 and the 500 fallback, and the caller-resolution 500 did the same, whatever the request's Accept-Language. The four sentences are now print_* keys of the platform's operation-message catalog (BUILTIN_OPERATION_MESSAGES) in en, zh-CN, ja-JP and es-ES, written through operationUserMessage in the request's top Accept-Language tag. English is byte-identical to the old text. Claude-Session: https://claude.ai/code/session_01QSeKYnagJvGbCtNg2PhvgW Co-authored-by: Claude <noreply@anthropic.com>
1 parent 9171bed commit 3dfbfdb

6 files changed

Lines changed: 236 additions & 12 deletions

File tree

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
---
2+
'@objectstack/spec': patch
3+
'@objectstack/service-print': patch
4+
---
5+
6+
Clause-②: no
7+
Metadata-protocol: none
8+
9+
The print door (`POST /api/v1/print/records`) now answers its own 5xx sentences in the request's language. A print that fails on the server because the print engine is not ready (`503`), ran past its time (`504`), failed for any other reason (`500`), or could not resolve its caller (`500`) used to answer a fixed English `error.message` whatever the request's `Accept-Language`, so a Chinese console showed the toast in English. The sentences are now four keys of the platform's operation-message catalog (`print_engine_unavailable`, `print_timed_out`, `print_failed`, `print_caller_unresolved` in `BUILTIN_OPERATION_MESSAGES`, `@objectstack/spec/system`) in `en`, `zh-CN`, `ja-JP` and `es-ES`, written through `operationUserMessage` (`@objectstack/core`) in the request's top `Accept-Language` tag. A print clicked as a `type: 'api'` action answers the same way: the `/actions` door forwards the caller's `Accept-Language` and relays the door's `message` as written.
10+
11+
Code, status and the English text do not change: a request in English, with no `Accept-Language`, or in a language the catalog carries no text for, reads the same sentence as before. What the engine or the host said is still withheld from the wire and kept in the server fault log.

‎packages/services/service-print/src/print-routes.test.ts‎

Lines changed: 110 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import { describe, expect, it, vi } from 'vitest';
44
import { ApiErrorSchema, envelopeViolations } from '@objectstack/spec/api';
5+
import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system';
56
import type { ExecutionContext } from '@objectstack/spec/kernel';
67
import type { ChromiumDriver } from './chromium-driver.js';
78
import type { PrintPlacementResolution } from './config.js';
@@ -57,6 +58,8 @@ interface DoorSetup {
5758
page?: Record<string, unknown>;
5859
/** Hand the door this service instead of a real `PrintService`. */
5960
service?: IPrintService;
61+
/** Replace the tenancy-posture read the resolver awaits (a rejection fails the caller's resolution). */
62+
resolveTenancyPosture?: () => Promise<undefined>;
6063
}
6164

6265
function door(setup: DoorSetup = {}) {
@@ -159,10 +162,12 @@ function door(setup: DoorSetup = {}) {
159162
},
160163
}),
161164
getAuth: () => auth as never,
162-
resolveTenancyPosture: async () => undefined,
165+
resolveTenancyPosture: setup.resolveTenancyPosture ?? (async () => undefined),
163166
});
164167

165-
async function call(opts: { bearer?: string; body?: unknown; query?: Record<string, string> } = {}) {
168+
async function call(
169+
opts: { bearer?: string; body?: unknown; query?: Record<string, string>; headers?: Record<string, string> } = {},
170+
) {
166171
const handler = handlers.get(`POST ${PRINT_RECORDS_ROUTE}`);
167172
if (!handler) throw new Error('the door mounted no POST handler at its route');
168173
const answer: { status: number; body: any } = { status: 0, body: undefined };
@@ -182,7 +187,7 @@ function door(setup: DoorSetup = {}) {
182187
params: {},
183188
query: opts.query ?? {},
184189
body: opts.body,
185-
headers: opts.bearer ? { authorization: `Bearer ${opts.bearer}` } : {},
190+
headers: { ...(opts.bearer ? { authorization: `Bearer ${opts.bearer}` } : {}), ...opts.headers },
186191
method: 'POST',
187192
path: PRINT_RECORDS_ROUTE,
188193
},
@@ -362,6 +367,108 @@ describe('the print door — the refusals card ③ pins, relayed through the doo
362367
});
363368
});
364369

370+
describe("the print door — its own 5xx sentences, in the request's language", () => {
371+
/** A service whose print throws `error`: a declared 504, an undeclared fault. */
372+
function throwing(error: unknown): IPrintService {
373+
return {
374+
status: () => ({ state: 'ready', placement: 'local', version: 'stand-in' }),
375+
printRecordToFile: async () => {
376+
throw error;
377+
},
378+
};
379+
}
380+
381+
/** The three failures the card names, each with the door setup that produces it and the catalog key it answers. */
382+
const FAILURES: Array<{ name: string; code: string; status: number; key: string; setup: () => DoorSetup }> = [
383+
{
384+
name: 'no print engine ready',
385+
code: 'SERVICE_UNAVAILABLE',
386+
status: 503,
387+
key: 'print_engine_unavailable',
388+
setup: () => ({ placement: { state: 'unconfigured', reason: 'No print engine is configured. Set OS_PRINT_CHROMIUM_PATH.' } }),
389+
},
390+
{
391+
name: 'the render ran past its time',
392+
code: 'TIMEOUT',
393+
status: 504,
394+
key: 'print_timed_out',
395+
setup: () => ({ service: throwing(Object.assign(new Error('render timed out at /srv/secret'), { code: 'TIMEOUT', status: 504 })) }),
396+
},
397+
{
398+
name: 'an undeclared fault',
399+
code: 'INTERNAL_ERROR',
400+
status: 500,
401+
key: 'print_failed',
402+
setup: () => ({ service: throwing(new Error('ECONNRESET at /srv/secret')) }),
403+
},
404+
];
405+
406+
async function printAs(setup: DoorSetup, headers?: Record<string, string>) {
407+
const d = door(setup);
408+
const logged = quietFaultLog();
409+
const answer = await d.call({ bearer: 'alice', body: { ...INVOICE, recordId: 'inv_alice' }, headers });
410+
logged.restore();
411+
return answer;
412+
}
413+
414+
for (const failure of FAILURES) {
415+
it(`${failure.name}: ${failure.code} / ${failure.status} under accept-language zh-CN answers the zh-CN sentence`, async () => {
416+
const answer = await printAs(failure.setup(), { 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8' });
417+
expect(envelope(answer)).toEqual([failure.code, failure.status]);
418+
expect(answer.body.error.message).toBe(BUILTIN_OPERATION_MESSAGES['zh-CN'][failure.key]);
419+
expect(answer.body.error.message).not.toBe(BUILTIN_OPERATION_MESSAGES.en[failure.key]);
420+
});
421+
422+
it(`${failure.name}: the control — an English or absent accept-language keeps the English sentence`, async () => {
423+
const english = BUILTIN_OPERATION_MESSAGES.en[failure.key];
424+
for (const headers of [{ 'accept-language': 'en-US,en;q=0.9' }, undefined]) {
425+
const answer = await printAs(failure.setup(), headers);
426+
expect(envelope(answer)).toEqual([failure.code, failure.status]);
427+
expect(answer.body.error.message, JSON.stringify(headers)).toBe(english);
428+
}
429+
});
430+
}
431+
432+
it('the English sentences are the ones the door answered before they were localized', () => {
433+
expect(FAILURES.map((f) => BUILTIN_OPERATION_MESSAGES.en[f.key])).toEqual([
434+
'Records cannot be printed to a file right now: the print engine is not ready. The server log records why.',
435+
'The record could not be printed to a file in the time a print is allowed.',
436+
'The record could not be printed to a file because of an error on the server.',
437+
]);
438+
});
439+
440+
it('a base language reaches its regional catalog (ja → ja-JP); a language the catalog lacks answers English', async () => {
441+
const [unavailable] = FAILURES;
442+
const ja = await printAs(unavailable!.setup(), { 'accept-language': 'ja' });
443+
expect(ja.body.error.message).toBe(BUILTIN_OPERATION_MESSAGES['ja-JP'].print_engine_unavailable);
444+
const de = await printAs(unavailable!.setup(), { 'accept-language': 'de-DE' });
445+
expect(de.body.error.message).toBe(BUILTIN_OPERATION_MESSAGES.en.print_engine_unavailable);
446+
});
447+
448+
it('a caller the door cannot resolve: INTERNAL_ERROR / 500 in the request\'s language, the cause in the fault log only', async () => {
449+
const setup: DoorSetup = {
450+
resolveTenancyPosture: async () => {
451+
throw new Error('posture read failed at /srv/secret');
452+
},
453+
};
454+
const zh = await printAs(setup, { 'accept-language': 'zh-CN' });
455+
expect(envelope(zh)).toEqual(['INTERNAL_ERROR', 500]);
456+
expect(zh.body.error.message).toBe(BUILTIN_OPERATION_MESSAGES['zh-CN'].print_caller_unresolved);
457+
const absent = await printAs(setup);
458+
expect(absent.body.error.message).toBe('The caller of this print could not be resolved.');
459+
});
460+
461+
it('a 4xx refusal keeps its producer\'s own text whatever the request\'s language', async () => {
462+
const text = 'the service\'s own refusal text';
463+
const answer = await printAs(
464+
{ service: throwing(Object.assign(new Error(text), { code: 'VALIDATION_ERROR', status: 400 })) },
465+
{ 'accept-language': 'zh-CN' },
466+
);
467+
expect(envelope(answer)).toEqual(['VALIDATION_ERROR', 400]);
468+
expect(answer.body.error.message).toBe(text);
469+
});
470+
});
471+
365472
describe('the print door — its own refusals, before the service is asked', () => {
366473
it('an impersonation session: PERMISSION_DENIED / 403, saying so, before anything is minted or read', async () => {
367474
const d = door();

‎packages/services/service-print/src/print-routes.ts‎

Lines changed: 40 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
evaluateAuthGate,
1010
isApiKeyLifecycleRefusalError,
1111
isAuthzStoreUnavailableError,
12+
operationUserMessage,
1213
resolveAuthzContext,
1314
shouldDenyAnonymous,
1415
userAuthGateSourceOf,
@@ -18,6 +19,7 @@ import type { ErrorCode } from '@objectstack/spec/api';
1819
import type { AuthSessionApi, IAuthService, IHttpRequest, IHttpResponse, IHttpServer } from '@objectstack/spec/contracts';
1920
import type { ExecutionContext } from '@objectstack/spec/kernel';
2021
import type { TenancyPosture } from '@objectstack/spec/security';
22+
import { preferredLocaleFromHeader } from '@objectstack/spec/system';
2123
import {
2224
declaredRefusalMessage,
2325
demotedDeclaredCode,
@@ -97,6 +99,12 @@ import type { IPrintService, PrintedRecordFile, PrintRecordRequest } from './pri
9799
* - **Anything else** is a fault: `500` / `INTERNAL_ERROR`, the door's generic
98100
* sentence, and the error in the fault log.
99101
*
102+
* The door's own 5xx sentences are entries of the platform's operation-message
103+
* catalog (the `print_*` keys of `BUILTIN_OPERATION_MESSAGES`), written in the
104+
* request's language: its top `Accept-Language` tag, English when the catalog
105+
* carries no text for it. A print that fails in a Chinese console is answered
106+
* in Chinese. A refusal relayed with its producer's own text keeps that text.
107+
*
100108
* ## What is not recorded
101109
*
102110
* The door writes no audit row of its own. A print signs a session in and out
@@ -153,7 +161,7 @@ async function handlePrintRecord(req: IHttpRequest, res: IHttpResponse, deps: Pr
153161
sendError(res, err.status, err.code, err.message);
154162
return;
155163
}
156-
sendServerFault(res, 500, 'INTERNAL_ERROR', 'The caller of this print could not be resolved.', err, {
164+
sendServerFault(res, 500, 'INTERNAL_ERROR', operationUserMessage('print_caller_unresolved', { locale: requestLocaleOf(req) }), err, {
157165
method: 'POST',
158166
path: PRINT_RECORDS_ROUTE,
159167
});
@@ -210,7 +218,7 @@ async function handlePrintRecord(req: IHttpRequest, res: IHttpResponse, deps: Pr
210218
try {
211219
printed = await deps.print.printRecordToFile(request, context);
212220
} catch (err) {
213-
relayPrintFailure(res, err);
221+
relayPrintFailure(res, err, requestLocaleOf(req));
214222
return;
215223
}
216224
sendOk(res, printed, 201);
@@ -302,15 +310,38 @@ function printRequestOf(body: unknown): PrintRecordRequest | string {
302310
return request as unknown as PrintRecordRequest;
303311
}
304312

305-
/** This door's own sentence for a 5xx whose producer declared no text for its caller. */
306-
function serverAnswerFor(status: number): string {
307-
if (status === 503) return 'Records cannot be printed to a file right now: the print engine is not ready. The server log records why.';
308-
if (status === 504) return 'The record could not be printed to a file in the time a print is allowed.';
309-
return 'The record could not be printed to a file because of an error on the server.';
313+
/**
314+
* The language this door's own 5xx sentences are written in: the request's top
315+
* `Accept-Language` tag. The console sends its UI language on every call, and
316+
* the `/actions` door's in-process forward of a `type: 'api'` action carries
317+
* the caller's header across, so a print clicked as an action is answered in
318+
* the same language. The door reads no query parameter, so `?locale` is no
319+
* source here. It picks the language of the door's words and nothing else.
320+
*/
321+
function requestLocaleOf(req: IHttpRequest): string | undefined {
322+
const header = req.headers?.['accept-language'] ?? req.headers?.['Accept-Language'];
323+
const value = Array.isArray(header) ? header[0] : header;
324+
return preferredLocaleFromHeader(typeof value === 'string' ? value : undefined);
325+
}
326+
327+
/**
328+
* The catalog key of this door's own sentence for a 5xx whose producer declared
329+
* no text for its caller: the platform's operation-message catalog
330+
* (`BUILTIN_OPERATION_MESSAGES`, `@objectstack/spec/system`), never a second one.
331+
*/
332+
function serverAnswerKeyFor(status: number): 'print_engine_unavailable' | 'print_timed_out' | 'print_failed' {
333+
if (status === 503) return 'print_engine_unavailable';
334+
if (status === 504) return 'print_timed_out';
335+
return 'print_failed';
336+
}
337+
338+
/** This door's own sentence for a 5xx whose producer declared no text for its caller, in the request's language. */
339+
function serverAnswerFor(status: number, locale: string | undefined): string {
340+
return operationUserMessage(serverAnswerKeyFor(status), { locale });
310341
}
311342

312343
/** Relay a failed print: a declared refusal with its own `code` and `status`, anything else as a fault. */
313-
function relayPrintFailure(res: IHttpResponse, err: unknown): void {
344+
function relayPrintFailure(res: IHttpResponse, err: unknown, locale: string | undefined): void {
314345
const thrown = resolveThrownHttpError(err, 500);
315346
if (thrown.status < 500) {
316347
const declaredCode = demotedDeclaredCode(thrown);
@@ -326,7 +357,7 @@ function relayPrintFailure(res: IHttpResponse, err: unknown): void {
326357
sendError(res, thrown.status, thrown.code, refusal);
327358
return;
328359
}
329-
sendServerFault(res, thrown.status, thrown.code, serverAnswerFor(thrown.status), err, {
360+
sendServerFault(res, thrown.status, thrown.code, serverAnswerFor(thrown.status, locale), err, {
330361
method: 'POST',
331362
path: PRINT_RECORDS_ROUTE,
332363
});

‎packages/services/service-print/vitest.config.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ export default defineConfig({
2828
{ find: /^@objectstack\/spec\/contracts$/, replacement: path.resolve(__dirname, '../../spec/src/contracts/index.ts') },
2929
{ find: /^@objectstack\/spec\/kernel$/, replacement: path.resolve(__dirname, '../../spec/src/kernel/index.ts') },
3030
{ find: /^@objectstack\/spec\/ui$/, replacement: path.resolve(__dirname, '../../spec/src/ui/index.ts') },
31+
{ find: /^@objectstack\/spec\/system$/, replacement: path.resolve(__dirname, '../../spec/src/system/index.ts') },
3132
{ find: /^@objectstack\/types$/, replacement: path.resolve(__dirname, '../../types/src/index.ts') },
3233
],
3334
},

‎packages/spec/src/system/operation-message.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -724,3 +724,42 @@ describe('operation message catalog — not found, unreadable query field, deleg
724724
expect(renderOperationMessage({ messageKey: 'record_not_found' }, { locale: 'zh-CN', translate })).toBe('记录不见了');
725725
});
726726
});
727+
728+
describe('operation message catalog — the print door\'s own 5xx sentences', () => {
729+
const KEYS = ['print_engine_unavailable', 'print_timed_out', 'print_failed', 'print_caller_unresolved'] as const;
730+
731+
it('every locale defines all four, placeholder-free', () => {
732+
for (const [locale, catalog] of Object.entries(BUILTIN_OPERATION_MESSAGES)) {
733+
for (const key of KEYS) {
734+
expect(catalog[key], `${locale} defines ${key}`).toBeTypeOf('string');
735+
expect(catalog[key].match(/\{\{\w+\}\}/g) ?? [], `${locale}.${key}`).toEqual([]);
736+
}
737+
}
738+
});
739+
740+
it('names no wire code, engine or host vocabulary — in every locale', () => {
741+
for (const [locale, catalog] of Object.entries(BUILTIN_OPERATION_MESSAGES)) {
742+
for (const key of KEYS) {
743+
expect(catalog[key], `${locale}.${key}`).not.toMatch(/SERVICE_UNAVAILABLE|TIMEOUT|INTERNAL_ERROR|Chromium|OS_PRINT|\//);
744+
}
745+
}
746+
});
747+
748+
it('renders the caller locale, matches a base language, and falls back to en for a locale the catalog lacks', () => {
749+
for (const key of KEYS) {
750+
expect(renderOperationMessage({ messageKey: key }, { locale: 'zh-CN' })).toBe(BUILTIN_OPERATION_MESSAGES['zh-CN'][key]);
751+
expect(renderOperationMessage({ messageKey: key }, { locale: 'zh-CN' })).not.toBe(BUILTIN_OPERATION_MESSAGES.en[key]);
752+
expect(renderOperationMessage({ messageKey: key }, { locale: 'es' })).toBe(BUILTIN_OPERATION_MESSAGES['es-ES'][key]);
753+
expect(renderOperationMessage({ messageKey: key }, { locale: 'de-DE' })).toBe(BUILTIN_OPERATION_MESSAGES.en[key]);
754+
}
755+
});
756+
757+
it('each says something different from every other key, in every locale', () => {
758+
for (const [locale, catalog] of Object.entries(BUILTIN_OPERATION_MESSAGES)) {
759+
for (const key of KEYS) {
760+
const others = Object.entries(catalog).filter(([k]) => k !== key).map(([, v]) => v);
761+
expect(others, `${locale}.${key}`).not.toContain(catalog[key]);
762+
}
763+
}
764+
});
765+
});

0 commit comments

Comments
 (0)