Skip to content

Commit 8cc4d7a

Browse files
committed
fix(meta): the layered view naming no package refuses a name two packages hold, as the package-less writes do
Claude-Session: https://claude.ai/code/session_01FEkQ5o95tvF7A7y85W37iR Co-authored-by: Claude <noreply@anthropic.com>
1 parent ad08707 commit 8cc4d7a

7 files changed

Lines changed: 516 additions & 6 deletions

File tree

Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#28337, ADR-0048] `packagelessLayeredReadRefusal`: the layered view's door
5+
* refusal for a name two or more packages hold, asked with no package. It is
6+
* the refusal the package-less save and delete answer for the same rows
7+
* (`packagelessAddressAmbiguityRefusal`, `409 RESOURCE_CONFLICT`, the holders
8+
* sorted and the `?package=` prescription), over the same resolution
9+
* (`packagelessAddress` at `active`).
10+
*
11+
* The layered read itself is unchanged: its in-process resolution readers
12+
* (the security catalog echo, the packaged-permission-set lock gate,
13+
* `/published`) read a name's layers with no package and keep the answer they
14+
* had. The door asks the judge (`createMetaLayeredAnswer` in `@objectstack/rest`).
15+
*/
16+
17+
import { describe, expect, it } from 'vitest';
18+
import { assertEngineDeleteDispatch, assertEngineFindOnePredicate, assertEngineUpdateDispatch } from '@objectstack/metadata-core';
19+
import { ObjectStackProtocolImplementation } from './protocol.js';
20+
21+
const PKG_A = 'app.alpha_demo';
22+
const PKG_B = 'app.beta_demo';
23+
24+
type Row = Record<string, any>;
25+
26+
const rowKey = (w: Row) =>
27+
[w.type, w.name, w.organization_id ?? '', w.package_id ?? '', w.state ?? 'active'].join('|');
28+
29+
const whereValueMatches = (actual: unknown, want: unknown): boolean =>
30+
want !== null && typeof want === 'object' && Array.isArray((want as { $in?: unknown }).$in)
31+
? (want as { $in: unknown[] }).$in.includes(actual)
32+
: actual === want;
33+
34+
const matchesWhere = (row: Row, where: Row) =>
35+
Object.entries(where).every(([k, v]) => {
36+
if (k.startsWith('$')) throw new Error(`fake driver: unsupported operator ${k}`);
37+
if (v === null) return row[k] === null || row[k] === undefined;
38+
return whereValueMatches(row[k], v);
39+
});
40+
41+
/** An in-memory `sys_metadata` behind the REAL protocol, with no registry items. */
42+
function makeProtocol() {
43+
const rows = new Map<string, Row>();
44+
let nextId = 0;
45+
const findRow = (w: Row) => {
46+
for (const [k, r] of rows) if (matchesWhere(r, w)) return { key: k, row: r };
47+
return null;
48+
};
49+
const registry: any = {
50+
getItem: () => undefined,
51+
getArtifactItem: () => undefined,
52+
listItems: () => [],
53+
getObject: () => undefined,
54+
isPackageDisabled: () => false,
55+
isObjectPackageDisabled: () => false,
56+
getAllPackages: () => [{ manifest: { id: PKG_A } }, { manifest: { id: PKG_B } }],
57+
getPackage: (id: string) => ({ manifest: { id } }),
58+
};
59+
const engine: any = {
60+
registry,
61+
async findOne(table: string, o: { where: Row }) {
62+
assertEngineFindOnePredicate(table, o);
63+
if (table !== 'sys_metadata') return null;
64+
return findRow(o.where)?.row ?? null;
65+
},
66+
async find(table: string, o: { where: Row; limit?: number }) {
67+
if (table !== 'sys_metadata') return [];
68+
const matched = Array.from(rows.values()).filter((r) => matchesWhere(r, o.where));
69+
return typeof o?.limit === 'number' ? matched.slice(0, o.limit) : matched;
70+
},
71+
async insert(table: string, data: Row) {
72+
if (table !== 'sys_metadata') return { id: `rec_${++nextId}` };
73+
const row = { id: `r_${++nextId}`, ...data };
74+
rows.set(rowKey(data), row);
75+
return { id: row.id };
76+
},
77+
async update(table: string, data: Row, o: { where: Row }) {
78+
assertEngineUpdateDispatch(data, o);
79+
if (table !== 'sys_metadata') return { id: null };
80+
const found = findRow(o.where);
81+
if (!found) return { id: null };
82+
const merged = { ...found.row, ...data };
83+
rows.delete(found.key);
84+
rows.set(rowKey(merged), merged);
85+
return { id: merged.id };
86+
},
87+
async delete(table: string, o?: Row) {
88+
assertEngineDeleteDispatch(o);
89+
if (table !== 'sys_metadata') return { deleted: 0 };
90+
const found = findRow((o?.where ?? {}) as Row);
91+
if (!found) return { deleted: 0 };
92+
rows.delete(found.key);
93+
return { deleted: 1 };
94+
},
95+
async syncObjectSchema() { /* no physical storage in this double */ },
96+
};
97+
return new ObjectStackProtocolImplementation(engine, undefined, 'env_test');
98+
}
99+
100+
/** Store one dashboard row per package named (`null`: the package-unbound row). */
101+
async function store(protocol: ObjectStackProtocolImplementation, name: string, packages: Array<string | null>) {
102+
for (const pkg of packages) {
103+
await protocol.saveMetaItem({
104+
type: 'dashboard', name, item: { name, label: `${pkg ?? 'local'} copy`, widgets: [] },
105+
...(pkg ? { packageId: pkg } : {}),
106+
} as any);
107+
}
108+
}
109+
110+
/** What a rejected promise threw. */
111+
const thrown = async (p: Promise<unknown>): Promise<any> => {
112+
try {
113+
await p;
114+
} catch (e) {
115+
return e;
116+
}
117+
throw new Error('expected a refusal; the call resolved');
118+
};
119+
120+
describe('[#28337] packagelessLayeredReadRefusal', () => {
121+
it('a name two packages hold: the package-less save\'s refusal, worded for the layered read', async () => {
122+
const protocol = makeProtocol();
123+
await store(protocol, 'twin_dash', [PKG_B, PKG_A]);
124+
const refusal = await protocol.packagelessLayeredReadRefusal({ type: 'dashboard', name: 'twin_dash' });
125+
const saveRefusal = await thrown(protocol.saveMetaItem({
126+
type: 'dashboard', name: 'twin_dash', item: { name: 'twin_dash', label: 'edited', widgets: [] },
127+
} as any));
128+
expect(refusal).toBeInstanceOf(Error);
129+
expect({ code: refusal!.code, status: refusal!.status }).toEqual({ code: saveRefusal.code, status: saveRefusal.status });
130+
expect({ code: refusal!.code, status: refusal!.status }).toEqual({ code: 'RESOURCE_CONFLICT', status: 409 });
131+
expect(refusal!.message).toBe(
132+
'Name the package this layered read is for, then send it again: on the REST door add ?package= with the '
133+
+ 'package id, in process pass packageId. Nothing was served. dashboard \'twin_dash\' belongs to 2 packages '
134+
+ `('${PKG_A}', '${PKG_B}'), and a layered read that names none has no single row to show.`,
135+
);
136+
// The holder list is the save's, sorted.
137+
expect(saveRefusal.message).toContain(`('${PKG_A}', '${PKG_B}')`);
138+
// The plural URL spelling is the same item.
139+
expect((await protocol.packagelessLayeredReadRefusal({ type: 'dashboards', name: 'twin_dash' }))?.message)
140+
.toBe(refusal!.message);
141+
});
142+
143+
it('no refusal where the package-less writes take an address: one package, the package-unbound row beside it, or none', async () => {
144+
const protocol = makeProtocol();
145+
await store(protocol, 'solo_dash', [PKG_A]);
146+
await store(protocol, 'local_beside', [PKG_A, null]);
147+
await store(protocol, 'local_dash', [null]);
148+
for (const name of ['solo_dash', 'local_beside', 'local_dash', 'no_such_dash']) {
149+
expect(await protocol.packagelessLayeredReadRefusal({ type: 'dashboard', name }), name).toBeUndefined();
150+
}
151+
});
152+
153+
it('the layered read itself still serves its in-process readers a name two packages hold', async () => {
154+
const protocol = makeProtocol();
155+
await store(protocol, 'twin_dash', [PKG_A, PKG_B]);
156+
const layered = await protocol.getMetaItemLayered({ type: 'dashboard', name: 'twin_dash' });
157+
expect(layered.overlay).toMatchObject({ name: 'twin_dash' });
158+
for (const pkg of [PKG_A, PKG_B]) {
159+
const scoped = await protocol.getMetaItemLayered({ type: 'dashboard', name: 'twin_dash', packageId: pkg });
160+
expect(scoped.overlay).toMatchObject({ name: 'twin_dash', label: `${pkg} copy` });
161+
}
162+
});
163+
});

