Skip to content
Draft
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
11 changes: 11 additions & 0 deletions .changeset/37260-print-failure-locale.md
Original file line number Diff line number Diff line change
@@ -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.
113 changes: 110 additions & 3 deletions packages/services/service-print/src/print-routes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -57,6 +58,8 @@ interface DoorSetup {
page?: Record<string, unknown>;
/** 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<undefined>;
}

function door(setup: DoorSetup = {}) {
Expand Down Expand Up @@ -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<string, string> } = {}) {
async function call(
opts: { bearer?: string; body?: unknown; query?: Record<string, string>; headers?: Record<string, string> } = {},
) {
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 };
Expand All @@ -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,
},
Expand Down Expand Up @@ -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<string, string>) {
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();
Expand Down
49 changes: 40 additions & 9 deletions packages/services/service-print/src/print-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
evaluateAuthGate,
isApiKeyLifecycleRefusalError,
isAuthzStoreUnavailableError,
operationUserMessage,
resolveAuthzContext,
shouldDenyAnonymous,
userAuthGateSourceOf,
Expand All @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
});
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand All @@ -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,
});
Expand Down
1 change: 1 addition & 0 deletions packages/services/service-print/vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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') },
],
},
Expand Down
39 changes: 39 additions & 0 deletions packages/spec/src/system/operation-message.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
}
}
});
});
Loading
Loading