Skip to content

Commit a2205a8

Browse files
fix(rest): the cached by-name meta read revalidates across a translation change (#38495)
Fixes #38288 Clause-②: no Metadata-protocol: none ## 维护者速读 用户能看到什么变化:前台和接口客户端在翻译更新后,再次打开对象或报表时会立刻看到新的显示名称,翻译故障恢复后提示也会随之消失;以前要强制刷新才行。 为什么做:多语言显示的缓存漏洞,翻译变了而缓存校验没变,客户端一直沿用旧文字(来自翻译故障提示那张卡的复审发现)。 出错会怎样:最坏情况是客户端多拿一次完整内容、少一次缓存命中,不会出现错误数据;本改动可以直接撤回。 要你做什么:无 ## What changes The default by-name metadata read (`GET /meta/:type/:name`, the cached door, `metadata.enableCache: true`) issued an `ETag` the protocol computed from the stored document and the locale, and translated the item only after `If-None-Match` was judged against it. A translation edit, or a translation fault beginning or clearing, moved no byte of that validator, so a revalidating client was answered `304` and kept the old labels, or kept a `translationWarning` after the fault had cleared. ADR-0156 D3 (verbatim: "The per-caller gate, the field mask, translation into the caller's locale and the `ETag` are computed on every request, over the cached part.") decides the shape: the door now translates on every request BEFORE it judges the request, and folds what the translation contributed into the validator. - `packages/rest/src/meta-item-read-routes.ts` (the landing point; the validator's input must come from the REST door because the translation happens there and the protocol has no i18n): the cached arm never hands the protocol `ifNoneMatch` any more and judges `If-None-Match` itself for every type, after `translateMetaEnvelope`. A new `cachedTranslationFingerprint` (the translated item and the fault warning, hashed) is folded into the validator with the existing folds. It is EMPTY when the translation changed nothing and reported no fault, so such a read keeps the exact `ETag` it had before. The action arm's early `304` moved into the common judgment for the same reason. The nested fold chain became one ordered list; the fold order, and so every existing `ETag` value, is unchanged. - `packages/metadata-protocol/src/protocol-search-and-cache.ts`: comment only, at the validator: the locale is all of the translation it holds, so a door that translates must not hand it `ifNoneMatch`. - Why a hash of the translated output and not a bundle version: none exists. `II18nService` declares no version or change counter, and ADR-0156 lists translation bundles among the sources "with no counter". The translation also reads the packaged base, the pair's and the patching packages' translations; only its output says what all of them produced. Adding a counter would be a new contract surface. - The translated answer is not cached; only the validator changes. ## Tests New `packages/rest/src/meta-item-cached-translation-etag.test.ts`: the real REST route over the real `ObjectStackProtocolImplementation` over a real `SchemaRegistry`, with an i18n double whose bundles are replaced in place and whose read can be made to fail. For `object` (the arm that already judged its own validator, before translating) and `report` (an arm the protocol judged): 1. The card's round trip: read, update the translation, revalidate with the earlier `ETag` → `200` with the new label and a new `ETag`; the new `ETag` then revalidates to `304`. 2. Control: an unchanged translation revalidates to `304`. 3. A read served during a translation fault, revalidated after the fault clears → `200`, no `translationWarning`, translated label. 4. A fault that begins after a healthy read → `200` with the warning. <details><summary>Reproduction on unfixed code, fix, ablation (head 02ae5c5)</summary> - Before the fix (test file only, on base 7e1b222): `Tests 6 failed | 2 passed (8)`, each failure `expected 304 to be 200`; the two controls passed. - With the fix: `Tests 8 passed (8)`. - Ablation via `scripts/ablation-replace.mjs` (fingerprint forced empty): anchor 1 to 0, blob 003518b to 1a5a24f60025, `Tests 6 failed | 2 passed (8)`, the same six; restored, blob equals HEAD, `git diff HEAD` empty. - `@objectstack/rest` local project, whole package: `Test Files 438 passed (438)`, `Tests 9025 passed | 351 skipped (9376)` (lock VERDICT command-exit 0; run at e626f84, the later commit removes one unused binding and adds the changeset). - `pnpm --filter @objectstack/rest typecheck` and `pnpm --filter @objectstack/metadata-protocol typecheck`: VERDICT command-exit 0 at 02ae5c5. </details> <details><summary>Derived gates (dispatch-gates --commands, 68 families, at 02ae5c5)</summary> - 66 exit 0, including `check:nul-bytes`, `check:durability-log-level`, `check:cross-package-test-inputs`, `check:test-source-alias`, `check:adr-anchors`, `check:doc-authoring`, `check:issue-citations`, `check-adr-0087-registration --base origin/main`, `check-empty-changeset`, `check-changeset-no-major`. - NOT MEASURED: `check:dual-build-cjs-loads`, reason: PREREQUISITE NOT MET (reads every package's dist; this worktree built only the rest closure). CI runs it. - NOT MEASURED: `check-plugin-teardown-shape.mjs --self-test`, reason: its pinned fixture commit is outside this shallow clone (checker health, not a verdict on this diff). - `--ran` reconciliation: 68 derived, 68 run, 0 UNRUN. </details> ## Acceptance notes - One-time revalidation miss: for a translated read (a locale whose translation changes the item), the `ETag` gains a fold, so each client gets one `200` after this deploys, then `304`s as before. A read the translation does not change keeps its `ETag` byte for byte. - Cost: a revalidation that the protocol used to answer `304` without translating now translates first (the ADR-0156 D3 rule) plus up to two `JSON.stringify` of the item. NOT MEASURED: per-request latency, reason: no load harness in scope; the uncached doors already hash the full served body per request. - `GET /meta/:type/:name` wire behaviour moves (when a `304` is answered); no spec schema, export or error code changes. ## Verification Read first, by risk: `packages/rest/src/meta-item-read-routes.ts` (the cached arm: `cacheRequest`, the translate-before-judge block, the fold list and the `304` condition; then `cachedTranslationFingerprint` at the bottom), then the new test file. Two-minute check: `pnpm --filter @objectstack/rest exec vitest run --maxWorkers=2 src/meta-item-cached-translation-etag.test.ts` → `Tests 8 passed (8)`. Account: os-project-manager --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5pH8MaBBP5T2dVcTHL)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent dccf836 commit a2205a8

4 files changed

Lines changed: 314 additions & 61 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/rest': patch
3+
---
4+
5+
fix(rest): the cached `GET /meta/:type/:name` validator moves when the served translation moves
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The default by-name metadata read (the cached door, `metadata.enableCache: true`) computed its `ETag` from the stored document and the locale, and translated the item only after judging `If-None-Match` against it. A client revalidating after a translation edit was answered `304` and kept the old labels; a client that read the item during a translation fault was answered `304` after the fault cleared and kept the `translationWarning`.
11+
12+
The door now translates the item on every request before it judges the request, and folds what the translation contributed (the translated item, and the `translationWarning` of a fault) into the validator. A translation edit, a fault that begins and a fault that clears each answer `200` under a new `ETag`; an unchanged translation still revalidates to `304`. A read whose translation changes nothing keeps the `ETag` it had before. The translated answer itself is not cached.

‎packages/metadata-protocol/src/protocol-search-and-cache.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,15 @@ export class ProtocolSearchAndCacheFacet {
9595
// language until a hard refresh (issue #1319). Folding the resolved
9696
// locale into the hash gives each locale a distinct validator.
9797
//
98+
// [#38288 · ADR-0156 D3] The locale is all of the translation this
99+
// validator holds: a translation edit, or a translation fault
100+
// beginning or clearing, moves none of these bytes. So a door that
101+
// translates the item must not hand this read its `ifNoneMatch`:
102+
// it translates first, folds what the translation contributed into
103+
// this value and judges the conditional request itself (the REST
104+
// cached door, `packages/rest`, does). The `304` below is right
105+
// only for a caller that serves `item` untranslated.
106+
//
98107
// [ADR-0131 D6] No organization is part of the validator: the
99108
// read is the environment's for every caller, so the document
100109
// hashed below is the whole scope. An org-less caller's validator
Lines changed: 185 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,185 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
//
3+
// [#38288] The default `GET /meta/:type/:name` (the CACHED door,
4+
// `metadata.enableCache` defaults to `true`) issues a validator that moves when
5+
// the served TRANSLATION moves.
6+
//
7+
// The defect: the protocol's validator (`getMetaItemCached`) hashes the stored
8+
// document and the locale, and the REST door translated the item only after
9+
// that validator was judged. A client revalidating with `If-None-Match` after a
10+
// translation edit was answered `304` and kept the old labels; a client that
11+
// read the item during a translation fault was answered `304` after the fault
12+
// cleared and kept the `translationWarning`.
13+
//
14+
// ADR-0156 D3: the translation and the `ETag` are computed on every request,
15+
// over the cached part. So the door translates first and folds what the
16+
// translation contributed into the validator before it judges the request.
17+
//
18+
// Everything is real but the i18n service: the REST route handlers over the
19+
// real `ObjectStackProtocolImplementation` over a real `SchemaRegistry`. The
20+
// i18n double holds mutable bundles, the way `loadTranslations` replaces a
21+
// locale's bundle on a live service, and can be made to fail its read.
22+
//
23+
// Two arms of the cached door, both measured:
24+
// - `object`: the door folds and judges the validator itself (its per-caller
25+
// gate); before the fix it judged it before translating.
26+
// - `report`: no per-caller step, so the protocol judged the validator; the
27+
// door now judges it after translating, for every type.
28+
29+
import { describe, it, expect, vi } from 'vitest';
30+
import { SchemaRegistry } from '@objectstack/objectql';
31+
import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol';
32+
import { RestServer } from './rest-server.js';
33+
import { META_TRANSLATION_FAULT_WARNING } from './meta-item-read-gate.js';
34+
35+
const clone = <T>(v: T): T => JSON.parse(JSON.stringify(v)) as T;
36+
37+
const CUSTOMER = {
38+
name: 'crm_customer',
39+
label: 'Customer',
40+
fields: { title: { name: 'title', type: 'text', label: 'Title' } },
41+
};
42+
const PIPELINE = { name: 'crm_pipeline', label: 'Pipeline', objectName: 'crm_customer', type: 'tabular' };
43+
44+
/** A `de` bundle naming the object and the report with `label`. */
45+
function deBundle(label: string) {
46+
return {
47+
objects: { crm_customer: { label, fields: { title: { label: `${label} Titel` } } } },
48+
reports: { crm_pipeline: { label } },
49+
};
50+
}
51+
52+
/** An `II18nService` double: bundles replaced in place, a read that can be made to fail. */
53+
function i18nDouble() {
54+
const bundles: Record<string, Record<string, unknown>> = { en: {}, de: deBundle('Kunde') };
55+
const state = { fault: false };
56+
const svc = {
57+
getLocales: () => Object.keys(bundles),
58+
getTranslations: (locale: string) => {
59+
if (state.fault) throw new Error('translation store unreachable');
60+
return bundles[locale] ?? {};
61+
},
62+
loadTranslations: (locale: string, data: Record<string, unknown>) => { bundles[locale] = data; },
63+
getDefaultLocale: () => 'en',
64+
getFallbackLocale: () => 'en',
65+
t: (key: string) => key,
66+
};
67+
return { svc, state };
68+
}
69+
70+
function createMockServer() {
71+
return {
72+
get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn(), patch: vi.fn(),
73+
use: vi.fn(),
74+
listen: vi.fn().mockResolvedValue(undefined),
75+
close: vi.fn().mockResolvedValue(undefined),
76+
};
77+
}
78+
79+
function host() {
80+
const registry = new SchemaRegistry();
81+
registry.registerObject(clone(CUSTOMER) as never, 'pkg_code', undefined, 'own');
82+
registry.registerItem('report', clone(PIPELINE) as never, 'name' as never, 'pkg_code');
83+
const engine = { registry, find: async () => [], count: async () => 0 };
84+
const protocol: any = new ObjectStackProtocolImplementation(engine as never, () => new Map());
85+
const cached = vi.spyOn(protocol, 'getMetaItemCached');
86+
const i18n = i18nDouble();
87+
const rest = new RestServer(
88+
createMockServer() as never, protocol as never, { api: { requireAuth: false } } as never,
89+
undefined, undefined, undefined, undefined, undefined,
90+
undefined, undefined, undefined, undefined, undefined,
91+
// i18nServiceProvider — the 14th constructor argument.
92+
async () => i18n.svc,
93+
);
94+
(rest as unknown as { resolveExecCtx: () => Promise<unknown> }).resolveExecCtx =
95+
async () => ({ userId: 'test-user', systemPermissions: [] });
96+
rest.registerRoutes();
97+
return { rest, i18n, cached };
98+
}
99+
100+
async function read(h: ReturnType<typeof host>, type: string, name: string, ifNoneMatch?: string) {
101+
const route = (h.rest as any).getRoutes().find((r: any) => r.method === 'GET' && r.path === '/api/v1/meta/:type/:name');
102+
if (!route) throw new Error('route not registered: GET /api/v1/meta/:type/:name');
103+
let status = 200;
104+
let body: any;
105+
const headers: Record<string, string> = {};
106+
const res: any = {
107+
status: (c: number) => { status = c; return res; },
108+
json: (b: unknown) => { body = b; return res; },
109+
send: (b: unknown) => { body = b; return res; },
110+
header: (k: string, v: string) => { headers[k] = v; return res; },
111+
setHeader: () => res, write: () => true, end: () => res,
112+
};
113+
const requestHeaders: Record<string, string> = { 'accept-language': 'de' };
114+
if (ifNoneMatch !== undefined) requestHeaders['if-none-match'] = ifNoneMatch;
115+
await route.handler({ method: 'GET', params: { type, name }, query: {}, headers: requestHeaders, body: {} }, res);
116+
return { status, body, etag: headers.ETag };
117+
}
118+
119+
const CASES = [
120+
{ type: 'object', name: CUSTOMER.name },
121+
{ type: 'report', name: PIPELINE.name },
122+
] as const;
123+
124+
for (const { type, name } of CASES) {
125+
describe(`[#38288] the cached GET /meta/${type}/:name revalidates across a translation change`, () => {
126+
it('a translation edit moves the ETag: the earlier ETag is answered 200 with the new label', async () => {
127+
const h = host();
128+
const first = await read(h, type, name);
129+
expect(first.status).toBe(200);
130+
expect(first.body.item.label).toBe('Kunde');
131+
expect(typeof first.etag).toBe('string');
132+
// The cached door, measured — not the uncached read.
133+
expect(h.cached).toHaveBeenCalled();
134+
135+
h.i18n.svc.loadTranslations('de', deBundle('Kundin'));
136+
const again = await read(h, type, name, first.etag);
137+
expect(again.status).toBe(200);
138+
expect(again.body.item.label).toBe('Kundin');
139+
expect(again.etag).not.toBe(first.etag);
140+
141+
// …and the new ETag revalidates to 304 while nothing moves.
142+
const settled = await read(h, type, name, again.etag);
143+
expect(settled.status).toBe(304);
144+
expect(settled.body).toBeUndefined();
145+
});
146+
147+
it('control: an unchanged translation revalidates to 304 under the ETag it issued', async () => {
148+
const h = host();
149+
const first = await read(h, type, name);
150+
expect(first.status).toBe(200);
151+
const again = await read(h, type, name, first.etag);
152+
expect(again.status).toBe(304);
153+
expect(again.body).toBeUndefined();
154+
});
155+
156+
it('a read served during a translation fault is answered 200, without the warning, once the fault clears', async () => {
157+
const h = host();
158+
h.i18n.state.fault = true;
159+
const faulted = await read(h, type, name);
160+
expect(faulted.status).toBe(200);
161+
expect(faulted.body.translationWarning).toBe(META_TRANSLATION_FAULT_WARNING);
162+
expect(faulted.body.item.label).toBe(type === 'object' ? CUSTOMER.label : PIPELINE.label);
163+
164+
h.i18n.state.fault = false;
165+
const healed = await read(h, type, name, faulted.etag);
166+
expect(healed.status).toBe(200);
167+
expect(healed.body).not.toHaveProperty('translationWarning');
168+
expect(healed.body.item.label).toBe('Kunde');
169+
expect(healed.etag).not.toBe(faulted.etag);
170+
});
171+
172+
it('a fault that begins after a healthy read is answered 200 with the warning', async () => {
173+
const h = host();
174+
const healthy = await read(h, type, name);
175+
expect(healthy.status).toBe(200);
176+
expect(healthy.body).not.toHaveProperty('translationWarning');
177+
178+
h.i18n.state.fault = true;
179+
const faulted = await read(h, type, name, healthy.etag);
180+
expect(faulted.status).toBe(200);
181+
expect(faulted.body.translationWarning).toBe(META_TRANSLATION_FAULT_WARNING);
182+
expect(faulted.etag).not.toBe(healthy.etag);
183+
});
184+
});
185+
}

0 commit comments

Comments
 (0)