Skip to content

Commit 554ca28

Browse files
committed
fix(service-storage): Setup storage test connection answers in the caller's language
The storage/test settings action writes its message in the locale the settings action route hands the handler (Accept-Language, else ?locale): success, probe mismatch and incomplete S3 settings in en, zh-CN, ja-JP and es-ES; an adapter's own error text stays verbatim behind a localized lead-in outside English. Absent or unknown locale answers in English. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Utp6CaWLG2RrgKub5oRNjC
1 parent c23eafa commit 554ca28

4 files changed

Lines changed: 285 additions & 6 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/service-storage': patch
3+
---
4+
5+
fix(service-storage): Setup → Storage → Test connection answers in the caller's language
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The `storage/test` settings action writes its `message` in the language the settings action route hands its handler as `locale` (`Accept-Language`, else `?locale`), the same source the mail test notice reads. It covers the sentences the product writes: the success sentence (which still names the adapter), the refusal when the probe read back is not the one written, and the refusal for S3 settings missing a bucket or a region. An adapter's own error text stays verbatim: alone in English, as before; in another language behind a lead-in saying the connection test failed. Locales: `en`, `zh-CN`, `ja-JP`, `es-ES`; an absent locale, or one with no copy, is answered in English exactly as before. `ok`, `severity`, the probe and its cleanup, and the operator log lines are unchanged.

