diff --git a/.changeset/34144-bare-save-holder-judgment.md b/.changeset/34144-bare-save-holder-judgment.md new file mode 100644 index 00000000000..3d85a3f6c0c --- /dev/null +++ b/.changeset/34144-bare-save-holder-judgment.md @@ -0,0 +1,31 @@ +--- +'@objectstack/metadata-protocol': patch +--- + +fix(metadata-protocol)!: a bare save or delete answers the holders the bare read counts: a name two enabled packages hold is refused naming both, and a name only disabled packages hold is refused naming none (ADR-0150 D3/D5) + +Clause-②: no (narrowing) +Metadata-protocol: none + + + +**BREAKING** for a writer that saves or deletes a name without naming a package (`PUT` or `DELETE /meta/:type/:name` with no `?package=`, or `saveMetaItem` / `deleteMetaItem` with no `packageId`), in two states. The bare write used to take its address from the stored rows alone, while the bare read counts the name's holders. It now counts them as the read does (ADR-0150 D3/D5, red line 2: ambiguity is reported, never guessed). Every refusal is the existing `409 RESOURCE_CONFLICT` with the `?package=` remedy; there is no new code. Measured on a booted kernel through the runtime dispatcher and `RestServer`, in both registration orders. + +**Two or more enabled packages hold the name.** The bare read refuses 409 naming them. + +- A publish-mode bare save used to answer 200. Over no stored row it wrote a package-unbound row beside both packages; over one package's row it updated that row. It is now refused naming both packages, and nothing is written. Over a row of each it was refused already, and still is. +- A draft-mode bare save (`?mode=draft`) used to write a package-unbound draft, or the one package's draft. It is now refused the same way. +- A bare delete used to remove the one package's row. It is now refused the same way, and the row stays. +- A bare delete or bare draft discard (`?state=draft`) over no stored row used to answer the no-op receipt (`success: true, reset: false`). It is now refused the same way. + +**Every package that holds the name is disabled.** A disabled package holds no name (ruling A on #34144 and the registry's served-holder rule, #32183), so the bare read answers 404. The bare write is now refused naming no package (ruling A): + +- A publish-mode bare save of a name whose only holder D is disabled used to answer 200. Over D's row alone it updated D's row; over no stored row it wrote a package-unbound row that every read then withheld. It is now refused, and nothing is written. +- A bare save of a bundled name (an `email_template`) whose every holder is disabled, at a member the holder never ships, used to answer 200 and store a package-unbound row that the by-name read and both lists withheld until the package was enabled again. It is now refused, and nothing is stored. This replaces the "accepted and kept" save described in this release's note on reads of a disabled package's customization: FROM `success: true` with the row stored and hidden, TO `409 RESOURCE_CONFLICT` with the `?package=` remedy, naming no package, no row stored. The line of `.changeset/33385-disabled-holders-env-404.md` that says this save "is accepted and kept, as before" is superseded by this note: while every holder is disabled, the save is refused and nothing is stored. A delete of such a row while the package is disabled still removes it, a save at a member the package ships is still refused `403 NOT_OVERRIDABLE` where the package door refuses it, and once the package is enabled again the same save is kept. +- A draft-mode bare save (`?mode=draft`) of such a name used to write a package-unbound draft. It is now refused the same way. +- A bare delete of such a name used to remove D's row. It is now refused, and D's row stays. +- A bare delete or bare draft discard (`?state=draft`) of such a name over no stored row used to answer the no-op receipt (`success: true, reset: false`). It is now refused the same way. + +**Not moved.** A write naming the package (`?package=`, `packageId`) answers as before. So do a name one enabled package holds, a name an enabled and a disabled package both hold, a name no package holds (the environment's own item), and a package-unbound row stored at the address: the save edits that row and the delete removes it, as before. Once a disabled package is enabled again, its bare writes answer as before. A type the registry does not read by package (`action`, `doc`, whose bare reads refuse through their own judges) is not judged here and answers as before. A bare save in these two states that a later gate already refused (an invalid body, a read-only inherited package) is still refused, now with this `409` first: refused to refused. + +**No migration.** No schema key or stored row changes. To write one holder's item, name its package; to write a disabled package's item, name it or enable it again. diff --git a/packages/metadata-protocol/src/protocol-diff-delete-load.ts b/packages/metadata-protocol/src/protocol-diff-delete-load.ts index 1128f18ab99..9893064fbf6 100644 --- a/packages/metadata-protocol/src/protocol-diff-delete-load.ts +++ b/packages/metadata-protocol/src/protocol-diff-delete-load.ts @@ -66,6 +66,7 @@ import { withRefusalAudit } from './protocol-refusal-audit.js'; import { captureStoredExpressionChange, fillStoredExpressionChange } from './protocol-stored-expression-fill.js'; import type { RuntimeAuthoringIssue } from './runtime-authoring-gate.js'; import type { ProtocolHost } from './protocol-host.js'; +import { packagelessHolderRefusal } from './protocol-save.js'; /** * [#33308] The row slot a `sys_metadata` row is: its bound package, or `null` @@ -730,6 +731,23 @@ export class ProtocolDiffDeleteLoadFacet { ); throw addressRefusal; } + // [ADR-0150 D3/D5, red line 2, ruling A] …and the holders the + // read naming no package counts, as the save door asks them + // ({@link packagelessHolderRefusal}): two or more enabled holders + // are refused naming them, and a name only disabled packages hold + // is refused naming none, never one row removed. Over no stored + // row too (the delete and the draft discard answered the no-op + // receipt). A package-unbound row at the address is the + // environment's own, and its removal is left as it was. + if (request.packageId == null) { + const holderRefusal = packagelessHolderRefusal( + host, 'delete', request.type, singularTypeForRepo, request.name, member, rowsAtAddress, + ); + if (holderRefusal) { + addressRefusal = holderRefusal; + throw addressRefusal; + } + } const packageId: string | null = request.packageId ?? (draftAddress !== undefined ? draftAddress.key : rowsAtAddress.packageId); // Probe first — "no overlay exists" is a success/no-op, not diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index aefdb76aede..8578a6d3e3f 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -88,6 +88,9 @@ import { saveRegistryQuestion } from './registry-question.js'; import { OBJECT_EXTENSION_TYPE, registrableObjectExtension } from './protocol-object-extension-item.js'; import { servedAddressJudgment } from './protocol-meta-item-face.js'; import { packagelessContentPackage, shippingPackageIds } from './protocol-environment-rows.js'; +import { installedManifestsOfEngine } from './installed-manifests.js'; +import { packageScopedRefusalOf } from './protocol-meta-item-reads.js'; +import { pairsOf } from '@objectstack/metadata-core'; import { BatchRowHealError, canJudgeBatchObjects, isBatchObjectType, readActiveBatchRow, settleBatchObjectRows, undoBatchRowWrite, undoOutcomeForLog, type WrittenBatchRow } from './batch-object-registration.js'; export class ProtocolSaveFacet { @@ -826,6 +829,15 @@ export class ProtocolSaveFacet { if (address.candidates.length > 1) { throw packagelessAddressAmbiguityRefusal('save', request.type, request.name, address.candidates); } + // [ADR-0150 D3/D5, red line 2, ruling A] …and the holders the + // read naming no package counts ({@link packagelessHolderRefusal}): + // two or more enabled holders are refused naming them, and a name + // only disabled packages hold is refused naming none, never + // written at one row's package or as a new package-unbound row. + const holderRefusal = packagelessHolderRefusal( + host, 'save', request.type, writeType, request.name, itemDiscriminator(writeType, request.item), address, + ); + if (holderRefusal) throw holderRefusal; if (address.packageId !== null) request = { ...request, packageId: address.packageId }; } } @@ -846,6 +858,21 @@ export class ProtocolSaveFacet { singularType, request.name, itemDiscriminator(singularType, request.item), ) : undefined; + // [ADR-0150 D3/D5, red line 2, ruling A] The draft save naming no + // package answers the holders as the publish-mode save above does + // ({@link packagelessHolderRefusal}), judged over the item's active rows + // and its drafts: the draft address alone took the one package with a + // row, or a new package-unbound draft. An ambiguous draft address is + // left to the repository's `409`, as before. + if (draftAddress !== undefined && draftAddress.kind !== 'ambiguous') { + const member = itemDiscriminator(singularType, request.item); + const active = await host.packagelessAddress(singularType, request.name, member, 'active'); + const holderRefusal = packagelessHolderRefusal(host, 'save', request.type, singularType, request.name, member, { + candidates: [...new Set([...active.candidates, ...draftAddress.drafts.candidates])], + unbound: active.unbound || draftAddress.drafts.unbound, + }); + if (holderRefusal) throw holderRefusal; + } // [#26921] THE NAMED-BASE RULE for the binding a save naming no // package INHERITS: the package its address gives (the resolved @@ -2835,9 +2862,10 @@ export class ProtocolSaveFacet { /** * [#32605, epic ruling 6781691009 on #32354, ADR-0150 D3/D4/D5] THE WRITE * ADDRESS of a publish-mode save naming no package, for a name a DISABLED - * package also holds: the address the read naming no package serves, so the - * save writes exactly the row the next read answers. A disabled package holds - * nothing an address reaches, so it is never the address and never named. + * package also holds: in the cells below, the address the read naming no + * package serves, so the save writes the row the next read answers. A + * disabled package holds nothing an address reaches, so it is never the + * address and never named. * * - The read's own judgment first ({@link servedAddressJudgment}, the one * #32183 and #32354 gave the reads): its served holder is the address; its @@ -2850,9 +2878,15 @@ export class ProtocolSaveFacet { * the package-unbound row when one is stored (the save edits it, as the * read serves it), else the one enabled package that ships the name (the * read's content package, {@link packagelessContentPackage}). - * - `undefined` leaves the address to {@link packagelessAddress}, as before: - * no disabled holder, or one only disabled packages hold (no served holder - * to take the write; the save keeps naming that package, as it did). + * - `undefined` leaves the address to {@link packagelessAddress} and + * {@link packagelessHolderRefusal}: no disabled holder, or one only + * disabled packages hold (no served holder to take the write; that judgment + * refuses it naming no package). + * + * Known gap: two or more ENABLED packages hold the name and the stored rows + * are bound to a disabled package and to exactly one of them. The enabled + * bindings above pick that one (the save answers 200) where the read refuses + * `409` naming every enabled holder. A follow-up card is filed. * * Without it the save door counted the disabled holder as a holder: over no * stored row it wrote a package-unbound row (an environment-own item that @@ -2886,3 +2920,110 @@ async function servedPackagelessSaveAddress( const content = packagelessContentPackage({ packageId: null, candidates: [] }, shippers.map((id) => ({ _packageId: id }))); return typeof content === 'string' ? { packageId: content } : undefined; } + +/** + * [ADR-0150 D3, ruling A on the disabled-only name] The refusal of a write + * naming no package of a name every holder of which is disabled. A disabled + * package holds no name, so the read naming no package answers the missing + * name; the write names no package either, and points to the one way to act + * on that package's item. `409 RESOURCE_CONFLICT`, the refusal family of + * {@link packagelessAddressAmbiguityRefusal}, with no new code. + */ +export function disabledHoldersOnlyRefusal( + verb: 'save' | 'delete', + type: string, + name: string, +): Error & { code: 'RESOURCE_CONFLICT'; status: 409 } { + const [nothing, single] = verb === 'save' + ? ['Nothing was written.', 'no row to write'] + : ['Nothing was deleted.', 'no row to remove']; + const err = new Error( + `Name the package this ${verb} is for, then send it again: on the REST door add ?package= with the package id, ` + + `in process pass packageId. ${nothing} ${type} '${name}' is held by no enabled package, and a ${verb} ` + + `that names none has ${single}.`, + ) as Error & { code: 'RESOURCE_CONFLICT'; status: 409 }; + err.code = 'RESOURCE_CONFLICT'; + err.status = 409; + return err; +} + +/** + * [ADR-0150 D3/D5 and red line 2] THE HOLDERS a write naming no package + * counts before it takes its address from the stored rows' bindings + * ({@link packagelessAddress}): the holders the read naming no package + * counts, so the bare save (publish and draft mode), the bare delete and the + * bare draft discard answer as the bare read does in the two states below, + * whether or not a row is stored at the address (over none, the delete and + * the discard are refused too, not answered the no-op receipt). + * Asked after {@link servedPackagelessSaveAddress} (a name an enabled and a + * disabled package both hold) and after the rows' own refusal (two or more + * bindings), so neither answer moves. + * + * - Two or more ENABLED packages hold the name: the package-scoped + * resolver's own refusal (`resolveItem` naming no package, the judgment + * the by-name read asks before any layer), restated as the write's + * refusal naming those packages. The rows' bindings alone picked the one + * package with a row, or wrote a package-unbound row beside both. + * - Every package holding the name is disabled (a registry holder, a code + * shipper or a stored row's binding; a row bound to a disabled holder's + * customization pair is that holder's): {@link disabledHoldersOnlyRefusal}, + * naming no package. The write edited the disabled package's row, or + * stored a row every read then withholds. + * - `undefined` otherwise: no holder, one enabled holder, a package-unbound + * row stored at the address or the environment's own item (ADR-0150 D3 + * (a): the row the write edits), a type the registry does not read by + * package, or a registry without the reads. + * + * Known gap: with an enabled and a disabled holder, the draft save and the + * delete have no {@link servedPackagelessSaveAddress} step and still take + * their address from the rows, and that step's own gap stands for the publish + * save. A follow-up card is filed. + */ +export function packagelessHolderRefusal( + host: Pick, + verb: 'save' | 'delete', + shownType: string, + type: string, + name: string, + member: string | undefined, + address: { readonly candidates: readonly string[]; readonly unbound: boolean }, +): (Error & { code: 'RESOURCE_CONFLICT'; status: 409 }) | undefined { + if (address.unbound) return undefined; + const registry = host.engine?.registry as HolderRegistry | undefined; + if (typeof registry?.readsByPackage !== 'function' || registry.readsByPackage(type) !== true) return undefined; + if (typeof registry.getEnvironmentScopedItem === 'function' && registry.getEnvironmentScopedItem(type, name, member) !== undefined) { + return undefined; + } + if (typeof registry.resolveItem === 'function') { + try { + registry.resolveItem(type, name, null, member); + } catch (error) { + const refusal = packageScopedRefusalOf(error); + if (refusal === undefined) throw error; + const held = refusal.reason === 'ambiguous-in-environment' + ? refusal.candidates.flatMap((candidate) => (candidate.kind === 'package' ? [candidate.packageId] : [])) + : []; + if (held.length > 1) return packagelessAddressAmbiguityRefusal(verb, shownType, name, held); + } + } + if (typeof registry.packageScopedHoldersOf !== 'function' || typeof registry.isPackageDisabled !== 'function') return undefined; + const disabled = (id: string): boolean => registry.isPackageDisabled?.(id) === true; + const known = [...new Set([ + ...(registry.packageScopedHoldersOf(type, name, null, { includeDisabledPackages: true }) ?? []), + ...shippingPackageIds(host.shippedArtifactsOf(type, name)), + ])]; + const installed = installedManifestsOfEngine(host.engine); + const disabledHoldersPair = (id: string): boolean => known.some((holder) => disabled(holder) && pairsOf(holder, installed).includes(id)); + const every = [...new Set([...known, ...address.candidates])]; + if (every.length === 0 || every.some((id) => !disabled(id) && !disabledHoldersPair(id))) return undefined; + return disabledHoldersOnlyRefusal(verb, shownType, name); +} + +/** The registry reads {@link packagelessHolderRefusal} asks, each optional-called. */ +interface HolderRegistry { + readsByPackage?(type: string): boolean; + getEnvironmentScopedItem?(type: string, name: string, member?: string): unknown; + resolveItem?(type: string, name: string, callerPackageId: null, member?: string): unknown; + packageScopedHoldersOf?(type: string, name: string, callerPackageId?: string | null, options?: { includeDisabledPackages?: boolean }): readonly string[] | undefined; + isPackageDisabled?(id: string): boolean; +} diff --git a/packages/objectql/src/disabled-holder-packageless-row-doors.test.ts b/packages/objectql/src/disabled-holder-packageless-row-doors.test.ts index 1ae66494bcf..fbc74535bc8 100644 --- a/packages/objectql/src/disabled-holder-packageless-row-doors.test.ts +++ b/packages/objectql/src/disabled-holder-packageless-row-doors.test.ts @@ -14,9 +14,12 @@ * - S1: the list naming no package and the execution list leave it out too, * whether the row was hydrated at boot or saved after it. * - S3: a package-less save of that member while the package is disabled is - * accepted and kept, and hidden until the package is enabled again; a - * delete removes it. A save at a member the package ships is refused, as - * before. + * refused 409 with the `?package=` remedy, naming no package, and stores + * no row (#34144 ruling A, #34262: a disabled package holds no name, so a + * save naming none has no row to write). Re-enabled, the same save is + * kept. A delete of the stored package-less row removes it while the + * package is disabled, as before. A save at a member the package ships is + * refused, as before. * - S5: while an ENABLED package holds the name through a stored row the * registry has not read, the row is served and listed as on `main`, in * either read order. @@ -188,21 +191,32 @@ describe('[#33401, review#2 S1] the lists leave out the package-less row the by- }); describe('[#33401, review#2 S3] a package-less save and delete while every holder is disabled', () => { - it('a save at a member the package never ships is kept and hidden until re-enable; a delete removes it; a save at a shipped member is refused, as before', async () => { + it('a save at a member the package never ships is refused naming no package and stores no row; re-enabled it is kept; a delete removes it; a save at a shipped member is refused, as before', async () => { const stores: Stores = new Map(); const { engine, protocol } = await boot(stores); engine.registry.disablePackage(PKG); - expect(await protocol.saveMetaItem({ type: 'email_template', name: NAME, item: template('fr-FR', 'SAVED fr') } as any)) - .toMatchObject({ success: true, state: 'active' }); - expect(packagelessRows(stores)).toEqual(['fr-FR']); - // BASE: the read-back served `SAVED fr`. + // FROM (#33995): accepted (`success: true, state: 'active'`), stored + // package-less at `fr-FR`, hidden until the package is enabled again. + // TO (#34144 ruling A, #34262): refused 409 with the `?package=` + // remedy, naming no package, and no row is stored. + const refused: any = await protocol.saveMetaItem({ type: 'email_template', name: NAME, item: template('fr-FR', 'SAVED fr') } as any) + .then(() => undefined, (error: unknown) => error); + expect([refused?.status, refused?.code]).toEqual([409, 'RESOURCE_CONFLICT']); + expect(String(refused?.message)).toContain('?package='); + expect(String(refused?.message)).not.toContain(PKG); + expect(packagelessRows(stores)).toEqual([]); expect(await subjectAt(protocol, 'fr-FR')).toBeUndefined(); expect(await listed(protocol)).toEqual({ list: [], execution: [] }); // CONTROL — unchanged: a shipped member's save naming no package is refused. await expect(protocol.saveMetaItem({ type: 'email_template', name: NAME, item: template('en-US', 'SAVED en') } as any)) .rejects.toMatchObject({ code: 'NOT_OVERRIDABLE', status: 403 }); + // CONTROL — re-enabled: the same save is accepted and kept. engine.registry.enablePackage(PKG); + expect(await protocol.saveMetaItem({ type: 'email_template', name: NAME, item: template('fr-FR', 'SAVED fr') } as any)) + .toMatchObject({ success: true, state: 'active' }); + expect(packagelessRows(stores)).toEqual(['fr-FR']); expect(await subjectAt(protocol, 'fr-FR')).toBe('SAVED fr'); + // Unchanged: with the package disabled again, a delete naming no package removes the row. engine.registry.disablePackage(PKG); expect(await protocol.deleteMetaItem({ type: 'email_template', name: NAME, member: 'fr-FR' } as any)) .toMatchObject({ success: true }); diff --git a/packages/runtime/src/domains/meta-disabled-holder-served-stack.test.ts b/packages/runtime/src/domains/meta-disabled-holder-served-stack.test.ts index 71a77421730..73e665628b8 100644 --- a/packages/runtime/src/domains/meta-disabled-holder-served-stack.test.ts +++ b/packages/runtime/src/domains/meta-disabled-holder-served-stack.test.ts @@ -723,12 +723,19 @@ describe('[#32605] the bare save of a name an enabled and a disabled package hol const AUTH_F = 'com.qa.save_authored_gamma'; const BOTH_SHIP = ['ship_none_dash', 'ship_drow_dash', 'ship_de_dash', 'ship_ed_dash']; const E_SHIPS = ['e_only_dash', 'e_authored_drow_dash', 'e_unbound_drow_dash', 'e_two_authored_dash']; + // [#33955] Names two ENABLED packages ship (neither disabled), and [#34144] names only D ships. + const TWO_SHIP = ['two_none_dash', 'two_erow_dash', 'two_drow_dash', 'two_rows_dash', 'two_unbound_dash', 'two_draft_dash', 'two_del_dash', 'two_norow_dash']; + const D_SHIPS = ['d_none_dash', 'd_drow_dash', 'd_unbound_dash', 'd_draft_dash', 'd_del_dash', 'd_norow_dash']; + const MAIL = 'save_beta_welcome'; + const mailAt = (locale: string, subject: string) => ({ name: MAIL, label: 'Welcome', locale, subject, bodyHtml: `

${subject}

` }); const savePackageOf = (id: string) => ({ id, name: id.split('.').pop(), namespace: id.split('.').pop(), version: '1.0.0', type: 'app', objects: [], - dashboards: [...BOTH_SHIP, ...(id === CODE_E ? E_SHIPS : [])].map((name) => ({ name, label: `${id} code`, widgets: [] })), + dashboards: [...BOTH_SHIP, ...TWO_SHIP, ...(id === CODE_E ? E_SHIPS : D_SHIPS)].map((name) => ({ name, label: `${id} code`, widgets: [] })), + // [#34262] A bundled name D alone ships, at one member (`en-US`). + ...(id === CODE_D ? { emailTemplates: [mailAt('en-US', 'D en')] } : {}), }); - interface SaveBooted extends Booted { put(name: string, label: string): Promise<{ status: number | undefined; body: any }> } + interface SaveBooted extends Booted { put(name: string, label: string, query?: Record): Promise<{ status: number | undefined; body: any }> } async function bootSaveKernel(order: readonly string[], transport: 'dispatcher' | 'rest'): Promise { const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false }); @@ -755,14 +762,15 @@ describe('[#32605] the bare save of a name an enabled and a disabled package hol if (transport === 'dispatcher') { return { kernel, engine, root, - put: async (name, label) => { + put: async (name, label, query = {}) => { const dispatcher = new HttpDispatcher(kernel as any, undefined, { enforceProjectMembership: false }); (dispatcher as any).timedResolveExecutionContext = async () => ({ ...CALLER }); - const request = new Request(`http://localhost/api/v1/meta/dashboard/${name}`, { + const search = new URLSearchParams(query).toString(); + const request = new Request(`http://localhost/api/v1/meta/dashboard/${name}${search ? `?${search}` : ''}`, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body(name, label)), }); try { - const out: any = await dispatcher.dispatch('PUT', `/meta/dashboard/${name}`, body(name, label), {}, { request } as any, '/api/v1'); + const out: any = await dispatcher.dispatch('PUT', `/meta/dashboard/${name}`, body(name, label), query, { request } as any, '/api/v1'); return { status: out.response?.status as number | undefined, body: out.response?.body }; } catch (e) { const thrown = resolveThrownHttpError(e); @@ -780,7 +788,7 @@ describe('[#32605] the bare save of a name an enabled and a disabled package hol rest.resolveExecCtx = async () => ({ ...CALLER }); return { kernel, engine, root, - put: async (name, label) => { + put: async (name, label, query = {}) => { const res: any = { statusCode: 200, body: undefined, headers: {} as Record }; res.status = (code: number) => { res.statusCode = code; return res; }; res.json = (payload: any) => { res.body = payload; return res; }; @@ -791,7 +799,7 @@ describe('[#32605] the bare save of a name an enabled and a disabled package hol res.write = () => true; await route.handler({ method: 'PUT', path: `/api/v1/meta/dashboard/${name}`, params: { type: 'dashboard', name }, - headers: {}, query: {}, body: body(name, label), + headers: {}, query, body: body(name, label), }, res); return { status: res.statusCode, body: res.body }; }, @@ -818,6 +826,23 @@ describe('[#32605] the bare save of a name an enabled and a disabled package hol expect([answer.status, codeOf(answer.body)], JSON.stringify(answer.body)).toEqual([409, 'RESOURCE_CONFLICT']); for (const id of [e, d]) expect(JSON.stringify(answer.body)).toContain(id); }; + /** [#34144] Refused with the `?package=` remedy, naming none of `ids`. */ + const expectRefusedNamingNone = (answer: { status: number | undefined; body: any }, ids: readonly string[]) => { + expect([answer.status, codeOf(answer.body)], JSON.stringify(answer.body)).toEqual([409, 'RESOURCE_CONFLICT']); + expect(JSON.stringify(answer.body)).toContain('?package='); + for (const id of ids) expect(JSON.stringify(answer.body)).not.toContain(id); + }; + /** Every stored row of the dashboard, active and draft: `state:binding:label`. */ + const everyRow = async (engine: ObjectQL, name: string) => ((await engine.find('sys_metadata', { where: { type: 'dashboard', name }, context: { isSystem: true } } satisfies EngineQueryOptions)) as any[]) + .map((row) => `${row.state}:${row.package_id ?? null}:${JSON.parse(String(row.metadata)).label}`).sort(); + /** What `call` rejects with, or `{ resolved }` when it resolves. */ + const refusalOf = (call: Promise): Promise => call.then((resolved) => ({ resolved }), (error: unknown) => error); + /** [#34144] An in-process delete refused with the `?package=` remedy, naming none of `ids`. */ + const expectDeleteRefusedNamingNone = (refusal: any, ids: readonly string[]) => { + expect([refusal?.code, refusal?.status], JSON.stringify(refusal?.resolved ?? String(refusal?.message))).toEqual(['RESOURCE_CONFLICT', 409]); + expect(String(refusal?.message)).toContain('?package='); + for (const id of ids) expect(String(refusal?.message)).not.toContain(id); + }; describe.each([ { regOrder: 'disabled first', transport: 'dispatcher' as const, order: [CODE_D, CODE_E] }, @@ -965,14 +990,160 @@ describe('[#32605] the bare save of a name an enabled and a disabled package hol }); }); - it('CONTROL: a name only the disabled D holds (its row alone) is saved as before, at D\'s address (no served holder takes it)', async () => { + // [#34144, ruling A, ADR-0150 D3] A name only disabled packages hold: + // the bare read answers the missing name, so the bare save is refused + // with the `?package=` remedy and names no package. It edited D's row + // (200), or stored a package-unbound row every read then withholds. + it('ruling A: a name only the disabled D holds (its row alone): the bare save is refused naming no package and D\'s row is byte-unchanged; ?package=D saves as before, and re-enabled the bare save is D\'s again (CONTROL)', async () => { await layRow(booted!.engine, 'authored_donly_dash', AUTH_D, 'disabled row'); + const before = await storedRows(booted!.engine, 'authored_donly_dash'); await withDisabled(AUTH_D, async () => { - const saved = await booted!.put('authored_donly_dash', 'edited'); - expect(saved.status, JSON.stringify(saved.body)).toBe(200); - const rows = await storedRows(booted!.engine, 'authored_donly_dash'); - expect([Object.keys(rows), rows[AUTH_D]?.label]).toEqual([[AUTH_D], 'edited']); + expect((await get(booted!.kernel, '/meta/dashboard/authored_donly_dash')).status).toBe(404); + expectRefusedNamingNone(await booted!.put('authored_donly_dash', 'edited'), [AUTH_D, CODE_D, CODE_E]); + expect(await storedRows(booted!.engine, 'authored_donly_dash')).toEqual(before); + // CONTROL: the address naming D, unchanged. + const named = await booted!.put('authored_donly_dash', 'named', { package: AUTH_D }); + expect(named.status, JSON.stringify(named.body)).toBe(200); + expect((await storedRows(booted!.engine, 'authored_donly_dash'))[AUTH_D]?.label).toBe('named'); + }); + // CONTROL: re-enabled, the bare save writes D's row, as before. + const saved = await booted!.put('authored_donly_dash', 'edited'); + expect(saved.status, JSON.stringify(saved.body)).toBe(200); + const rows = await storedRows(booted!.engine, 'authored_donly_dash'); + expect([Object.keys(rows), rows[AUTH_D]?.label]).toEqual([[AUTH_D], 'edited']); + }); + + it.each([ + { rows: 'no stored row', name: 'd_none_dash', laid: false }, + { rows: 'D\'s row', name: 'd_drow_dash', laid: true }, + ])('ruling A: only the disabled D ships it ($rows): the bare save is refused naming no package and nothing is written; re-enabled, it saves as before (CONTROL)', async ({ name, laid }) => { + if (laid) await layRow(booted!.engine, name, CODE_D, 'disabled row'); + const before = await everyRow(booted!.engine, name); + await withDisabled(CODE_D, async () => { + expect((await get(booted!.kernel, `/meta/dashboard/${name}`)).status).toBe(404); + expectRefusedNamingNone(await booted!.put(name, 'edited'), [CODE_D, CODE_E]); + expect(await everyRow(booted!.engine, name)).toEqual(before); + }); + const saved = await booted!.put(name, 'edited'); + expect(saved.status, JSON.stringify(saved.body)).toBe(200); + expect(Object.values(await storedRows(booted!.engine, name)).map((row) => row.label)).toEqual(['edited']); + }); + + it('ruling A, aligned: the bare draft save and the bare delete of a name only the disabled D holds are refused naming no package, and nothing moves; the delete naming D removes D\'s row as before (CONTROL)', async () => { + await layRow(booted!.engine, 'd_del_dash', CODE_D, 'disabled row'); + const before = { draft: await everyRow(booted!.engine, 'd_draft_dash'), del: await everyRow(booted!.engine, 'd_del_dash') }; + const protocol = booted!.kernel.getService('protocol'); + await withDisabled(CODE_D, async () => { + expectRefusedNamingNone(await booted!.put('d_draft_dash', 'drafted', { mode: 'draft' }), [CODE_D, CODE_E]); + expectDeleteRefusedNamingNone(await refusalOf(protocol.deleteMetaItem({ type: 'dashboard', name: 'd_del_dash' })), [CODE_D, CODE_E]); + expect({ draft: await everyRow(booted!.engine, 'd_draft_dash'), del: await everyRow(booted!.engine, 'd_del_dash') }).toEqual(before); + expect(await protocol.deleteMetaItem({ type: 'dashboard', name: 'd_del_dash', packageId: CODE_D })).toMatchObject({ success: true }); + expect(await everyRow(booted!.engine, 'd_del_dash')).toEqual([]); + }); + }); + + // [#34144 review#1 S2, ruling A] Over NO stored row the bare delete and + // the bare draft discard answered the no-op receipt (`success: true, + // reset: false`). They are refused as the bare save is. + it('ruling A, no stored row: the bare delete and the bare draft discard of a name only the disabled D holds are refused naming no package, not answered the no-op receipt; naming D, the receipt as before (CONTROL)', async () => { + const protocol = booted!.kernel.getService('protocol'); + await withDisabled(CODE_D, async () => { + expectDeleteRefusedNamingNone(await refusalOf(protocol.deleteMetaItem({ type: 'dashboard', name: 'd_norow_dash' })), [CODE_D, CODE_E]); + expectDeleteRefusedNamingNone(await refusalOf(protocol.deleteMetaItem({ type: 'dashboard', name: 'd_norow_dash', state: 'draft' })), [CODE_D, CODE_E]); + expect(await everyRow(booted!.engine, 'd_norow_dash')).toEqual([]); + expect(await protocol.deleteMetaItem({ type: 'dashboard', name: 'd_norow_dash', packageId: CODE_D })).toMatchObject({ success: true, reset: false }); + }); + }); + + it('CONTROL: the environment\'s own items save as before beside a disabled D: a name no package holds, and the package-unbound row of a name only D ships (which the bare read withholds)', async () => { + await layRow(booted!.engine, 'env_only_dash', null, 'environment row'); + await layRow(booted!.engine, 'd_unbound_dash', null, 'environment row'); + await withDisabled(CODE_D, async () => { + for (const name of ['env_only_dash', 'd_unbound_dash']) { + const saved = await booted!.put(name, 'edited'); + expect(saved.status, JSON.stringify(saved.body)).toBe(200); + const rows = await storedRows(booted!.engine, name); + expect([Object.keys(rows), rows.null?.label]).toEqual([['null'], 'edited']); + } + }); + }); + + // [#33955, ADR-0150 D3/D5, red line 2] Two ENABLED packages ship the + // name: the bare read refuses 409 naming both, so the bare save does + // too, never a guess. It answered 200, writing a package-unbound row + // over no stored row and updating the one package's row over one. + it.each([ + { rows: 'no stored row', name: 'two_none_dash', laid: [] as string[] }, + { rows: 'E\'s row', name: 'two_erow_dash', laid: [CODE_E] }, + { rows: 'D\'s row', name: 'two_drow_dash', laid: [CODE_D] }, + { rows: 'a row of each (CONTROL: refused before too)', name: 'two_rows_dash', laid: [CODE_E, CODE_D] }, + ])('two enabled packages ship it, $rows: the bare save refuses 409 naming both, as the bare read does, and nothing is written', async ({ name, laid }) => { + for (const id of laid) await layRow(booted!.engine, name, id, `${id} row`); + const before = await everyRow(booted!.engine, name); + expectRefusedNamingBoth(await get(booted!.kernel, `/meta/dashboard/${name}`), CODE_E, CODE_D); + expectRefusedNamingBoth(await booted!.put(name, 'edited'), CODE_E, CODE_D); + expect(await everyRow(booted!.engine, name)).toEqual(before); + }); + + it('two enabled packages ship it, aligned: the bare draft save and the bare delete refuse naming both and nothing moves; ?package=E saves and deletes E\'s row as before (CONTROL)', async () => { + await layRow(booted!.engine, 'two_del_dash', CODE_E, 'E row'); + const protocol = booted!.kernel.getService('protocol'); + const before = { draft: await everyRow(booted!.engine, 'two_draft_dash'), del: await everyRow(booted!.engine, 'two_del_dash') }; + expectRefusedNamingBoth(await booted!.put('two_draft_dash', 'drafted', { mode: 'draft' }), CODE_E, CODE_D); + let refusal: any; + try { await protocol.deleteMetaItem({ type: 'dashboard', name: 'two_del_dash' }); } catch (error) { refusal = error; } + expect([refusal?.code, refusal?.status]).toEqual(['RESOURCE_CONFLICT', 409]); + for (const id of [CODE_E, CODE_D]) expect(String(refusal?.message)).toContain(id); + expect({ draft: await everyRow(booted!.engine, 'two_draft_dash'), del: await everyRow(booted!.engine, 'two_del_dash') }).toEqual(before); + const named = await booted!.put('two_draft_dash', 'named', { package: CODE_E }); + expect(named.status, JSON.stringify(named.body)).toBe(200); + expect(await everyRow(booted!.engine, 'two_draft_dash')).toEqual([`active:${CODE_E}:named`]); + expect(await protocol.deleteMetaItem({ type: 'dashboard', name: 'two_del_dash', packageId: CODE_E })).toMatchObject({ success: true }); + expect(await everyRow(booted!.engine, 'two_del_dash')).toEqual([]); + }); + + // [#33955 review#1 S2] Over NO stored row the bare delete and the bare + // draft discard answered the no-op receipt. They are refused naming + // both, as the bare read is. + it('two enabled packages ship it, no stored row: the bare delete and the bare draft discard refuse naming both, not answered the no-op receipt; naming E, the receipt as before (CONTROL)', async () => { + const protocol = booted!.kernel.getService('protocol'); + for (const state of [undefined, 'draft'] as const) { + const refusal = await refusalOf(protocol.deleteMetaItem({ type: 'dashboard', name: 'two_norow_dash', ...(state ? { state } : {}) })); + expect([refusal?.code, refusal?.status], JSON.stringify(refusal?.resolved ?? String(refusal?.message))).toEqual(['RESOURCE_CONFLICT', 409]); + for (const id of [CODE_E, CODE_D]) expect(String(refusal?.message)).toContain(id); + } + expect(await everyRow(booted!.engine, 'two_norow_dash')).toEqual([]); + expect(await protocol.deleteMetaItem({ type: 'dashboard', name: 'two_norow_dash', packageId: CODE_E })).toMatchObject({ success: true, reset: false }); + }); + + it('CONTROL: two enabled packages ship it and the environment\'s package-unbound row is stored: the bare save edits that row and the bare delete removes it, as before', async () => { + await layRow(booted!.engine, 'two_unbound_dash', null, 'environment row'); + const saved = await booted!.put('two_unbound_dash', 'edited'); + expect(saved.status, JSON.stringify(saved.body)).toBe(200); + expect(await everyRow(booted!.engine, 'two_unbound_dash')).toEqual(['active:null:edited']); + expect(await booted!.kernel.getService('protocol').deleteMetaItem({ type: 'dashboard', name: 'two_unbound_dash' })).toMatchObject({ success: true }); + expect(await everyRow(booted!.engine, 'two_unbound_dash')).toEqual([]); + }); + + // [#34262, ruling A] Every holder of a bundled name disabled: the bare + // save at a member D never ships was accepted and stored (200), then + // withheld by every read until D was enabled again. It is refused as + // any bare save of a name only disabled packages hold is. + it('ruling A: every holder of a bundled name disabled, the bare save at a member D never ships (and at the one it ships) is refused naming no package and stores nothing; re-enabled, the unshipped member saves (CONTROL)', async () => { + const protocol = booted!.kernel.getService('protocol'); + const mailRows = async () => ((await booted!.engine.find('sys_metadata', { where: { type: 'email_template', name: MAIL }, context: { isSystem: true } } satisfies EngineQueryOptions)) as any[]).length; + await withDisabled(CODE_D, async () => { + for (const locale of ['fr-FR', 'en-US']) { + let refusal: any; + try { await protocol.saveMetaItem({ type: 'email_template', name: MAIL, item: mailAt(locale, `saved ${locale}`) }); } catch (error) { refusal = error; } + expect([refusal?.code, refusal?.status], String(refusal?.message)).toEqual(['RESOURCE_CONFLICT', 409]); + expect(String(refusal?.message)).toContain('?package='); + expect(String(refusal?.message)).not.toContain(CODE_D); + } + expect(await mailRows()).toBe(0); }); + expect(await protocol.saveMetaItem({ type: 'email_template', name: MAIL, item: mailAt('fr-FR', 'saved fr-FR') })).toMatchObject({ success: true }); + expect(await mailRows()).toBe(1); }); }); });