‎packages/metadata-protocol/src/protocol.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11468,6 +11468,45 @@ export class ObjectStackProtocolImplementation implements
1146811468
};
1146911469
}
1147011470

11471+
/**
11472+
* [#28337, ADR-0048] The layered view's door refusal: what
11473+
* `GET /meta/:type/:name/layers` (and the deprecated `?layers=true`)
11474+
* answers when it names no package and the item's ACTIVE rows are bound
11475+
* to two or more packages. The refusal the package-less save and delete
11476+
* answer for the same rows ({@link packagelessAddressAmbiguityRefusal},
11477+
* `409 RESOURCE_CONFLICT`, the holders sorted and the `?package=`
11478+
* prescription), asked of the same resolution
11479+
* ({@link packagelessAddress} at `active`, at the addressed bundle member,
11480+
* read in full): one answer to one ambiguity. `undefined` for a name one
11481+
* package holds, none does, or only the package-unbound row does, and for
11482+
* every request that names a package (the caller asks only without one).
11483+
*
11484+
* Before, {@link getMetaItemLayered} naming no package took its overlay
11485+
* from {@link packagelessReadAddress}, which answers no package for such
11486+
* a name, so the layer was the first row a package-agnostic lookup met:
11487+
* one holder's stack, picked silently, while the Studio editor that loads
11488+
* this view and the save it then sends were refused for the same name.
11489+
*
11490+
* Asked by the DOOR (the shared layered chain in `@objectstack/rest`,
11491+
* `createMetaLayeredAnswer`), ⛔ never inside {@link getMetaItemLayered}:
11492+
* its in-process resolution readers (the security catalog echo, the
11493+
* packaged-permission-set lock gate, `/published`) read the layers of a
11494+
* name with no package and keep the answer they had.
11495+
*/
11496+
async packagelessLayeredReadRefusal(request: {
11497+
type: string;
11498+
name: string;
11499+
/** The bundle member the layered read addresses ({@link resolveBundleMemberSelector}); omitted, the canonical one. */
11500+
member?: string;
11501+
}): Promise<(Error & { code: 'RESOURCE_CONFLICT'; status: 409 }) | undefined> {
11502+
const { type, name } = canonicalizeMetaRequestType(request);
11503+
const member = resolveBundleMemberSelector(type, request.member);
11504+
const address = await this.packagelessAddress(PLURAL_TO_SINGULAR[type] ?? type, name, member);
11505+
return address.candidates.length > 1
11506+
? packagelessAddressAmbiguityRefusal('layered read', type, name, address.candidates)
11507+
: undefined;
11508+
}
11509+
1147111510
/**
1147211511
* Phase 3a-layered-get: return the 3 layers of a metadata item
1147311512
* separately — `code` (artifact-loaded baseline), `overlay` (per-org

‎packages/metadata-protocol/src/sys-metadata-repository.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -563,7 +563,12 @@ export function versionNotFoundError(
563563
* the same request in different words. [#23495] And the per-item draft
564564
* publish (`publish`) and the draft discard (`delete`) that name no package,
565565
* whose draft address the protocol resolves as the draft save's
566-
* (`ObjectStackProtocolImplementation.packagelessDraftAddress`).
566+
* (`ObjectStackProtocolImplementation.packagelessDraftAddress`). [#28337] And
567+
* the layered view naming no package (`layered read`: `GET /meta/:type/:name/layers`
568+
* and the deprecated `?layers=true`), which served one holder's overlay,
569+
* picked silently, for the address these writes refuse: its door asks
570+
* `ObjectStackProtocolImplementation.packagelessLayeredReadRefusal`, which
571+
* answers this refusal over the same rows the direct save reads.
567572
*
568573
* A `sys_metadata` row is keyed `(org, type, name, package_id)`, so such a
569574
* write has no one row to write or remove. Before this refusal the save wrote
@@ -590,7 +595,7 @@ export function versionNotFoundError(
590595
* predicate.
591596
*/
592597
export function packagelessAddressAmbiguityRefusal(
593-
verb: 'save' | 'delete' | 'publish',
598+
verb: 'save' | 'delete' | 'publish' | 'layered read',
594599
type: string,
595600
name: string,
596601
packageIds: readonly string[],
@@ -601,7 +606,9 @@ export function packagelessAddressAmbiguityRefusal(
601606
? ['Nothing was written.', 'no single row to write']
602607
: verb === 'publish'
603608
? ['Nothing was published.', 'no single draft to promote']
604-
: ['Nothing was deleted.', 'no single row to remove'];
609+
: verb === 'layered read'
610+
? ['Nothing was served.', 'no single row to show']
611+
: ['Nothing was deleted.', 'no single row to remove'];
605612
const err = new Error(
606613
`Name the package this ${verb} is for, then send it again: on the REST door add ?package= with the package id, `
607614
+ `in process pass packageId. ${nothing} ${type} '${name}' belongs to ${packageIds.length} packages `

‎packages/rest/src/meta-item-read-gate.ts‎

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,20 @@ export interface MetaItemReadGateSources extends MetaReadGateAudienceSources, Me
197197
* withheld".
198198
*/
199199
isItemOfDisabledPackage?(item: { type: string; name: string; packageId?: string }): Promise<boolean>;
200+
/**
201+
* [#28337, ADR-0048] The refusal of a layered read that names NO package,
202+
* of a name whose active rows two or more packages hold: the protocol's
203+
* `packagelessLayeredReadRefusal`, which answers the refusal the
204+
* package-less save and delete answer for the same rows (`409
205+
* RESOURCE_CONFLICT`, the holders and the `?package=` prescription), or
206+
* `undefined` when one package or none holds the name.
207+
*
208+
* Read by the layered chain ({@link createMetaLayeredAnswer}) only, and
209+
* only for a request with no `?package=`. Absent (a protocol without the
210+
* judge) refuses nothing: the answer before #28337. A REJECTION is a fault
211+
* and propagates.
212+
*/
213+
packagelessLayeredReadRefusal?(item: { type: string; name: string; member?: string }): Promise<Error | undefined>;
200214
}
201215

202216
// ── The caller's organization ─────────────────────────────────────────────────
@@ -3803,6 +3817,12 @@ export interface MetaLayeredRequest {
38033817
* owner step 1b asks about is the one this scope resolves.
38043818
*/
38053819
readonly packageId?: string;
3820+
/**
3821+
* [#28337] The bundle member selector the transport read the layers at
3822+
* (`?member=`, `metaMemberSelector`), absent for the canonical member: the
3823+
* address step 1c asks about is the member the layers are of.
3824+
*/
3825+
readonly member?: string;
38063826
/**
38073827
* [ADR-0106 D2/D3] The caller's field-visibility posture for this item,
38083828
* resolved by the transport BEFORE the read, the not-applicable passthrough
@@ -3883,6 +3903,20 @@ export type MetaLayeredAnswer =
38833903
* protocol's layered read keeps serving every layer, because
38843904
* its resolution readers (the security catalog echo, the
38853905
* packaged-permission-set lock gate) need them: the door answers here.
3906+
* 1c. [#28337, ADR-0048] A name two or more packages hold, read naming no
3907+
* package, is refused with the package-less writes' own refusal — `409
3908+
* RESOURCE_CONFLICT`, naming the holders, with the `?package=`
3909+
* prescription — asked of
3910+
* {@link MetaItemReadGateSources.packagelessLayeredReadRefusal} (the
3911+
* protocol's judge over the rows the save and the delete read) and THROWN,
3912+
* so each transport answers it through the catch its own save door answers
3913+
* that refusal through: one envelope per transport for one ambiguity. The
3914+
* protocol's layered read named no package picked one holder's stack
3915+
* silently. BEFORE the gate, so the answer never depends on which holder
3916+
* that pick met; for the same reason the read refuses, exactly where the
3917+
* writes refuse, on every type. Same producer rule as 1b: the protocol's
3918+
* layered read keeps serving its resolution readers; the door answers
3919+
* here.
38863920
* 2. [#20156] THE per-caller gate on EVERY present layer, `effective` first
38873921
* (it is what the plain read serves, so its refusal is the plain read's
38883922
* own), under {@link STORED_VERSION_DOOR_POLICY}: per-caller arms only
@@ -3908,7 +3942,7 @@ export function createMetaLayeredAnswer(
39083942
sources: MetaItemReadGateSources,
39093943
request: MetaLayeredRequest,
39103944
): (layered: unknown) => Promise<MetaLayeredAnswer> {
3911-
const { metaType, name, packageId, maskPosture } = request;
3945+
const { metaType, name, packageId, member, maskPosture } = request;
39123946
return async (raw) => {
39133947
const layered = raw as Record<string, unknown> | null | undefined;
39143948
const present = META_ITEM_LAYERS.filter((layer) => layered?.[layer] != null);
@@ -3924,6 +3958,15 @@ export function createMetaLayeredAnswer(
39243958
return { kind: 'refuse', refusal: { reason: 'absent' } };
39253959
}
39263960

3961+
// 1c. [#28337] A name several packages hold, naming none: the
3962+
// package-less writes' refusal, thrown to the transport's catch.
3963+
if (!packageId) {
3964+
const ambiguity = await sources.packagelessLayeredReadRefusal?.({
3965+
type: metaType, name, ...(member !== undefined ? { member } : {}),
3966+
});
3967+
if (ambiguity) throw ambiguity;
3968+
}
3969+
39273970
// 2. [#20156] THE per-caller gate, on every present layer.
39283971
const served = new Map<string, unknown>();
39293972
{

‎packages/rest/src/rest-server.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,14 @@ import { sendError as sendEnvelopeError } from '@objectstack/types';
279279
export type RestProtocol = DataProtocol & MetadataProtocol & {
280280
getMetaItemForExecution?: MetadataProtocol['getMetaItem'];
281281
getMetaItemsForExecution?: MetadataProtocol['getMetaItems'];
282+
/**
283+
* [#28337] The layered view's door refusal for a name several packages
284+
* hold, read naming none (metadata-protocol's
285+
* `packagelessLayeredReadRefusal`), equally optional: the layered chain
286+
* asks it ({@link RestServer.metaItemReadGateSources}); a protocol without
287+
* it refuses nothing, as before.
288+
*/
289+
packagelessLayeredReadRefusal?(request: { type: string; name: string; member?: string }): Promise<Error | undefined>;
282290
};
283291

284292
// [#23050 slice 10] `TransportScopedMetaRequest`, the meta doors' request envelope, moved to
@@ -3634,6 +3642,9 @@ export class RestServer {
36343642
* reached through {@link wiredEngineOrLoud}: none wired withholds nothing,
36353643
* as before; one that cannot be resolved is the loud outage, never "not
36363644
* withheld".
3645+
*
3646+
* [#28337] `packagelessLayeredReadRefusal`, the layered chain's step 1c:
3647+
* the protocol's own judge, handed through when it has one.
36373648
*/
36383649
private metaItemReadGateSources(
36393650
environmentId: string | undefined,
@@ -3663,6 +3674,9 @@ export class RestServer {
36633674
const envelope = await p.getMetaItem(itemRequest) as { item?: unknown; packageId?: unknown } | undefined;
36643675
return envelope?.item == null && registry.isPackageDisabled(envelope?.packageId) === true;
36653676
},
3677+
...(typeof p.packagelessLayeredReadRefusal === 'function'
3678+
? { packagelessLayeredReadRefusal: (item: { type: string; name: string; member?: string }) => p.packagelessLayeredReadRefusal!(item) }
3679+
: {}),
36663680
};
36673681
}
36683682

@@ -4337,6 +4351,8 @@ export class RestServer {
43374351
metaType: RestServer.metaTypeSingular(req.params.type),
43384352
name: req.params.name,
43394353
...(layeredPackageId ? { packageId: layeredPackageId } : {}),
4354+
// [#28337] The member the layers were read at, for step 1c.
4355+
...metaReadGate.metaMemberSelector(req.query),
43404356
maskPosture,
43414357
},
43424358
)(layered);

0 commit comments

Comments
 (0)