Skip to content

Commit 02fa093

Browse files
committed
test(objectql): pin member-grain bundle reads on a base's address
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5m2Ryfx2Wubuz716mw
1 parent 455c1f1 commit 02fa093

1 file changed

Lines changed: 291 additions & 0 deletions

File tree

Lines changed: 291 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,291 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#28802, ADR-0146 D2, #28390 ruling A] Member-grain coexistence on a base's
5+
* address, for a bundle type (`ITEM_KEY_DISCRIMINATORS`: `email_template`,
6+
* one item per `(name, locale)`).
7+
*
8+
* A base ships a template in `en-US` only. Its address — the read naming it,
9+
* the read naming no package, the list scoped to it, the env-wide list and
10+
* the executing list — serves the base's members, its pair's declared
11+
* overrides, and its pair's own ADDED members (a locale the base does not
12+
* ship). A dependent package's added member under the base's name is served
13+
* only under that package's own address.
14+
*
15+
* Pinned through the real protocol over the real `ObjectQL` engine and an
16+
* in-memory driver (the harness of
17+
* `protocol-custom-override-effective-read.test.ts`), every package
18+
* installed through the package door with its dependency declared, every row
19+
* written through the draft save and the per-item publish.
20+
*
21+
* Test-path resolution: the protocol is `@objectstack/metadata-protocol`'s
22+
* `dist/`, so a change there is read here after that package is rebuilt.
23+
*/
24+
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
25+
import type { ServiceObject } from '@objectstack/spec/data';
26+
import { ObjectStackProtocolImplementation, resetEnvWritableMetadataTypes } from '@objectstack/metadata-protocol';
27+
import { SysMetadataAuditObject, SysMetadataCommitObject, SysMetadataHistoryObject } from '@objectstack/metadata-core';
28+
import { ObjectQL } from './engine.js';
29+
30+
const BASE = 'com.example.showcase';
31+
const PAIR = 'com.example.showcase.custom';
32+
const DEPENDENT = 'com.default.acme-addon';
33+
/** Shipped in `en-US` only. */
34+
const NAME = 'task_done_email';
35+
/** Shipped in `fr-FR` only: a bundle with no canonical member. */
36+
const FR_ONLY = 'task_late_email';
37+
const TYPE = 'email_template';
38+
39+
const sysMetadataObject: ServiceObject = {
40+
name: 'sys_metadata',
41+
label: 'System Metadata',
42+
fields: {
43+
id: { name: 'id', label: 'ID', type: 'text' as const },
44+
type: { name: 'type', label: 'Type', type: 'text' as const, required: true },
45+
name: { name: 'name', label: 'Name', type: 'text' as const, required: true },
46+
organization_id: { name: 'organization_id', label: 'Org', type: 'text' as const },
47+
package_id: { name: 'package_id', label: 'Package', type: 'text' as const },
48+
bundle_member: { name: 'bundle_member', label: 'Bundle Member', type: 'text' as const, maxLength: 100 },
49+
metadata: { name: 'metadata', label: 'Body', type: 'textarea' as const },
50+
draft_changes: { name: 'draft_changes', label: 'Draft Changes', type: 'textarea' as const },
51+
checksum: { name: 'checksum', label: 'Checksum', type: 'text' as const, maxLength: 71 },
52+
state: { name: 'state', label: 'State', type: 'text' as const },
53+
version: { name: 'version', label: 'Version', type: 'number' as const },
54+
created_at: { name: 'created_at', label: 'Created', type: 'datetime' as const },
55+
updated_at: { name: 'updated_at', label: 'Updated', type: 'datetime' as const },
56+
},
57+
};
58+
59+
function makeMemoryDriver() {
60+
const stores = new Map<string, Map<string, Record<string, unknown>>>();
61+
const storeFor = (obj: string) => {
62+
let s = stores.get(obj);
63+
if (!s) { s = new Map(); stores.set(obj, s); }
64+
return s;
65+
};
66+
let nextId = 0;
67+
const matchesWhere = (row: Record<string, unknown>, where: any): boolean => {
68+
if (!where || typeof where !== 'object') return true;
69+
for (const [k, v] of Object.entries(where)) {
70+
if (k === '$and' && Array.isArray(v)) {
71+
if (!v.every((w: any) => matchesWhere(row, w))) return false;
72+
continue;
73+
}
74+
if (k === '$or' && Array.isArray(v)) {
75+
if (!v.some((w: any) => matchesWhere(row, w))) return false;
76+
continue;
77+
}
78+
if (k.startsWith('$')) continue;
79+
const rowVal = row[k];
80+
if (v && typeof v === 'object' && Array.isArray((v as any).$in)) {
81+
if (!(v as any).$in.includes(rowVal === undefined ? null : rowVal)) return false;
82+
continue;
83+
}
84+
const expected = (v && typeof v === 'object' && '$eq' in (v as any)) ? (v as any).$eq : v;
85+
const a = rowVal === undefined ? null : rowVal;
86+
const b = expected === undefined ? null : expected;
87+
if (a !== b) return false;
88+
}
89+
return true;
90+
};
91+
const driver: any = {
92+
name: 'memory', version: '0.0.0', supports: {} as any,
93+
async connect() {}, async disconnect() {}, async checkHealth() { return true; },
94+
async execute() { return null; },
95+
async find(object: string, ast: any) {
96+
const rows = Array.from(storeFor(object).values()).filter((r) => matchesWhere(r, ast?.where));
97+
return typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows;
98+
},
99+
async findOne(object: string, ast: any) {
100+
for (const r of storeFor(object).values()) if (matchesWhere(r, ast?.where)) return r;
101+
return null;
102+
},
103+
async create(object: string, data: Record<string, unknown>) {
104+
nextId += 1;
105+
const id = (data.id as string) ?? `r_${nextId}`;
106+
const row = { ...data, id };
107+
storeFor(object).set(id, row);
108+
return row;
109+
},
110+
async update(object: string, id: string, data: Record<string, unknown>) {
111+
const s = storeFor(object);
112+
const cur = s.get(id);
113+
if (!cur) throw new Error(`not found: ${object}/${id}`);
114+
const updated = { ...cur, ...data, id };
115+
s.set(id, updated);
116+
return updated;
117+
},
118+
async upsert(object: string, data: Record<string, unknown>) {
119+
const id = data.id as string | undefined;
120+
if (id && storeFor(object).has(id)) return this.update(object, id, data);
121+
return this.create(object, data);
122+
},
123+
async delete(object: string, id: string) { return storeFor(object).delete(id); },
124+
async count(object: string, ast: any) { return (await this.find(object, ast)).length; },
125+
async bulkCreate(object: string, rows: Record<string, unknown>[]) {
126+
return Promise.all(rows.map((r) => this.create(object, r)));
127+
},
128+
async bulkUpdate() { return []; }, async bulkDelete() {},
129+
async beginTransaction() { return { commit: async () => {}, rollback: async () => {} }; },
130+
async commit() {}, async rollback() {},
131+
};
132+
return { driver, stores };
133+
}
134+
135+
const template = (name: string, locale: string, subject: string) => ({
136+
name, locale, label: name, subject, bodyHtml: `<p>${subject}</p>`, bodyText: `${subject} body`, active: true,
137+
});
138+
139+
function baseManifest(): Record<string, unknown> {
140+
return {
141+
id: BASE,
142+
name: 'showcase',
143+
version: '1.0.0',
144+
namespace: 'showcase',
145+
emailTemplates: [template(NAME, 'en-US', 'Base EN'), template(FR_ONLY, 'fr-FR', 'Base late FR')],
146+
};
147+
}
148+
149+
async function boot() {
150+
const engine = new ObjectQL();
151+
const { driver } = makeMemoryDriver();
152+
engine.registerDriver(driver, true);
153+
await engine.init();
154+
engine.registry.registerObject(sysMetadataObject, 'test-package');
155+
for (const o of [SysMetadataHistoryObject, SysMetadataAuditObject, SysMetadataCommitObject]) {
156+
engine.registry.registerObject(o as any, 'test-package');
157+
}
158+
engine.registerApp(baseManifest());
159+
const protocol = new ObjectStackProtocolImplementation(engine, () => new Map());
160+
return { engine, protocol };
161+
}
162+
163+
const savedWritable = process.env.OS_METADATA_WRITABLE;
164+
beforeEach(() => {
165+
delete process.env.OS_METADATA_WRITABLE;
166+
ObjectStackProtocolImplementation.resetEnvWritableCache();
167+
resetEnvWritableMetadataTypes();
168+
});
169+
afterEach(() => {
170+
if (savedWritable === undefined) delete process.env.OS_METADATA_WRITABLE;
171+
else process.env.OS_METADATA_WRITABLE = savedWritable;
172+
ObjectStackProtocolImplementation.resetEnvWritableCache();
173+
resetEnvWritableMetadataTypes();
174+
});
175+
176+
/** Installs a writable package through the package door (the pair as its ensure door writes it). */
177+
async function install(protocol: ObjectStackProtocolImplementation, id: string): Promise<void> {
178+
await (protocol as any).installPackage({
179+
manifest: {
180+
id, name: id.split('.').join('-'), version: '0.1.0', type: 'app',
181+
...(id === PAIR
182+
? { namespace: 'showcase_custom', dependencies: { [BASE]: '^1' } }
183+
: { dependencies: { [BASE]: '*' } }),
184+
},
185+
});
186+
}
187+
188+
/** A draft save naming the package, then the per-item publish naming it and the member. */
189+
async function publishInto(
190+
protocol: ObjectStackProtocolImplementation, packageId: string, name: string, locale: string, subject: string,
191+
extra: Record<string, unknown> = {},
192+
): Promise<void> {
193+
const item = { ...template(name, locale, subject), ...extra };
194+
await protocol.saveMetaItem({ type: TYPE, name, item, mode: 'draft', packageId } as any);
195+
await protocol.publishMetaItem({ type: TYPE, name, packageId, member: locale } as any);
196+
}
197+
198+
/** The by-name read: `[subject, locale, _packageId]`, or `404` when nothing is served. */
199+
const byName = async (protocol: ObjectStackProtocolImplementation, name: string, member?: string, packageId?: string) => {
200+
try {
201+
const res: any = await protocol.getMetaItem({ type: TYPE, name, ...(member ? { member } : {}), ...(packageId ? { packageId } : {}) });
202+
const item = res?.item;
203+
if (item === undefined || item === null) return 404;
204+
return [item.subject, item.locale, item._packageId];
205+
} catch (error: any) {
206+
if (error?.status === 404) return 404;
207+
throw error;
208+
}
209+
};
210+
const rowsOf = (items: any[], name: string) => items
211+
.filter((i) => i?.name === name)
212+
.map((i) => [i.locale, i._packageId, i.subject])
213+
.sort((a, b) => String(a[0]).localeCompare(String(b[0])));
214+
/** A list's members of `name`, as `[locale, _packageId, subject]` by locale. */
215+
const listed = async (protocol: ObjectStackProtocolImplementation, name: string, packageId?: string) =>
216+
rowsOf(((await protocol.getMetaItems({ type: TYPE, ...(packageId ? { packageId } : {}) })) as any).items, name);
217+
const executing = async (protocol: ObjectStackProtocolImplementation, name: string) =>
218+
rowsOf(((await protocol.getMetaItemsForExecution({ type: TYPE })) as any).items, name);
219+
220+
const BASE_EN = ['en-US', BASE, 'Base EN'];
221+
const PAIR_FR = ['fr-FR', PAIR, 'Pair FR'];
222+
223+
describe('[#28802] a bundle member on the base\'s address, at member grain', () => {
224+
it('the pair\'s own added member is served by the by-name reads and listed by the base\'s lists and the executing list', async () => {
225+
const { protocol } = await boot();
226+
await install(protocol, PAIR);
227+
await publishInto(protocol, PAIR, NAME, 'fr-FR', 'Pair FR');
228+
229+
expect(await byName(protocol, NAME, 'fr-FR', BASE)).toEqual(['Pair FR', 'fr-FR', PAIR]);
230+
expect(await byName(protocol, NAME, 'fr-FR')).toEqual(['Pair FR', 'fr-FR', PAIR]);
231+
expect(await listed(protocol, NAME)).toEqual([BASE_EN, PAIR_FR]);
232+
expect(await listed(protocol, NAME, BASE)).toEqual([BASE_EN, PAIR_FR]);
233+
expect(await executing(protocol, NAME)).toEqual([BASE_EN, PAIR_FR]);
234+
// Unchanged: the pair's own address, and the base's member on the base's address.
235+
expect(await listed(protocol, NAME, PAIR)).toEqual([PAIR_FR]);
236+
expect(await byName(protocol, NAME, 'fr-FR', PAIR)).toEqual(['Pair FR', 'fr-FR', PAIR]);
237+
expect(await byName(protocol, NAME, 'en-US', BASE)).toEqual(['Base EN', 'en-US', BASE]);
238+
});
239+
240+
it('a dependent\'s added member is served under the dependent only; the base\'s address answers 404 for it', async () => {
241+
const { protocol } = await boot();
242+
await install(protocol, DEPENDENT);
243+
await publishInto(protocol, DEPENDENT, NAME, 'fr-FR', 'Dependent FR');
244+
245+
expect(await byName(protocol, NAME, 'fr-FR', DEPENDENT)).toEqual(['Dependent FR', 'fr-FR', DEPENDENT]);
246+
expect(await listed(protocol, NAME, DEPENDENT)).toEqual([['fr-FR', DEPENDENT, 'Dependent FR']]);
247+
expect(await byName(protocol, NAME, 'fr-FR', BASE)).toBe(404);
248+
expect(await byName(protocol, NAME, 'fr-FR')).toBe(404);
249+
expect(await listed(protocol, NAME)).toEqual([BASE_EN]);
250+
expect(await listed(protocol, NAME, BASE)).toEqual([BASE_EN]);
251+
expect(await executing(protocol, NAME)).toEqual([BASE_EN]);
252+
});
253+
254+
it('with a dependent\'s member at the same locale, the base\'s address still serves the pair\'s', async () => {
255+
const { protocol } = await boot();
256+
await install(protocol, PAIR);
257+
await install(protocol, DEPENDENT);
258+
await publishInto(protocol, PAIR, NAME, 'fr-FR', 'Pair FR');
259+
await publishInto(protocol, DEPENDENT, NAME, 'fr-FR', 'Dependent FR');
260+
261+
expect(await byName(protocol, NAME, 'fr-FR', BASE)).toEqual(['Pair FR', 'fr-FR', PAIR]);
262+
expect(await byName(protocol, NAME, 'fr-FR')).toEqual(['Pair FR', 'fr-FR', PAIR]);
263+
expect(await byName(protocol, NAME, 'fr-FR', DEPENDENT)).toEqual(['Dependent FR', 'fr-FR', DEPENDENT]);
264+
expect(await listed(protocol, NAME)).toEqual([BASE_EN, PAIR_FR]);
265+
expect(await executing(protocol, NAME)).toEqual([BASE_EN, PAIR_FR]);
266+
});
267+
268+
it('a read naming no member of a bundle with no canonical member serves the base\'s member, not a dependent\'s canonical one', async () => {
269+
const { protocol } = await boot();
270+
await install(protocol, DEPENDENT);
271+
await publishInto(protocol, DEPENDENT, FR_ONLY, 'en-US', 'Dependent late EN');
272+
273+
expect(await byName(protocol, FR_ONLY, undefined, BASE)).toEqual(['Base late FR', 'fr-FR', BASE]);
274+
expect(await byName(protocol, FR_ONLY)).toEqual(['Base late FR', 'fr-FR', BASE]);
275+
expect(await byName(protocol, FR_ONLY, 'en-US', BASE)).toBe(404);
276+
expect(await byName(protocol, FR_ONLY, 'en-US', DEPENDENT)).toEqual(['Dependent late EN', 'en-US', DEPENDENT]);
277+
});
278+
279+
it('control: the pair\'s declared override of the base\'s member is served as the base\'s; the pair\'s own member beside it too', async () => {
280+
const { protocol } = await boot();
281+
await install(protocol, PAIR);
282+
await publishInto(protocol, PAIR, NAME, 'en-US', 'Override EN', { overrides: { package: BASE, basedOn: '1.0.0' } });
283+
await publishInto(protocol, PAIR, NAME, 'fr-FR', 'Pair FR');
284+
285+
expect(await byName(protocol, NAME, 'en-US', BASE)).toEqual(['Override EN', 'en-US', BASE]);
286+
expect(await byName(protocol, NAME, 'en-US')).toEqual(['Override EN', 'en-US', BASE]);
287+
expect(await listed(protocol, NAME)).toEqual([['en-US', BASE, 'Override EN'], PAIR_FR]);
288+
expect(await listed(protocol, NAME, BASE)).toEqual([['en-US', BASE, 'Override EN'], PAIR_FR]);
289+
expect(await executing(protocol, NAME)).toEqual([['en-US', BASE, 'Override EN'], PAIR_FR]);
290+
});
291+
});

0 commit comments

Comments
 (0)