‎packages/services/service-storage/src/storage-service-plugin.ts‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ import { mayActIrreversibly } from '@objectstack/platform-objects/system';
8787
import { FILE_REFERENCES_MIGRATION_ID } from '@objectstack/spec/system';
8888
import { inProcessSessionReadInput } from '@objectstack/types';
8989
import { SwappableStorageService } from './swappable-storage-service.js';
90+
import { S3SettingsIncompleteError, storageTestCopy } from './storage-test-copy.js';
9091
import {
9192
resolveStorageTarget,
9293
needsStorageSwap,
@@ -286,7 +287,7 @@ export class StorageServicePlugin implements Plugin {
286287
const bucket = values.s3_bucket as string | undefined;
287288
const region = values.s3_region as string | undefined;
288289
if (!bucket || !region) {
289-
throw new Error('StorageServicePlugin: S3 adapter requires s3_bucket and s3_region');
290+
throw new S3SettingsIncompleteError();
290291
}
291292
const opts: S3StorageAdapterOptions = {
292293
bucket,
@@ -814,7 +815,11 @@ export class StorageServicePlugin implements Plugin {
814815
// Register the live `storage/test` probe handler.
815816
if (typeof settings.registerAction === 'function' && this.storage) {
816817
const proxy = this.storage;
817-
settings.registerAction('storage', 'test', async ({ values, payload }: any) => {
818+
settings.registerAction('storage', 'test', async ({ values, payload, locale }: any) => {
819+
// [#30335] The answer is the toast the administrator reads: written
820+
// in the caller's display language, which the settings action
821+
// route hands over as `locale` (English when none is given).
822+
const copy = storageTestCopy(typeof locale === 'string' ? locale : undefined);
818823
// Merge the (possibly unsaved) form state posted as
819824
// `payload.values` over the persisted snapshot so an operator
820825
// can validate edits before hitting "Save". Matches the
@@ -851,7 +856,10 @@ export class StorageServicePlugin implements Plugin {
851856
try {
852857
target = await this.buildAdapterFromValues(merged);
853858
} catch (err: any) {
854-
return { ok: false, severity: 'error', message: err?.message ?? String(err) };
859+
const message = err instanceof S3SettingsIncompleteError
860+
? copy.s3SettingsIncomplete
861+
: copy.failed(err?.message ?? String(err));
862+
return { ok: false, severity: 'error', message };
855863
}
856864
}
857865

@@ -900,18 +908,18 @@ export class StorageServicePlugin implements Plugin {
900908
// unguarded delete, whose failure IS a probe failure the
901909
// operator must be told about, and no path deletes twice.
902910
await removeProbeObject();
903-
return { ok: false, severity: 'error', message: 'Probe download did not match upload.' };
911+
return { ok: false, severity: 'error', message: copy.downloadMismatch };
904912
}
905913
await target.delete(probeKey);
906914
const adapter = String(merged.adapter ?? this.options.adapter ?? 'local');
907915
return {
908916
ok: true,
909917
severity: 'info',
910-
message: `Storage round-trip succeeded (adapter=${adapter}).`,
918+
message: copy.succeeded(adapter),
911919
};
912920
} catch (err: any) {
913921
await removeProbeObject();
914-
return { ok: false, severity: 'error', message: err?.message ?? String(err) };
922+
return { ok: false, severity: 'error', message: copy.failed(err?.message ?? String(err)) };
915923
}
916924
});
917925
ctx.logger.info('StorageServicePlugin: registered settings action storage/test');
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#30335] The sentences Setup → Storage → 测试连接 (`storage/test`) answers
5+
* with, one entry per locale this package's `translations/` serves.
6+
*
7+
* The console prints the action's `message` as the toast, bare, so the
8+
* sentence is the administrator's whole answer. The settings action route
9+
* hands the handler the caller's display language (`Accept-Language`, else
10+
* `?locale`) as the input's `locale`; an absent locale, or one with no entry
11+
* here, is answered in English, the sentence every caller got before.
12+
*
13+
* Only the sentences the product writes live here. An adapter's own error
14+
* text (the S3 SDK's, the file system's) is passed through verbatim: in
15+
* English on its own, as it always was; in another language behind a lead-in
16+
* that says the connection test failed, so the reader knows what the
17+
* untranslated part is. The operator log lines stay English.
18+
*/
19+
20+
import { resolveLocale } from '@objectstack/core';
21+
22+
/** The English refusal for S3 settings missing a bucket or a region. */
23+
export const S3_SETTINGS_INCOMPLETE_MESSAGE =
24+
'StorageServicePlugin: S3 adapter requires s3_bucket and s3_region';
25+
26+
/**
27+
* Thrown when the `storage` settings name the S3 adapter without a bucket or a
28+
* region. Its message is the English refusal the operator log has always
29+
* carried; the `storage/test` answer reads the type to write the refusal in the
30+
* caller's language instead.
31+
*/
32+
export class S3SettingsIncompleteError extends Error {
33+
constructor() {
34+
super(S3_SETTINGS_INCOMPLETE_MESSAGE);
35+
this.name = 'S3SettingsIncompleteError';
36+
}
37+
}
38+
39+
export interface StorageTestCopy {
40+
/** The probe object was written, read back identical and deleted. */
41+
succeeded(adapter: string): string;
42+
/** The probe object read back is not the one written. */
43+
downloadMismatch: string;
44+
/** The S3 adapter was chosen without a bucket or a region. */
45+
s3SettingsIncomplete: string;
46+
/** The adapter refused; `reason` is its own text, verbatim. */
47+
failed(reason: string): string;
48+
}
49+
50+
export const STORAGE_TEST_COPY: Record<'en' | 'zh-CN' | 'ja-JP' | 'es-ES', StorageTestCopy> = {
51+
en: {
52+
succeeded: (adapter) => `Storage round-trip succeeded (adapter=${adapter}).`,
53+
downloadMismatch: 'Probe download did not match upload.',
54+
s3SettingsIncomplete: S3_SETTINGS_INCOMPLETE_MESSAGE,
55+
failed: (reason) => reason,
56+
},
57+
'zh-CN': {
58+
succeeded: (adapter) => `存储连接测试成功(适配器:${adapter})。`,
59+
downloadMismatch: '探测文件下载后的内容与上传的不一致。',
60+
s3SettingsIncomplete: 'S3 适配器需要填写存储桶(s3_bucket)和区域(s3_region)。',
61+
failed: (reason) => `存储连接测试失败:${reason}`,
62+
},
63+
'ja-JP': {
64+
succeeded: (adapter) => `ストレージの接続テストに成功しました(アダプター: ${adapter})。`,
65+
downloadMismatch: 'プローブファイルのダウンロード内容がアップロードした内容と一致しません。',
66+
s3SettingsIncomplete: 'S3 アダプターにはバケット(s3_bucket)とリージョン(s3_region)の指定が必要です。',
67+
failed: (reason) => `ストレージの接続テストに失敗しました: ${reason}`,
68+
},
69+
'es-ES': {
70+
succeeded: (adapter) => `La prueba de conexión del almacenamiento se ha completado correctamente (adaptador: ${adapter}).`,
71+
downloadMismatch: 'El archivo de prueba descargado no coincide con el que se subió.',
72+
s3SettingsIncomplete: 'El adaptador S3 necesita un bucket (s3_bucket) y una región (s3_region).',
73+
failed: (reason) => `La prueba de conexión del almacenamiento ha fallado: ${reason}`,
74+
},
75+
};
76+
77+
const COPY_LOCALES = Object.keys(STORAGE_TEST_COPY);
78+
79+
/** The copy for a caller's locale: exact, then by language, else English. */
80+
export function storageTestCopy(locale: string | undefined): StorageTestCopy {
81+
const picked = locale ? resolveLocale(locale, COPY_LOCALES) : undefined;
82+
return STORAGE_TEST_COPY[(picked ?? 'en') as keyof typeof STORAGE_TEST_COPY];
83+
}
Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#30335] Setup → Storage → 测试连接 answers in the caller's language.
5+
*
6+
* The console prints the `storage/test` action's `message` as the toast, bare.
7+
* The settings action route hands the handler the caller's display language as
8+
* the input's `locale` (`Accept-Language`, else `?locale`), the same source the
9+
* mail test notice reads. These pins run the REAL handler the plugin registers,
10+
* on a real local adapter, with that input member set or absent.
11+
*
12+
* `ok`, `severity`, the adapter name and the probe's cleanup are not the
13+
* subject: each case asserts the first two are what they were, so a
14+
* translation can never have moved a verdict.
15+
*/
16+
17+
import { describe, expect, it } from 'vitest';
18+
import { promises as fs } from 'node:fs';
19+
import { tmpdir } from 'node:os';
20+
import { join } from 'node:path';
21+
import { StorageServicePlugin } from './storage-service-plugin.js';
22+
import { LocalStorageAdapter } from './local-storage-adapter.js';
23+
import { storageTestCopy, STORAGE_TEST_COPY } from './storage-test-copy.js';
24+
25+
function makeCtx() {
26+
const services = new Map<string, unknown>();
27+
const hooks: Array<() => Promise<void> | void> = [];
28+
const ctx: any = {
29+
logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} },
30+
registerService: (name: string, svc: unknown) => { services.set(name, svc); },
31+
getService: <T>(name: string): T => {
32+
const s = services.get(name);
33+
if (!s) throw new Error(`service '${name}' not registered`);
34+
return s as T;
35+
},
36+
hook: (event: string, fn: () => Promise<void> | void) => {
37+
if (event === 'kernel:ready') hooks.push(fn);
38+
},
39+
_flushReady: async () => { for (const h of hooks) await h(); },
40+
};
41+
return ctx;
42+
}
43+
44+
/** A settings host that keeps the registered action so a test can run it. */
45+
function makeSettingsHost() {
46+
const actions = new Map<string, (input: unknown) => Promise<any>>();
47+
return {
48+
createClient: (_ns: string) => ({}),
49+
getNamespace: async (_ns: string) => ({ values: {} }),
50+
subscribe: (_ns: string, _fn: () => void) => {},
51+
registerAction: (ns: string, id: string, fn: (input: unknown) => Promise<any>) => {
52+
actions.set(`${ns}/${id}`, fn);
53+
},
54+
run: async (input: Record<string, unknown>) => {
55+
const fn = actions.get('storage/test');
56+
if (!fn) throw new Error('storage/test was not registered');
57+
return await fn({ namespace: 'storage', actionId: 'test', ctx: {}, ...input });
58+
},
59+
};
60+
}
61+
62+
async function bootPlugin() {
63+
const root = await fs.mkdtemp(join(tmpdir(), 'oss-30335-'));
64+
const plugin = new StorageServicePlugin({ adapter: 'local', local: { rootDir: root }, registerRoutes: false });
65+
const ctx = makeCtx();
66+
const settings = makeSettingsHost();
67+
ctx.registerService('settings', settings);
68+
await plugin.init(ctx);
69+
await plugin.start(ctx);
70+
await ctx._flushReady();
71+
return { root, settings, plugin };
72+
}
73+
74+
/** The local adapter with a download that answers bytes other than the ones uploaded. */
75+
function corruptDownloads(): () => void {
76+
const original = LocalStorageAdapter.prototype.download;
77+
LocalStorageAdapter.prototype.download = async function (this: LocalStorageAdapter, key: string) {
78+
void key;
79+
return Buffer.from('not the probe', 'utf-8');
80+
} as typeof original;
81+
return () => { LocalStorageAdapter.prototype.download = original; };
82+
}
83+
84+
describe('[#30335] storage/test answers in the caller\'s language', () => {
85+
it('zh-CN: the success sentence is Chinese and names the adapter; the verdict is unchanged', async () => {
86+
const { root, settings } = await bootPlugin();
87+
const result = await settings.run({ values: { adapter: 'local', local_root: root }, locale: 'zh-CN' });
88+
expect(result.ok).toBe(true);
89+
expect(result.severity).toBe('info');
90+
expect(result.message).toBe('存储连接测试成功(适配器:local)。');
91+
expect(result.message).not.toContain('round-trip');
92+
});
93+
94+
it('en: the success sentence is the English one the console showed before', async () => {
95+
const { root, settings } = await bootPlugin();
96+
const result = await settings.run({ values: { adapter: 'local', local_root: root }, locale: 'en-US' });
97+
expect(result.ok).toBe(true);
98+
expect(result.severity).toBe('info');
99+
expect(result.message).toBe('Storage round-trip succeeded (adapter=local).');
100+
});
101+
102+
it('no locale, or one with no copy: English, exactly as an older settings host gets it', async () => {
103+
const { root, settings } = await bootPlugin();
104+
const values = { adapter: 'local', local_root: root };
105+
for (const input of [{ values }, { values, locale: 'fr-FR' }, { values, locale: '' }]) {
106+
const result = await settings.run(input);
107+
expect(result.ok).toBe(true);
108+
expect(result.severity).toBe('info');
109+
expect(result.message).toBe('Storage round-trip succeeded (adapter=local).');
110+
}
111+
});
112+
113+
it('a language tag without the region still picks its copy (zh → zh-CN)', async () => {
114+
const { root, settings } = await bootPlugin();
115+
const result = await settings.run({ values: { adapter: 'local', local_root: root }, locale: 'zh' });
116+
expect(result.message).toBe('存储连接测试成功(适配器:local)。');
117+
});
118+
119+
it('zh-CN: a download that does not match the upload is refused in Chinese', async () => {
120+
const { root, settings } = await bootPlugin();
121+
const restore = corruptDownloads();
122+
try {
123+
const result = await settings.run({ values: { adapter: 'local', local_root: root }, locale: 'zh-CN' });
124+
expect(result.ok).toBe(false);
125+
expect(result.severity).toBe('error');
126+
expect(result.message).toBe('探测文件下载后的内容与上传的不一致。');
127+
} finally {
128+
restore();
129+
}
130+
// The probe object is still removed on this path (#13726).
131+
const left = await fs.readdir(join(root, '__objectstack_probe__')).catch(() => []);
132+
expect(left).toEqual([]);
133+
});
134+
135+
it('zh-CN: incomplete S3 settings are refused in Chinese, naming the two fields', async () => {
136+
const { settings } = await bootPlugin();
137+
const result = await settings.run({ values: { adapter: 's3', s3_bucket: '', s3_region: '' }, locale: 'zh-CN' });
138+
expect(result.ok).toBe(false);
139+
expect(result.severity).toBe('error');
140+
expect(result.message).toBe('S3 适配器需要填写存储桶(s3_bucket)和区域(s3_region)。');
141+
});
142+
143+
it('no locale: incomplete S3 settings keep the English refusal', async () => {
144+
const { settings } = await bootPlugin();
145+
const result = await settings.run({ values: { adapter: 's3', s3_bucket: '', s3_region: '' } });
146+
expect(result.ok).toBe(false);
147+
expect(result.message).toBe('StorageServicePlugin: S3 adapter requires s3_bucket and s3_region');
148+
});
149+
150+
it('zh-CN: the adapter\'s own error text stays verbatim behind a Chinese lead-in', async () => {
151+
const { settings } = await bootPlugin();
152+
// A root the process cannot create: a path under a regular FILE.
153+
const file = join(await fs.mkdtemp(join(tmpdir(), 'oss-30335-file-')), 'not-a-dir');
154+
await fs.writeFile(file, 'x');
155+
const zh = await settings.run({ values: { adapter: 'local', local_root: join(file, 'root') }, locale: 'zh-CN' });
156+
const en = await settings.run({ values: { adapter: 'local', local_root: join(file, 'root') } });
157+
expect(zh.ok).toBe(false);
158+
expect(zh.severity).toBe('error');
159+
expect(en.ok).toBe(false);
160+
// English stays the adapter's sentence alone; Chinese is lead-in + that same sentence.
161+
expect(en.message.length).toBeGreaterThan(0);
162+
expect(zh.message).toBe(`存储连接测试失败:${en.message}`);
163+
});
164+
});
165+
166+
describe('[#30335] the storage/test copy table', () => {
167+
it('serves every locale the package\'s translations serve, each with every sentence', () => {
168+
expect(Object.keys(STORAGE_TEST_COPY).sort()).toEqual(['en', 'es-ES', 'ja-JP', 'zh-CN']);
169+
for (const locale of Object.keys(STORAGE_TEST_COPY)) {
170+
const copy = storageTestCopy(locale);
171+
expect(copy.succeeded('s3')).toContain('s3');
172+
expect(copy.downloadMismatch.length).toBeGreaterThan(0);
173+
expect(copy.s3SettingsIncomplete).toContain('s3_bucket');
174+
expect(copy.s3SettingsIncomplete).toContain('s3_region');
175+
expect(copy.failed('EACCES')).toContain('EACCES');
176+
}
177+
});
178+
});

0 commit comments

Comments
 (0)