Skip to content

Commit ad08707

Browse files
committed
test(rest): red pin — the layered view of a name two packages hold, naming no package
Claude-Session: https://claude.ai/code/session_01FEkQ5o95tvF7A7y85W37iR Co-authored-by: Claude <noreply@anthropic.com>
1 parent efb1620 commit ad08707

1 file changed

Lines changed: 213 additions & 0 deletions

File tree

Lines changed: 213 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,213 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#28337, ADR-0048] The layered view naming no package, of a name two packages
5+
* hold, on `RestServer`: refused with the package-less writes' own refusal.
6+
*
7+
* A `sys_metadata` row is keyed `(org, type, name, package_id)`. When the
8+
* active rows of one name are bound to two or more packages, a save or a delete
9+
* naming no package is refused `409 RESOURCE_CONFLICT` with the `?package=`
10+
* prescription, naming the holders (`packagelessAddressAmbiguityRefusal`).
11+
* The layered view — `GET /meta/:type/:name/layers` and the deprecated
12+
* `?layers=true` — answered the same request `200` with ONE holder's overlay,
13+
* picked silently, so the Studio editor (which loads the layered view and saves
14+
* what it loaded) and an agent could not tell a second holder existed, and the
15+
* save that followed was refused. Now both spellings refuse it exactly where the
16+
* writes do, with the same code, status and holder list; `?package=` still reads
17+
* each holder's stack.
18+
*
19+
* The protocol and the registry are the REAL ones; only `sys_metadata` is held
20+
* in memory (the harness of `meta-disabled-package-doors.test.ts`).
21+
*/
22+
23+
import { describe, it, expect, vi } from 'vitest';
24+
import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/metadata-core';
25+
import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol';
26+
import { SchemaRegistry } from '@objectstack/objectql';
27+
import { RestServer } from './rest-server.js';
28+
29+
const META = '/api/v1/meta';
30+
const PKG_A = 'app.alpha_demo';
31+
const PKG_B = 'app.beta_demo';
32+
33+
const rowKey = (w: Record<string, unknown>) =>
34+
[w.type, w.name, w.organization_id ?? '', w.package_id ?? '', w.state ?? 'active'].join('|');
35+
36+
const whereValueMatches = (actual: unknown, want: unknown): boolean =>
37+
want !== null && typeof want === 'object' && Array.isArray((want as { $in?: unknown }).$in)
38+
? (want as { $in: unknown[] }).$in.includes(actual)
39+
: actual === want;
40+
41+
const matchesWhere = (row: Record<string, unknown>, where: Record<string, unknown>) =>
42+
Object.entries(where).every(([k, v]) => {
43+
if (k.startsWith('$')) throw new Error(`fake driver: unsupported operator ${k}`);
44+
if (v === null) return row[k] === null || row[k] === undefined;
45+
return whereValueMatches(row[k], v);
46+
});
47+
48+
/** In-memory `sys_metadata` carrying a REAL `SchemaRegistry`. */
49+
function makeHarness() {
50+
const registry = new SchemaRegistry({ multiTenant: false });
51+
(registry as any).logLevel = 'silent';
52+
const rows = new Map<string, any>();
53+
let nextId = 0;
54+
const findRow = (w: Record<string, unknown>) => {
55+
for (const [k, r] of rows) if (matchesWhere(r, w)) return { key: k, row: r };
56+
return null;
57+
};
58+
const engine: any = {
59+
registry,
60+
async findOne(table: string, o: { where: Record<string, unknown> }) {
61+
assertEngineFindOnePredicate(table, o);
62+
if (table !== 'sys_metadata') return null;
63+
return findRow(o.where)?.row ?? null;
64+
},
65+
async find(table: string, o: { where: Record<string, unknown>; limit?: number }) {
66+
if (table !== 'sys_metadata') return [];
67+
const matched = Array.from(rows.values()).filter((r) => matchesWhere(r, o.where));
68+
return typeof o?.limit === 'number' ? matched.slice(0, o.limit) : matched;
69+
},
70+
async insert(table: string, data: Record<string, unknown>) {
71+
if (table !== 'sys_metadata') return { id: `rec_${++nextId}` };
72+
const row = { id: `r_${++nextId}`, ...(data as any) };
73+
rows.set(rowKey(data), row);
74+
return { id: row.id };
75+
},
76+
async update(table: string, data: Record<string, unknown>, o: { where: Record<string, unknown> }) {
77+
assertEngineUpdateDispatch(data, o);
78+
if (table !== 'sys_metadata') return { id: null };
79+
const found = findRow(o.where);
80+
if (!found) return { id: null };
81+
const merged = { ...found.row, ...(data as any) };
82+
rows.delete(found.key);
83+
rows.set(rowKey(merged), merged);
84+
return { id: merged.id };
85+
},
86+
async delete(table: string, o?: Record<string, unknown>) {
87+
assertEngineDeleteDispatch(o);
88+
if (table !== 'sys_metadata') return { deleted: 0 };
89+
const found = findRow(((o as any)?.where ?? {}) as Record<string, unknown>);
90+
if (!found) return { deleted: 0 };
91+
rows.delete(found.key);
92+
return { deleted: 1 };
93+
},
94+
async syncObjectSchema() { /* no physical storage in this double */ },
95+
};
96+
const protocol = new ObjectStackProtocolImplementation(engine, undefined, 'env_test');
97+
return { protocol, registry, rows };
98+
}
99+
100+
/** `twin_dash` stored in BOTH packages; `solo_dash` stored in one. */
101+
async function seed(protocol: any, registry: SchemaRegistry) {
102+
for (const [pkg, label] of [[PKG_A, 'alpha copy'], [PKG_B, 'beta copy']] as const) {
103+
registry.installPackage({ id: pkg, name: pkg, version: '1.0.0' } as any, 'code');
104+
await protocol.saveMetaItem({ type: 'dashboard', name: 'twin_dash', packageId: pkg, item: { name: 'twin_dash', label, widgets: [] } });
105+
}
106+
await protocol.saveMetaItem({ type: 'dashboard', name: 'solo_dash', packageId: PKG_A, item: { name: 'solo_dash', label: 'solo', widgets: [] } });
107+
}
108+
109+
function makeRes() {
110+
const res: any = { statusCode: 200, body: undefined };
111+
res.status = vi.fn((c: number) => { res.statusCode = c; return res; });
112+
res.json = vi.fn((b: any) => { res.body = b; return res; });
113+
res.headers = {} as Record<string, string>;
114+
res.header = vi.fn((k: string, v: string) => { res.headers[k] = v; return res; });
115+
res.setHeader = vi.fn(); res.write = vi.fn(); res.end = vi.fn(); res.send = vi.fn();
116+
return res;
117+
}
118+
119+
/** An author: the save door admits them, so the writes reach the protocol. */
120+
const AUTHOR = { userId: 'u_author', systemPermissions: ['manage_metadata', 'studio.access'] };
121+
122+
async function setup() {
123+
const h = makeHarness();
124+
await seed(h.protocol, h.registry);
125+
const server = {
126+
get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn(), patch: vi.fn(), use: vi.fn(),
127+
listen: vi.fn().mockResolvedValue(undefined), close: vi.fn().mockResolvedValue(undefined),
128+
};
129+
const rest = new RestServer(server as any, h.protocol as any, { api: { requireAuth: false } } as any);
130+
(rest as any).resolveExecCtx = async () => AUTHOR;
131+
(rest as any).objectQLProvider = async () => ({ registry: h.registry });
132+
rest.registerRoutes();
133+
const call = async (
134+
method: string, pattern: string, path: string, params: Record<string, string>,
135+
query: Record<string, string> = {}, body: unknown = {},
136+
) => {
137+
const route = rest.getRoutes().find((r: any) => r.method === method && r.path === `${META}${pattern}`);
138+
if (!route) throw new Error(`${method} ${pattern} is not registered`);
139+
const res = makeRes();
140+
await route.handler({ method, path: `${META}${path}`, params, query, body, headers: {} }, res);
141+
return { status: res.statusCode as number, body: res.body, headers: res.headers as Record<string, string> };
142+
};
143+
const at = (name: string) => ({ type: 'dashboard', name });
144+
return {
145+
...h,
146+
layers: (name: string, query: Record<string, string> = {}) =>
147+
call('GET', '/:type/:name/layers', `/dashboard/${name}/layers`, at(name), query),
148+
layersFlag: (name: string, query: Record<string, string> = {}) =>
149+
call('GET', '/:type/:name', `/dashboard/${name}`, at(name), { ...query, layers: 'true' }),
150+
put: (name: string, item: Record<string, unknown>, query: Record<string, string> = {}) =>
151+
call('PUT', '/:type/:name', `/dashboard/${name}`, at(name), query, item),
152+
remove: (name: string, query: Record<string, string> = {}) =>
153+
call('DELETE', '/:type/:name', `/dashboard/${name}`, at(name), query),
154+
};
155+
}
156+
157+
/** The refusal's machine fields, wherever this transport's envelope carries them. */
158+
const codeOf = (r: { body: any }) => r.body?.code ?? r.body?.error?.code;
159+
const messageOf = (r: { body: any }) => {
160+
const m = r.body?.error?.message ?? r.body?.message ?? r.body?.error;
161+
return typeof m === 'string' ? m : '';
162+
};
163+
164+
describe('[#28337] RestServer: the layered view of a name two packages hold, naming no package', () => {
165+
it('both spellings answer the package-less writes\' 409 RESOURCE_CONFLICT, naming both holders and ?package=', async () => {
166+
const host = await setup();
167+
const save = await host.put('twin_dash', { name: 'twin_dash', label: 'edited', widgets: [] });
168+
const remove = await host.remove('twin_dash');
169+
// The writes' answer, unchanged: the refusal this read now shares.
170+
expect({ status: save.status, code: codeOf(save) }).toEqual({ status: 409, code: 'RESOURCE_CONFLICT' });
171+
expect({ status: remove.status, code: codeOf(remove) }).toEqual({ status: 409, code: 'RESOURCE_CONFLICT' });
172+
173+
for (const read of [host.layers, host.layersFlag]) {
174+
const refused = await read('twin_dash');
175+
expect({ status: refused.status, code: codeOf(refused) }).toEqual({ status: save.status, code: codeOf(save) });
176+
// One envelope shape for the read and the writes on this transport.
177+
expect(Object.keys(refused.body ?? {}).sort()).toEqual(Object.keys(save.body ?? {}).sort());
178+
const message = messageOf(refused);
179+
expect(message.startsWith('Name the package this layered read is for, then send it again')).toBe(true);
180+
expect(message).toContain('?package=');
181+
expect(message).toContain(`'${PKG_A}'`);
182+
expect(message).toContain(`'${PKG_B}'`);
183+
// Neither holder's layers ride the refusal.
184+
expect(JSON.stringify(refused.body)).not.toContain('alpha copy');
185+
expect(JSON.stringify(refused.body)).not.toContain('beta copy');
186+
}
187+
// Nothing was written or removed by any of it.
188+
expect([...host.rows.values()].filter((r) => r.name === 'twin_dash').map((r) => r.package_id).sort())
189+
.toEqual([PKG_A, PKG_B]);
190+
}, 60_000);
191+
192+
it('?package= reads each holder\'s stack, on both spellings', async () => {
193+
const host = await setup();
194+
for (const [pkg, label] of [[PKG_A, 'alpha copy'], [PKG_B, 'beta copy']] as const) {
195+
for (const read of [host.layers, host.layersFlag]) {
196+
const served = await read('twin_dash', { package: pkg });
197+
expect(served.status, JSON.stringify(served.body)).toBe(200);
198+
expect(served.body?.overlay).toMatchObject({ name: 'twin_dash', label });
199+
expect(served.body?.effective).toMatchObject({ name: 'twin_dash', label });
200+
}
201+
}
202+
}, 60_000);
203+
204+
it('a name one package holds answers as before, naming its package or not', async () => {
205+
const host = await setup();
206+
for (const read of [host.layers, host.layersFlag]) {
207+
const plain = await read('solo_dash');
208+
expect(plain.status, JSON.stringify(plain.body)).toBe(200);
209+
expect(plain.body?.effective).toMatchObject({ name: 'solo_dash', label: 'solo' });
210+
expect((await read('solo_dash', { package: PKG_A })).body).toEqual(plain.body);
211+
}
212+
}, 60_000);
213+
});

0 commit comments

Comments
 (0)