diff --git a/.changeset/37260-print-failure-locale.md b/.changeset/37260-print-failure-locale.md new file mode 100644 index 00000000000..94f0d154386 --- /dev/null +++ b/.changeset/37260-print-failure-locale.md @@ -0,0 +1,11 @@ +--- +'@objectstack/spec': patch +'@objectstack/service-print': patch +--- + +Clause-②: no +Metadata-protocol: none + +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. + +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. diff --git a/packages/services/service-print/src/print-routes.test.ts b/packages/services/service-print/src/print-routes.test.ts index ed3ba8a0bf4..555ce417ebb 100644 --- a/packages/services/service-print/src/print-routes.test.ts +++ b/packages/services/service-print/src/print-routes.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest'; import { ApiErrorSchema, envelopeViolations } from '@objectstack/spec/api'; +import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import type { ChromiumDriver } from './chromium-driver.js'; import type { PrintPlacementResolution } from './config.js'; @@ -57,6 +58,8 @@ interface DoorSetup { page?: Record; /** Hand the door this service instead of a real `PrintService`. */ service?: IPrintService; + /** Replace the tenancy-posture read the resolver awaits (a rejection fails the caller's resolution). */ + resolveTenancyPosture?: () => Promise; } function door(setup: DoorSetup = {}) { @@ -159,10 +162,12 @@ function door(setup: DoorSetup = {}) { }, }), getAuth: () => auth as never, - resolveTenancyPosture: async () => undefined, + resolveTenancyPosture: setup.resolveTenancyPosture ?? (async () => undefined), }); - async function call(opts: { bearer?: string; body?: unknown; query?: Record } = {}) { + async function call( + opts: { bearer?: string; body?: unknown; query?: Record; headers?: Record } = {}, + ) { const handler = handlers.get(`POST ${PRINT_RECORDS_ROUTE}`); if (!handler) throw new Error('the door mounted no POST handler at its route'); const answer: { status: number; body: any } = { status: 0, body: undefined }; @@ -182,7 +187,7 @@ function door(setup: DoorSetup = {}) { params: {}, query: opts.query ?? {}, body: opts.body, - headers: opts.bearer ? { authorization: `Bearer ${opts.bearer}` } : {}, + headers: { ...(opts.bearer ? { authorization: `Bearer ${opts.bearer}` } : {}), ...opts.headers }, method: 'POST', path: PRINT_RECORDS_ROUTE, }, @@ -362,6 +367,108 @@ describe('the print door — the refusals card ③ pins, relayed through the doo }); }); +describe("the print door — its own 5xx sentences, in the request's language", () => { + /** A service whose print throws `error`: a declared 504, an undeclared fault. */ + function throwing(error: unknown): IPrintService { + return { + status: () => ({ state: 'ready', placement: 'local', version: 'stand-in' }), + printRecordToFile: async () => { + throw error; + }, + }; + } + + /** The three failures the card names, each with the door setup that produces it and the catalog key it answers. */ + const FAILURES: Array<{ name: string; code: string; status: number; key: string; setup: () => DoorSetup }> = [ + { + name: 'no print engine ready', + code: 'SERVICE_UNAVAILABLE', + status: 503, + key: 'print_engine_unavailable', + setup: () => ({ placement: { state: 'unconfigured', reason: 'No print engine is configured. Set OS_PRINT_CHROMIUM_PATH.' } }), + }, + { + name: 'the render ran past its time', + code: 'TIMEOUT', + status: 504, + key: 'print_timed_out', + setup: () => ({ service: throwing(Object.assign(new Error('render timed out at /srv/secret'), { code: 'TIMEOUT', status: 504 })) }), + }, + { + name: 'an undeclared fault', + code: 'INTERNAL_ERROR', + status: 500, + key: 'print_failed', + setup: () => ({ service: throwing(new Error('ECONNRESET at /srv/secret')) }), + }, + ]; + + async function printAs(setup: DoorSetup, headers?: Record) { + const d = door(setup); + const logged = quietFaultLog(); + const answer = await d.call({ bearer: 'alice', body: { ...INVOICE, recordId: 'inv_alice' }, headers }); + logged.restore(); + return answer; + } + + for (const failure of FAILURES) { + it(`${failure.name}: ${failure.code} / ${failure.status} under accept-language zh-CN answers the zh-CN sentence`, async () => { + const answer = await printAs(failure.setup(), { 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8' }); + expect(envelope(answer)).toEqual([failure.code, failure.status]); + expect(answer.body.error.message).toBe(BUILTIN_OPERATION_MESSAGES['zh-CN'][failure.key]); + expect(answer.body.error.message).not.toBe(BUILTIN_OPERATION_MESSAGES.en[failure.key]); + }); + + it(`${failure.name}: the control — an English or absent accept-language keeps the English sentence`, async () => { + const english = BUILTIN_OPERATION_MESSAGES.en[failure.key]; + for (const headers of [{ 'accept-language': 'en-US,en;q=0.9' }, undefined]) { + const answer = await printAs(failure.setup(), headers); + expect(envelope(answer)).toEqual([failure.code, failure.status]); + expect(answer.body.error.message, JSON.stringify(headers)).toBe(english); + } + }); + } + + it('the English sentences are the ones the door answered before they were localized', () => { + expect(FAILURES.map((f) => BUILTIN_OPERATION_MESSAGES.en[f.key])).toEqual([ + 'Records cannot be printed to a file right now: the print engine is not ready. The server log records why.', + 'The record could not be printed to a file in the time a print is allowed.', + 'The record could not be printed to a file because of an error on the server.', + ]); + }); + + it('a base language reaches its regional catalog (ja → ja-JP); a language the catalog lacks answers English', async () => { + const [unavailable] = FAILURES; + const ja = await printAs(unavailable!.setup(), { 'accept-language': 'ja' }); + expect(ja.body.error.message).toBe(BUILTIN_OPERATION_MESSAGES['ja-JP'].print_engine_unavailable); + const de = await printAs(unavailable!.setup(), { 'accept-language': 'de-DE' }); + expect(de.body.error.message).toBe(BUILTIN_OPERATION_MESSAGES.en.print_engine_unavailable); + }); + + it('a caller the door cannot resolve: INTERNAL_ERROR / 500 in the request\'s language, the cause in the fault log only', async () => { + const setup: DoorSetup = { + resolveTenancyPosture: async () => { + throw new Error('posture read failed at /srv/secret'); + }, + }; + const zh = await printAs(setup, { 'accept-language': 'zh-CN' }); + expect(envelope(zh)).toEqual(['INTERNAL_ERROR', 500]); + expect(zh.body.error.message).toBe(BUILTIN_OPERATION_MESSAGES['zh-CN'].print_caller_unresolved); + const absent = await printAs(setup); + expect(absent.body.error.message).toBe('The caller of this print could not be resolved.'); + }); + + it('a 4xx refusal keeps its producer\'s own text whatever the request\'s language', async () => { + const text = 'the service\'s own refusal text'; + const answer = await printAs( + { service: throwing(Object.assign(new Error(text), { code: 'VALIDATION_ERROR', status: 400 })) }, + { 'accept-language': 'zh-CN' }, + ); + expect(envelope(answer)).toEqual(['VALIDATION_ERROR', 400]); + expect(answer.body.error.message).toBe(text); + }); +}); + describe('the print door — its own refusals, before the service is asked', () => { it('an impersonation session: PERMISSION_DENIED / 403, saying so, before anything is minted or read', async () => { const d = door(); diff --git a/packages/services/service-print/src/print-routes.ts b/packages/services/service-print/src/print-routes.ts index 88cc2d0d516..44b2c38dcc4 100644 --- a/packages/services/service-print/src/print-routes.ts +++ b/packages/services/service-print/src/print-routes.ts @@ -9,6 +9,7 @@ import { evaluateAuthGate, isApiKeyLifecycleRefusalError, isAuthzStoreUnavailableError, + operationUserMessage, resolveAuthzContext, shouldDenyAnonymous, userAuthGateSourceOf, @@ -18,6 +19,7 @@ import type { ErrorCode } from '@objectstack/spec/api'; import type { AuthSessionApi, IAuthService, IHttpRequest, IHttpResponse, IHttpServer } from '@objectstack/spec/contracts'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import type { TenancyPosture } from '@objectstack/spec/security'; +import { preferredLocaleFromHeader } from '@objectstack/spec/system'; import { declaredRefusalMessage, demotedDeclaredCode, @@ -97,6 +99,12 @@ import type { IPrintService, PrintedRecordFile, PrintRecordRequest } from './pri * - **Anything else** is a fault: `500` / `INTERNAL_ERROR`, the door's generic * sentence, and the error in the fault log. * + * The door's own 5xx sentences are entries of the platform's operation-message + * catalog (the `print_*` keys of `BUILTIN_OPERATION_MESSAGES`), written in the + * request's language: its top `Accept-Language` tag, English when the catalog + * carries no text for it. A print that fails in a Chinese console is answered + * in Chinese. A refusal relayed with its producer's own text keeps that text. + * * ## What is not recorded * * 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 sendError(res, err.status, err.code, err.message); return; } - sendServerFault(res, 500, 'INTERNAL_ERROR', 'The caller of this print could not be resolved.', err, { + sendServerFault(res, 500, 'INTERNAL_ERROR', operationUserMessage('print_caller_unresolved', { locale: requestLocaleOf(req) }), err, { method: 'POST', path: PRINT_RECORDS_ROUTE, }); @@ -210,7 +218,7 @@ async function handlePrintRecord(req: IHttpRequest, res: IHttpResponse, deps: Pr try { printed = await deps.print.printRecordToFile(request, context); } catch (err) { - relayPrintFailure(res, err); + relayPrintFailure(res, err, requestLocaleOf(req)); return; } sendOk(res, printed, 201); @@ -302,15 +310,38 @@ function printRequestOf(body: unknown): PrintRecordRequest | string { return request as unknown as PrintRecordRequest; } -/** This door's own sentence for a 5xx whose producer declared no text for its caller. */ -function serverAnswerFor(status: number): string { - if (status === 503) return 'Records cannot be printed to a file right now: the print engine is not ready. The server log records why.'; - if (status === 504) return 'The record could not be printed to a file in the time a print is allowed.'; - return 'The record could not be printed to a file because of an error on the server.'; +/** + * The language this door's own 5xx sentences are written in: the request's top + * `Accept-Language` tag. The console sends its UI language on every call, and + * the `/actions` door's in-process forward of a `type: 'api'` action carries + * the caller's header across, so a print clicked as an action is answered in + * the same language. The door reads no query parameter, so `?locale` is no + * source here. It picks the language of the door's words and nothing else. + */ +function requestLocaleOf(req: IHttpRequest): string | undefined { + const header = req.headers?.['accept-language'] ?? req.headers?.['Accept-Language']; + const value = Array.isArray(header) ? header[0] : header; + return preferredLocaleFromHeader(typeof value === 'string' ? value : undefined); +} + +/** + * The catalog key of this door's own sentence for a 5xx whose producer declared + * no text for its caller: the platform's operation-message catalog + * (`BUILTIN_OPERATION_MESSAGES`, `@objectstack/spec/system`), never a second one. + */ +function serverAnswerKeyFor(status: number): 'print_engine_unavailable' | 'print_timed_out' | 'print_failed' { + if (status === 503) return 'print_engine_unavailable'; + if (status === 504) return 'print_timed_out'; + return 'print_failed'; +} + +/** This door's own sentence for a 5xx whose producer declared no text for its caller, in the request's language. */ +function serverAnswerFor(status: number, locale: string | undefined): string { + return operationUserMessage(serverAnswerKeyFor(status), { locale }); } /** Relay a failed print: a declared refusal with its own `code` and `status`, anything else as a fault. */ -function relayPrintFailure(res: IHttpResponse, err: unknown): void { +function relayPrintFailure(res: IHttpResponse, err: unknown, locale: string | undefined): void { const thrown = resolveThrownHttpError(err, 500); if (thrown.status < 500) { const declaredCode = demotedDeclaredCode(thrown); @@ -326,7 +357,7 @@ function relayPrintFailure(res: IHttpResponse, err: unknown): void { sendError(res, thrown.status, thrown.code, refusal); return; } - sendServerFault(res, thrown.status, thrown.code, serverAnswerFor(thrown.status), err, { + sendServerFault(res, thrown.status, thrown.code, serverAnswerFor(thrown.status, locale), err, { method: 'POST', path: PRINT_RECORDS_ROUTE, }); diff --git a/packages/services/service-print/vitest.config.ts b/packages/services/service-print/vitest.config.ts index 2246812c638..8b39061cef1 100644 --- a/packages/services/service-print/vitest.config.ts +++ b/packages/services/service-print/vitest.config.ts @@ -28,6 +28,7 @@ export default defineConfig({ { find: /^@objectstack\/spec\/contracts$/, replacement: path.resolve(__dirname, '../../spec/src/contracts/index.ts') }, { find: /^@objectstack\/spec\/kernel$/, replacement: path.resolve(__dirname, '../../spec/src/kernel/index.ts') }, { find: /^@objectstack\/spec\/ui$/, replacement: path.resolve(__dirname, '../../spec/src/ui/index.ts') }, + { find: /^@objectstack\/spec\/system$/, replacement: path.resolve(__dirname, '../../spec/src/system/index.ts') }, { find: /^@objectstack\/types$/, replacement: path.resolve(__dirname, '../../types/src/index.ts') }, ], }, diff --git a/packages/spec/src/system/operation-message.test.ts b/packages/spec/src/system/operation-message.test.ts index ad9afd22a70..ca9810ebd56 100644 --- a/packages/spec/src/system/operation-message.test.ts +++ b/packages/spec/src/system/operation-message.test.ts @@ -724,3 +724,42 @@ describe('operation message catalog — not found, unreadable query field, deleg expect(renderOperationMessage({ messageKey: 'record_not_found' }, { locale: 'zh-CN', translate })).toBe('记录不见了'); }); }); + +describe('operation message catalog — the print door\'s own 5xx sentences', () => { + const KEYS = ['print_engine_unavailable', 'print_timed_out', 'print_failed', 'print_caller_unresolved'] as const; + + it('every locale defines all four, placeholder-free', () => { + for (const [locale, catalog] of Object.entries(BUILTIN_OPERATION_MESSAGES)) { + for (const key of KEYS) { + expect(catalog[key], `${locale} defines ${key}`).toBeTypeOf('string'); + expect(catalog[key].match(/\{\{\w+\}\}/g) ?? [], `${locale}.${key}`).toEqual([]); + } + } + }); + + it('names no wire code, engine or host vocabulary — in every locale', () => { + for (const [locale, catalog] of Object.entries(BUILTIN_OPERATION_MESSAGES)) { + for (const key of KEYS) { + expect(catalog[key], `${locale}.${key}`).not.toMatch(/SERVICE_UNAVAILABLE|TIMEOUT|INTERNAL_ERROR|Chromium|OS_PRINT|\//); + } + } + }); + + it('renders the caller locale, matches a base language, and falls back to en for a locale the catalog lacks', () => { + for (const key of KEYS) { + expect(renderOperationMessage({ messageKey: key }, { locale: 'zh-CN' })).toBe(BUILTIN_OPERATION_MESSAGES['zh-CN'][key]); + expect(renderOperationMessage({ messageKey: key }, { locale: 'zh-CN' })).not.toBe(BUILTIN_OPERATION_MESSAGES.en[key]); + expect(renderOperationMessage({ messageKey: key }, { locale: 'es' })).toBe(BUILTIN_OPERATION_MESSAGES['es-ES'][key]); + expect(renderOperationMessage({ messageKey: key }, { locale: 'de-DE' })).toBe(BUILTIN_OPERATION_MESSAGES.en[key]); + } + }); + + it('each says something different from every other key, in every locale', () => { + for (const [locale, catalog] of Object.entries(BUILTIN_OPERATION_MESSAGES)) { + for (const key of KEYS) { + const others = Object.entries(catalog).filter(([k]) => k !== key).map(([, v]) => v); + expect(others, `${locale}.${key}`).not.toContain(catalog[key]); + } + } + }); +}); diff --git a/packages/spec/src/system/operation-message.ts b/packages/spec/src/system/operation-message.ts index 0b9357ccc0a..8781693143c 100644 --- a/packages/spec/src/system/operation-message.ts +++ b/packages/spec/src/system/operation-message.ts @@ -308,6 +308,22 @@ export function operationMessageTranslationKey(messageKey: string): string { * delegated administrator's write outside their own `adminScope`. The * reason in `message` names business units and permission sets by their * API names and ids; the user's half names none of them. + * + * The four `print_*` keys are the print door's own sentences for a print that + * failed on the server (`POST /api/v1/print/records`, `@objectstack/service-print`): + * the `message` of a 5xx whose producer declared no text for its caller. The + * door writes them in the request's language (`Accept-Language`) through + * `operationUserMessage` (`@objectstack/core`). None takes a placeholder: what + * the engine or the host said is withheld from the wire and kept in the server + * fault log, so the sentence can only name the situation. + * + * - `print_engine_unavailable` — `503`: the print engine is not ready. + * - `print_timed_out` — `504`: the render ran past the time a print is allowed. + * - `print_failed` — any other 5xx, the door's fallback. + * - `print_caller_unresolved` — `500`: the door could not resolve who asked. + * + * Their English is byte-identical to the fixed sentences the door answered + * before they were localized. */ export const BUILTIN_OPERATION_MESSAGES: Record> = { en: { @@ -369,6 +385,11 @@ export const BUILTIN_OPERATION_MESSAGES: Record> 'This request filters, sorts or groups by a field you do not have access to. Remove that condition and try again, or contact your administrator if you need access.', delegation_scope_violation: 'This change is outside the scope you were delegated to administer. Contact your administrator if it needs to be made.', + print_engine_unavailable: + 'Records cannot be printed to a file right now: the print engine is not ready. The server log records why.', + print_timed_out: 'The record could not be printed to a file in the time a print is allowed.', + print_failed: 'The record could not be printed to a file because of an error on the server.', + print_caller_unresolved: 'The caller of this print could not be resolved.', }, 'zh-CN': { permission_denied: '您没有执行此操作的权限,如需访问请联系管理员。', @@ -407,6 +428,10 @@ export const BUILTIN_OPERATION_MESSAGES: Record> record_not_found: '该记录不存在,或您无权访问它。', query_field_not_readable: '当前请求按您无权查看的字段筛选、排序或分组,请去掉该条件后重试,或联系管理员。', delegation_scope_violation: '此更改超出了您被委派管理的范围,如需更改请联系管理员。', + print_engine_unavailable: '暂时无法将记录打印为文件:打印引擎尚未就绪,原因已记录在服务器日志中。', + print_timed_out: '记录未能在打印允许的时间内打印为文件。', + print_failed: '服务器出错,记录未能打印为文件。', + print_caller_unresolved: '无法确认发起此次打印的用户。', }, 'ja-JP': { permission_denied: 'この操作を実行する権限がありません。アクセスが必要な場合は管理者にお問い合わせください。', @@ -462,6 +487,11 @@ export const BUILTIN_OPERATION_MESSAGES: Record> 'この要求は、閲覧権限のない項目で絞り込み、並べ替え、またはグループ化しています。その条件を削除して再試行するか、アクセスが必要な場合は管理者にお問い合わせください。', delegation_scope_violation: 'この変更は、管理を委任された範囲を超えています。変更が必要な場合は管理者にお問い合わせください。', + print_engine_unavailable: + '現在、レコードをファイルに印刷できません。印刷エンジンの準備ができていません。原因はサーバーログに記録されています。', + print_timed_out: '印刷に許可された時間内にレコードをファイルに印刷できませんでした。', + print_failed: 'サーバーでエラーが発生したため、レコードをファイルに印刷できませんでした。', + print_caller_unresolved: 'この印刷を要求したユーザーを特定できませんでした。', }, 'es-ES': { permission_denied: @@ -522,6 +552,11 @@ export const BUILTIN_OPERATION_MESSAGES: Record> 'Esta solicitud filtra, ordena o agrupa por un campo al que no tiene acceso. Quite esa condición e inténtelo de nuevo, o póngase en contacto con su administrador si necesita acceso.', delegation_scope_violation: 'Este cambio está fuera del ámbito que se le ha delegado para administrar. Póngase en contacto con su administrador si es necesario realizarlo.', + print_engine_unavailable: + 'Ahora mismo no se pueden imprimir registros en un archivo: el motor de impresión no está listo. El motivo consta en el log del servidor.', + print_timed_out: 'No se pudo imprimir el registro en un archivo en el tiempo permitido para una impresión.', + print_failed: 'No se pudo imprimir el registro en un archivo debido a un error en el servidor.', + print_caller_unresolved: 'No se pudo identificar a la persona que solicitó esta impresión.', }, };