diff --git a/.changeset/33003-environment-row-rewrite-keeps-mark.md b/.changeset/33003-environment-row-rewrite-keeps-mark.md new file mode 100644 index 00000000000..4d7da86e2b9 --- /dev/null +++ b/.changeset/33003-environment-row-rewrite-keeps-mark.md @@ -0,0 +1,14 @@ +--- +'@objectstack/metadata': patch +--- + +fix(metadata): a write that rewrites an environment row the boot pass stamped with the host keeps it the environment's, so unregistering the host package keeps it in this process and after a restart + +Clause-②: no — no released answer moves: `@objectstack/metadata@18.3.0`'s `unregisterPackage` never removed an item named only by the `_packageId` stamp, so these rows were kept there too; #32198 (unreleased) is what turned the rewrite into a deletion. The registry entry keeps the stamp, so the ObjectQL owner of such an object does not move. +Metadata-protocol: none + +On a host that declares its package and stores metadata in a database, the boot pass stamps each stored row that names no package with the host's package, and `unregisterPackage(host)` leaves such a row (#32986). That held only until something rewrote the row: a write that registered a copy still stamped with the host dropped the mark and stored the stamp in the row's body, so the row then read as the host's own, in that process and after a restart, and `unregisterPackage(host)` deleted it. The writers that do this: ObjectQL's late-manifest bridge when another package extends the environment's object (and its restore when that package is withdrawn), ObjectQL's object-copy follow, `publishPackage` and `revertPackage` of the host, `importMetadata` with `conflictResolution: 'merge'`, and `rollback` to a version stored with the host stamp. + +Now a copy that replaces such a row and carries the host's stamp, or no stamp, keeps the row's mark (so a copy stamped with the host after an unstamped replacement is still the row), and the row is stored without the host stamp (at the top and in the publish envelope's `metadata` body, on `register` and on `rollback`), so the next boot reads it as the environment's own again. The host's own rows, a copy that names the host by its own `packageId` or `package` key, a copy stamped with another package, and a stored row another writer re-saved naming the host are removed as before. A `draft` row is treated like an `active` one. Types stored per `(package, name)` are unchanged here. + +A row whose stored body already carries the host stamp (one a boot pass of 18.3.0 or earlier stored, or a write stored before this change) reads as the host's own row and is still removed with it: no boot rule can tell it from a row the host seeded. Its upgrade path is #33043. diff --git a/packages/metadata/src/loaders/database-loader.test.ts b/packages/metadata/src/loaders/database-loader.test.ts index 5dae5a02573..44758b14dd6 100644 --- a/packages/metadata/src/loaders/database-loader.test.ts +++ b/packages/metadata/src/loaders/database-loader.test.ts @@ -3324,3 +3324,252 @@ describe('[#32986] unregisterPackage of the host package keeps the environment\' expect(await state(bare)).toEqual(ITEMS.map(([type]) => [type, null, 'env', 1])); }); }); + +/** + * [#33003; follow-up of #32986, review S1 of PR #32999] The boot pass's mark + * on an environment row it stamped with the host rode the registry object, so + * a later write that registered a COPY still stamped with the host dropped it + * — and stored the stamp in the row's body, so the next boot read the row as + * the host's own too. `unregisterPackage(host)` then deleted the row again, in + * that process and after a restart. The writers measured, each driven here + * through the call it makes on this manager: + * + * - ObjectQL's late-manifest bridge, the `ownPreviousCopy` arm: another + * package extends the environment's object and the bridge re-registers the + * merged object stamped with its owner, the host (`register`, `notify: + * false`); its withdrawal counterpart `restoreExtendedObjectCopies` puts the + * owner's body back the same way; + * - ObjectQL's object-copy follow (`putObjectCopy` → `registerInMemory`); + * - `publishPackage(host)` and `revertPackage(host)`, over + * `collectPackageMembers`, which counts a stamped environment row as the + * host's; + * - `importMetadata` with `conflictResolution: 'merge'` (`{ ...existing, ...item }`). + * + * A copy that replaces such a row and still names the host by the stamp alone + * now keeps the row's mark, and the row is stored without the host stamp: the + * environment's own row, read as such at the next boot. The registry entry + * keeps the stamp (ObjectQL's owner does not move). + * + * Also pinned (review nits N1/N2 of PR #32999): a `state: 'draft'` row is + * treated like an `active` one, and the rule holds for non-slotted types + * beyond the five #32986 names (`page`, `report`; `flow` is stored per + * `(package, name)` and is not under this rule). + * + * BEFORE (#32999's head): every case below not marked CONTROL lost the row. + */ +describe('[#33003] a write that rewrites an environment row the boot pass stamped keeps it the environment\'s: unregisterPackage(host) keeps it in process and after a reboot', () => { + const HOST = 'com.host.app'; + const EXT = 'com.ext.app'; + /** [type, name, state]: one draft row (N1), and two non-slotted types beyond the five (N2). */ + const ITEMS: ReadonlyArray = [ + ['object', 'env_account', 'active'], ['object', 'env_draft', 'draft'], ['view', 'env_account.all', 'active'], + ['app', 'env_app', 'active'], ['hook', 'env_hook', 'active'], ['dashboard', 'env_dashboard', 'active'], + ['page', 'env_page', 'active'], ['report', 'env_report', 'active'], + ]; + const OBJECTS = ITEMS.filter(([type]) => type === 'object'); + let driver: IDataDriver; + + const seed = (type: string, name: string, state: string, body: Record) => + driver.create('sys_metadata', { + id: `${type}_${name}`, type, name, state, version: 1, checksum: `${type}_${name}`, + source: 'database', package_id: null, metadata: JSON.stringify({ name, label: 'env', ...body }), + }); + const bootPass = async () => { + const plugin = new MetadataPlugin({ packageId: HOST, watch: false, config: { bootstrap: 'eager' } }); + const m = (plugin as any).manager as MetadataManager; + (m as any).loaders.clear(); + m.registerLoader(new DatabaseLoader({ driver })); + await (plugin as any)._loadFromFileSystem({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() } }); + return m; + }; + /** Per item: the registry's stamp, whether a read answers it, and how many stored rows it has. */ + const state = async (m: MetadataManager, items: ReadonlyArray = ITEMS) => { + const out: unknown[] = []; + for (const [type, name] of items) { + const held = (m as any).registry.get(type)?.get(name) as { _packageId?: string } | undefined; + const rows = await driver.find('sys_metadata', { where: { type, name } } as never); + out.push([type, name, held?._packageId ?? null, (await m.get(type, name)) !== undefined, rows.length]); + } + return out; + }; + const kept = (items: ReadonlyArray = ITEMS) => items.map(([type, name]) => [type, name, HOST, true, 1]); + const gone = (items: ReadonlyArray = ITEMS) => items.map(([type, name]) => [type, name, null, false, 0]); + + /** Each writer, driven through the call it makes on the manager; `items` = the rows it rewrites. */ + const WRITES: ReadonlyArray<{ writer: string; items: typeof ITEMS; write: (m: MetadataManager) => Promise }> = [ + { + writer: 'ObjectQL\'s late-manifest bridge, ownPreviousCopy arm (an extender\'s field merged, re-registered stamped with the owner)', + items: OBJECTS, + write: async (m) => { + for (const [, name] of OBJECTS) { + const current = (m as any).registry.get('object').get(name) as Record; + await m.register('object', name, { ...current, fields: { ext_score: { type: 'number' } }, _packageId: HOST }, { notify: false }); + } + }, + }, + { + writer: 'the bridge, then restoreExtendedObjectCopies (the owner\'s body put back, stamped with the owner)', + items: OBJECTS, + write: async (m) => { + for (const [, name] of OBJECTS) { + await m.register('object', name, { name, label: 'env', fields: { ext_score: { type: 'number' } }, _packageId: HOST }, { notify: false }); + await m.register('object', name, { name, label: 'env', _packageId: HOST }, { notify: false }); + } + }, + }, + { + writer: 'ObjectQL\'s object-copy follow (registerInMemory of the served body, stamped with the owner)', + items: OBJECTS, + write: async (m) => { + for (const [, name] of OBJECTS) m.registerInMemory('object', name, { name, label: 'served', _packageId: HOST }); + }, + }, + { writer: 'publishPackage(host)', items: ITEMS, write: (m) => m.publishPackage(HOST, { validate: false }) }, + { + writer: 'publishPackage(host), then revertPackage(host)', + items: ITEMS, + write: async (m) => { + expect((await m.publishPackage(HOST, { validate: false })).success).toBe(true); + await m.revertPackage(HOST); + }, + }, + { + writer: 'importMetadata, conflictResolution merge', + items: ITEMS, + write: (m) => m.importMetadata( + Object.fromEntries(ITEMS.map(([type]) => [type, ITEMS.filter(([t]) => t === type).map(([, name]) => ({ name, description: 'imported' }))])), + { conflictResolution: 'merge' }, + ), + }, + ]; + + beforeEach(() => { + driver = createMockDriver(); + }); + + for (const { writer, items, write } of WRITES) { + it(`${writer}: unregisterPackage(host) in the same process keeps each rewritten row, registry entry and stored row (BEFORE: deleted)`, async () => { + for (const [type, name, rowState] of ITEMS) await seed(type, name, rowState, {}); + const m = await bootPass(); + await write(m); + expect(await state(m, items), 'the stamp stays on the registry entry: the owner does not move').toEqual(kept(items)); + await m.unregisterPackage(HOST); + expect(await state(m)).toEqual(kept()); + }); + + it(`${writer}: after a reboot from the same database, unregisterPackage(host) keeps each rewritten row (BEFORE: the stored stamp made it the host's, and it was deleted)`, async () => { + for (const [type, name, rowState] of ITEMS) await seed(type, name, rowState, {}); + await write(await bootPass()); + const rebooted = await bootPass(); + expect(await state(rebooted)).toEqual(kept()); + await rebooted.unregisterPackage(HOST); + expect(await state(rebooted)).toEqual(kept()); + }); + + it(`CONTROL ${writer}: the host's own rows (stored bodies carrying its stamp) are still removed, in the same process and after a reboot`, async () => { + for (const [type, name, rowState] of ITEMS) await seed(type, name, rowState, { _packageId: HOST }); + const m = await bootPass(); + await write(m); + const rebooted = await bootPass(); + expect(await state(rebooted)).toEqual(kept()); + await rebooted.unregisterPackage(HOST); + expect(await state(rebooted)).toEqual(gone()); + // The same rows, removed by the first process too (already gone from storage). + await m.unregisterPackage(HOST); + expect(await state(m)).toEqual(gone()); + }); + } + + it('CONTROL a copy that names the host by its own key (packageId) is the host\'s item: unregisterPackage(host) removes it', async () => { + for (const [type, name, rowState] of ITEMS) await seed(type, name, rowState, {}); + const m = await bootPass(); + await m.register('object', 'env_account', { name: 'env_account', label: 'env', packageId: HOST, _packageId: HOST }); + await m.unregisterPackage(HOST); + expect(await state(m)).toEqual(ITEMS.map(([type, name]) => name === 'env_account' ? [type, name, null, false, 0] : [type, name, HOST, true, 1])); + }); + + it('CONTROL a stored row that now names the host in its own body, read again by the pass over the marked entry, is the host\'s: unregisterPackage(host) removes it', async () => { + for (const [type, name, rowState] of ITEMS) await seed(type, name, rowState, {}); + const plugin = new MetadataPlugin({ packageId: HOST, watch: false, config: { bootstrap: 'eager' } }); + const m = (plugin as any).manager as MetadataManager; + (m as any).loaders.clear(); + m.registerLoader(new DatabaseLoader({ driver })); + const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; + await (plugin as any)._loadFromFileSystem({ logger }); + // Another writer (a peer node, a CLI) stores the host's own row under the name. + await driver.update('sys_metadata', 'object_env_account', { metadata: JSON.stringify({ name: 'env_account', label: 'host', _packageId: HOST }), checksum: 'host' }); + // A fresh loader over the store (no read cache), as a reload reads it. + (m as any).loaders.clear(); + m.registerLoader(new DatabaseLoader({ driver })); + await (plugin as any)._loadFromFileSystem({ logger }); + expect((m as any).registry.get('object').get('env_account')).toMatchObject({ label: 'host', _packageId: HOST }); + await m.unregisterPackage(HOST); + expect(await state(m)).toEqual(ITEMS.map(([type, name]) => name === 'env_account' ? [type, name, null, false, 0] : [type, name, HOST, true, 1])); + }); + + it('CONTROL a copy stamped with another package is that package\'s item: unregisterPackage of that package removes it', async () => { + for (const [type, name, rowState] of ITEMS) await seed(type, name, rowState, {}); + const m = await bootPass(); + await m.register('object', 'env_account', { name: 'env_account', label: 'env', _packageId: EXT }, { notify: false }); + await m.unregisterPackage(EXT); + expect(await state(m)).toEqual(ITEMS.map(([type, name]) => name === 'env_account' ? [type, name, null, false, 0] : [type, name, HOST, true, 1])); + }); + + /** + * [#33003, review S3] An unstamped replacement (an import without `merge`, + * a `bulkRegister`) keeps the row's mark and its host, so the copy ObjectQL's + * object-copy follow then writes, stamped with the registry owner (still the + * host), is the row too. + */ + for (const [writer, replace] of [ + ['importMetadata overwrite', (m: MetadataManager) => m.importMetadata({ object: [{ name: 'env_account', label: 'replaced' }] }, { conflictResolution: 'overwrite' })], + ['bulkRegister', (m: MetadataManager) => m.bulkRegister([{ type: 'object', name: 'env_account', data: { name: 'env_account', label: 'replaced' } }])], + ] as const) { + it(`an unstamped replacement (${writer}), then the object-copy follow stamped with the host: unregisterPackage(host) keeps the row (BEFORE: deleted)`, async () => { + for (const [type, name, rowState] of ITEMS) await seed(type, name, rowState, {}); + const m = await bootPass(); + await replace(m); + m.registerInMemory('object', 'env_account', { name: 'env_account', label: 'served', _packageId: HOST }); + await m.unregisterPackage(HOST); + expect(await state(m)).toEqual(kept()); + }); + } + + /** + * [#33003, review S2] `rollback` persists through the loader's own rollback + * path, not `register`. A version a rewrite stored before #33003 carries the + * host stamp; restored over the environment's row, it is that row. + */ + it('rollback to a version stored with the host stamp: unregisterPackage(host) keeps the row in this process and after a reboot (BEFORE: deleted after the reboot)', async () => { + for (const [type, name, rowState] of ITEMS) await seed(type, name, rowState, {}); + const m = await bootPass(); + // A version a rewrite stored before #33003: the body carries the host stamp. + await (m as any).getDatabaseLoader().save('object', 'env_account', { name: 'env_account', label: 'stamped', _packageId: HOST }); + await m.register('object', 'env_account', { name: 'env_account', label: 'later' }); + await m.rollback('object', 'env_account', 2); + const rebooted = await bootPass(); + await rebooted.unregisterPackage(HOST); + expect(await state(rebooted)).toEqual(kept()); + await m.unregisterPackage(HOST); + expect(await state(m)).toEqual(kept()); + }); + + it('CONTROL rollback of the host\'s own row to a stamped version: removed after a reboot', async () => { + for (const [type, name, rowState] of ITEMS) await seed(type, name, rowState, { _packageId: HOST }); + const m = await bootPass(); + await (m as any).getDatabaseLoader().save('object', 'env_account', { name: 'env_account', label: 'stamped', _packageId: HOST }); + await m.register('object', 'env_account', { name: 'env_account', label: 'later', _packageId: HOST }); + await m.rollback('object', 'env_account', 2); + const rebooted = await bootPass(); + await rebooted.unregisterPackage(HOST); + expect(await state(rebooted)).toEqual(gone()); + }); + + it('CONTROL unregisterPackage of the extender leaves the environment\'s object the bridge rewrote, and of another package nothing moves', async () => { + for (const [type, name, rowState] of ITEMS) await seed(type, name, rowState, {}); + const m = await bootPass(); + await WRITES[0].write(m); + await m.unregisterPackage(EXT); + expect(await state(m)).toEqual(kept()); + }); +}); diff --git a/packages/metadata/src/metadata-manager.ts b/packages/metadata/src/metadata-manager.ts index d48a78267ac..599a20ec8dd 100644 --- a/packages/metadata/src/metadata-manager.ts +++ b/packages/metadata/src/metadata-manager.ts @@ -113,7 +113,7 @@ import { } from './package-slotted-store.js'; // [#5309] The stored ENVELOPE / authored BODY split — peeled before any spec // schema parses a stored row. See `stored-envelope.ts`. -import { peelStoredEnvelope, STORED_ENVELOPE_KEYS } from './stored-envelope.js'; +import { peelStoredEnvelope, STORED_BODY_KEY, STORED_ENVELOPE_KEYS } from './stored-envelope.js'; // [#13913] Registry-free expansion of an aggregated view container reached // through THIS manager's own store — see `getViewsByObject`. import { expandRuntimeViewContainer } from './view-container-expansion.js'; @@ -185,6 +185,26 @@ function isPackageMember(item: unknown, packageId: string): boolean { return meta?.packageId === packageId || meta?.package === packageId || meta?._packageId === packageId; } +/** + * [#33003] The body {@link MetadataManager.register} stores for an environment + * row the boot pass stamped with `stamp`: `data` without that stamp, at the top + * and in the publish envelope's `metadata` body (`revertPackage` restores the + * stamped snapshot there, and the store's package read peels to it). The + * registry keeps `data` as it is, stamp included. A copy: `data` is never + * changed. + */ +function withoutEnvironmentRowStamp(data: Record, stamp: string): Record { + const stored: Record = { ...data }; + delete stored._packageId; + const body = stored[STORED_BODY_KEY]; + if (body !== null && typeof body === 'object' && !Array.isArray(body) && (body as { _packageId?: unknown })._packageId === stamp) { + const unstamped: Record = { ...(body as Record) }; + delete unstamped._packageId; + stored[STORED_BODY_KEY] = unstamped; + } + return stored; +} + /** * [#5276, #32246, #32353] Whether {@link MetadataManager.unregister}'s storage * half deletes from `loader`: a `datasource:` loader that declares write @@ -654,9 +674,17 @@ export class MetadataManager implements IMetadataService { * the host's declared package (`_packageId`), and the stamp stays — ObjectQL * registers such an `object` as the host package's contribution — but the * row is not the package's item, so {@link unregisterPackage} leaves it - * ({@link isStampedEnvironmentRow}). + * ({@link isStampedEnvironmentRow}). [#33003] A copy that replaces one + * joins the set ({@link carryEnvironmentRowMark}), and {@link register} + * stores a member without the stamp. */ private readonly storedEnvironmentRows = new WeakSet(); + /** + * [#33003] The host stamp each {@link storedEnvironmentRows} member carried + * on, so an unstamped replacement passes it on to the copy after it + * ({@link carryEnvironmentRowMark}). + */ + private readonly environmentRowHosts = new WeakMap(); // Protected so subclasses can access serializers if needed protected serializers: Map; protected logger: Logger; @@ -1167,6 +1195,13 @@ export class MetadataManager implements IMetadataService { const existed = this.writeRegistryEntry(type, name, data); this.invalidateListCache(type); + // [#33003] An environment row the boot pass stamped is stored as the + // environment's own row: without the host stamp, so the next boot reads it + // naming no package again, whichever writer rewrote it + // ({@link withoutEnvironmentRowStamp}). + const stamp = this.environmentRowStamp(data); + const stored = stamp === undefined ? data : withoutEnvironmentRowStamp(data as Record, stamp); + // Persist only to database-backed loaders that declare write capability. // FilesystemLoader is read-only at runtime — writing to it can crash in // read-only environments (e.g. serverless, containerized deployments). @@ -1188,7 +1223,7 @@ export class MetadataManager implements IMetadataService { await loader.bindReadRowPackage?.(type, name, data); continue; } - await loader.save(type, name, data); + await loader.save(type, name, stored); } // Publish metadata.{type}.created / .updated event to realtime service. @@ -1294,6 +1329,8 @@ export class MetadataManager implements IMetadataService { const { key, replaces } = slot === undefined ? storeWriteKey(typeStore, type, name, data) : { key: slot, replaces: [] }; if (!typeStore) this.registry.set(type, (typeStore = new Map())); const existed = typeStore.has(key) || replaces.length > 0; + // [#33003] A copy of an environment row the boot pass stamped, carrying its stamp or none, is that row. + this.carryEnvironmentRowMark(typeStore.get(key), data); for (const replaced of replaces) typeStore.delete(replaced); typeStore.set(key, data); recordStoreWrite(typeStore, key); @@ -2667,6 +2704,48 @@ export class MetadataManager implements IMetadataService { return meta._packageId === packageId && meta.packageId !== packageId && meta.package !== packageId; } + /** + * [#33003] The host stamp of `data` when it is one of the + * {@link storedEnvironmentRows} naming its package by that stamp alone + * ({@link isStampedEnvironmentRow}); `undefined` for every other item. + */ + private environmentRowStamp(data: unknown): string | undefined { + const stamp = (data as { _packageId?: unknown } | null | undefined)?._packageId; + return typeof stamp === 'string' && this.isStampedEnvironmentRow(data, stamp) ? stamp : undefined; + } + + /** + * [#33003] Writing `data` over `before`, where `before` is one of the + * {@link storedEnvironmentRows}: `data` is that row rewritten, and keeps its + * mark, when no loader handed it out and it carries the row's host stamp or + * none. A copy that also names the package by its own key stays the + * package's item ({@link isStampedEnvironmentRow} reads every key at each + * use); a copy stamped with another package is that package's. The host + * stamp is remembered ({@link environmentRowHosts}), so a copy stamped with + * the host after an unstamped replacement (an `importMetadata` without + * `merge`, a `bulkRegister`, a `rollback` to an authored version, then + * ObjectQL's object-copy follow) is still the row. + * + * Every writer that registers such a copy reaches this — ObjectQL's + * late-manifest bridge (the `ownPreviousCopy` re-register and + * `restoreExtendedObjectCopies`) and its object-copy follow + * (`registerInMemory`), `publishPackage` / `revertPackage` over + * {@link collectPackageMembers}, `importMetadata`, `bulkRegister` and + * {@link rollback} — so the copy keeps the row's mark instead of the mark + * riding the replaced object. An item a loader handed out (a file's, a + * stored row's) is that loader's item, never a copy: a stored row is marked + * by {@link loadMany} itself. + */ + private carryEnvironmentRowMark(before: unknown, data: unknown): void { + if (data === null || typeof data !== 'object' || data === before || this.loadedFrom.has(data)) return; + if (before === null || typeof before !== 'object' || !this.storedEnvironmentRows.has(before)) return; + const host = this.environmentRowHosts.get(before) ?? this.environmentRowStamp(before); + const stamp = (data as { _packageId?: unknown })._packageId; + if (stamp !== undefined && stamp !== host) return; + this.storedEnvironmentRows.add(data); + if (host !== undefined) this.environmentRowHosts.set(data, host); + } + /** * [#22113] The registry items that belong to `packageId`, for the two * package-wide writes ({@link publishPackage}, {@link revertPackage}). @@ -4546,10 +4625,16 @@ export class MetadataManager implements IMetadataService { // Restore the metadata using the dedicated rollback path so that a single // 'revert' history entry is written (instead of a conflicting 'update' entry) const restoredMetadata = targetVersion.metadata; + // [#33003] A version restored over an environment row the boot pass + // stamped is that row (a version a rewrite stored before #33003 carries the + // host stamp): stored without the stamp, as {@link register} stores it. + const slotted = PACKAGE_SLOTTED_STORE_TYPES.has(type); + if (!slotted) this.carryEnvironmentRowMark(this.registry.get(type)?.get(name), restoredMetadata); + const stamp = this.environmentRowStamp(restoredMetadata); await dbLoader.registerRollback( type, name, - restoredMetadata, + stamp === undefined ? restoredMetadata : withoutEnvironmentRowStamp(restoredMetadata as Record, stamp), version, options?.changeNote, options?.recordedBy, @@ -4562,7 +4647,6 @@ export class MetadataManager implements IMetadataService { // as the row it was written to is. [S4] One restored by the environment // address is filed under the bare slot, as its row is, even when one // package holds the name (the write rule would file it under that package's). - const slotted = PACKAGE_SLOTTED_STORE_TYPES.has(type); if (slotted && isPackageCaller(address?.packageId)) { this.writeRegistryEntry(type, name, withEntryPackage({ name, data: restoredMetadata, packageId: address.packageId })); } else if (slotted && address !== undefined) { diff --git a/packages/objectql/src/plugin-late-bridge-environment-row.test.ts b/packages/objectql/src/plugin-late-bridge-environment-row.test.ts new file mode 100644 index 00000000000..6113ffb518d --- /dev/null +++ b/packages/objectql/src/plugin-late-bridge-environment-row.test.ts @@ -0,0 +1,229 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#33003] The late-manifest bridge rewrites an environment row the boot pass + * stamped with the host, and the row stays the environment's. + * + * ## The defect + * + * On a host that declares its package and stores metadata in a database, the + * metadata boot pass stamps each stored row naming no package with the host + * (`_packageId`), and ObjectQL owns such an object as the host's. When another + * package extends it, {@link ObjectQLPlugin}'s late-manifest bridge sees the + * metadata service's copy stamped with the owner and re-registers the merged + * object (`ownPreviousCopy`); withdrawing the extender puts the owner's body + * back the same way (`restoreExtendedObjectCopies`). Each write replaced the + * object the boot pass had marked as the environment's own row and stored the + * host stamp in the row's body, so `unregisterPackage(host)` deleted the + * environment's object, in that process and after a restart. + * + * ## Why these parts are real + * + * The bridge and its restore are this plugin's own methods, run over a real + * `ObjectQL` registry (the extender's merge, the owner's stamp) into a real + * `MetadataManager` whose rows a real `DatabaseLoader` reads and writes, primed + * by `MetadataPlugin`'s real boot pass; a second pass over the same store is + * the restart. The metadata-level pins of every writer live in + * `packages/metadata/src/loaders/database-loader.test.ts` (`[#33003]`). + */ + +import { describe, expect, it, vi } from 'vitest'; +import { randomUUID } from 'node:crypto'; +import { DatabaseLoader, MetadataPlugin, type MetadataManager } from '@objectstack/metadata'; +import { ObjectQL } from './engine.js'; +import { ObjectQLPlugin } from './plugin.js'; + +type Stores = Map>>; + +/** In-memory driver, copied from `protocol-delete-boot-hydrated-object-heal.test.ts`; equality-only WHERE. */ +function makeMemoryDriver(stores: Stores) { + const storeFor = (obj: string) => { + let s = stores.get(obj); + if (!s) { s = new Map(); stores.set(obj, s); } + return s; + }; + const matchesWhere = (row: Record, where: any): boolean => { + if (!where || typeof where !== 'object') return true; + for (const [k, v] of Object.entries(where)) { + if (k === '$and' && Array.isArray(v)) { + if (!v.every((w: any) => matchesWhere(row, w))) return false; + continue; + } + if (k === '$or' && Array.isArray(v)) { + if (!v.some((w: any) => matchesWhere(row, w))) return false; + continue; + } + if (k.startsWith('$')) continue; + const rowVal = row[k]; + const expected = (v && typeof v === 'object' && '$eq' in (v as any)) ? (v as any).$eq : v; + const a = rowVal === undefined ? null : rowVal; + const b = expected === undefined ? null : expected; + if (a !== b) return false; + } + return true; + }; + const driver: any = { + name: 'memory', version: '0.0.0', supports: {} as any, + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, + async syncSchema() {}, + async execute() { return null; }, + async find(object: string, ast: any) { + const rows = Array.from(storeFor(object).values()).filter((r) => matchesWhere(r, ast?.where)); + // The caller's bound, after the filter, by presence (`check:objectql-double-limit`). + return typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows; + }, + async findOne(object: string, ast: any) { + for (const r of storeFor(object).values()) if (matchesWhere(r, ast?.where)) return r; + return null; + }, + async create(object: string, data: Record) { + const id = (data.id as string) ?? `r_${randomUUID()}`; + const row = { ...data, id }; + storeFor(object).set(id, row); + return row; + }, + async update(object: string, id: string, data: Record) { + const s = storeFor(object); + const cur = s.get(id); + if (!cur) throw new Error(`not found: ${object}/${id}`); + const updated = { ...cur, ...data, id }; + s.set(id, updated); + return updated; + }, + async upsert(object: string, data: Record) { + const id = data.id as string | undefined; + if (id && storeFor(object).has(id)) return this.update(object, id, data); + return this.create(object, data); + }, + async delete(object: string, id: string) { return storeFor(object).delete(id); }, + async count(object: string, ast: any) { return (await this.find(object, ast)).length; }, + async bulkCreate(object: string, rows: Record[]) { + return Promise.all(rows.map((r) => this.create(object, r))); + }, + async bulkUpdate() { return []; }, async bulkDelete() {}, + async beginTransaction() { return { commit: async () => {}, rollback: async () => {} }; }, + async commit() {}, async rollback() {}, + async dropTable(object: string) { stores.delete(object); }, + }; + return driver; +} + +const HOST = 'com.host.app'; +const EXT = 'com.ext.score'; +const OBJECT = 'env_account'; + +/** An extender whose only content is a field on the environment's object. */ +const extender = () => ({ + id: EXT, + name: EXT, + version: '1.0.0', + type: 'app', + objectExtensions: [{ extend: OBJECT, fields: { ext_score: { name: 'ext_score', label: 'Score', type: 'number' } } }], +}); + +const logger = () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }); + +/** The metadata boot pass over the store, on a host that declares `HOST`. */ +async function bootPass(stores: Stores): Promise { + const plugin = new MetadataPlugin({ packageId: HOST, watch: false, config: { bootstrap: 'eager' } }); + const m = (plugin as any).manager as MetadataManager; + (m as any).loaders.clear(); + m.registerLoader(new DatabaseLoader({ driver: makeMemoryDriver(stores) })); + await (plugin as any)._loadFromFileSystem({ logger: logger() }); + return m; +} + +/** A stored row naming no package, as the environment saved it; `body` may name the host (CONTROL). */ +function seed(stores: Stores, name: string, body: Record = {}) { + const table = new Map>(stores.get('sys_metadata') ?? []); + table.set(`object_${name}`, { + id: `object_${name}`, type: 'object', name, state: 'active', version: 1, checksum: name, source: 'database', + package_id: null, metadata: JSON.stringify({ name, label: 'env', fields: { name: { name: 'name', type: 'text', label: 'Name' } }, ...body }), + }); + stores.set('sys_metadata', table); +} + +/** + * The ObjectQL side: the registry owns each object as the metadata copy's + * stamp names it (ObjectQL registers a copy under `_packageId`), the extender + * is installed, and the bridge and its restore are the plugin's own. + */ +function objectql(m: MetadataManager, names: readonly string[]) { + const engine = new ObjectQL(); + for (const name of names) { + const copy = (m as any).registry.get('object').get(name) as Record; + const { _packageId, ...schema } = copy; + engine.registry.registerObject(schema as any, _packageId as string); + } + engine.registerApp(extender()); + const plugin = new ObjectQLPlugin({ ql: engine }); + (plugin as any).bridgeLateManifests = true; + const ctx = { logger: logger(), getService: (name: string) => { if (name === 'metadata') return m; throw new Error(name); } }; + return { + engine, + bridge: () => (plugin as any).bridgeManifestObjectsToMetadataService(ctx, extender()) as Promise, + restore: async () => { + engine.registry.uninstallPackage(EXT); + await (plugin as any).restoreExtendedObjectCopies(ctx, EXT); + }, + }; +} + +/** Per object: the registry's stamp, its served field names, and how many stored rows it has. */ +async function state(m: MetadataManager, stores: Stores, names: readonly string[]) { + const out: unknown[] = []; + for (const name of names) { + const held = (m as any).registry.get('object')?.get(name) as { _packageId?: string; fields?: object } | undefined; + const rows = [...(stores.get('sys_metadata')?.values() ?? [])].filter((r) => r.type === 'object' && r.name === name); + out.push([name, held?._packageId ?? null, held ? Object.keys(held.fields ?? {}).includes('ext_score') : null, rows.length]); + } + return out; +} + +describe('[#33003] the late-manifest bridge rewrites the environment\'s object the boot pass stamped with the host: unregisterPackage(host) keeps it', () => { + it('the extender bridged (ownPreviousCopy): unregisterPackage(host) keeps the object in this process and after a restart (BEFORE: deleted)', async () => { + const stores: Stores = new Map(); + seed(stores, OBJECT); + const m = await bootPass(stores); + const { bridge } = objectql(m, [OBJECT]); + await bridge(); + // Identity: the bridge rewrote the copy with the merged body, stamped with the owner. + expect(await state(m, stores, [OBJECT])).toEqual([[OBJECT, HOST, true, 1]]); + + const rebooted = await bootPass(stores); + await rebooted.unregisterPackage(HOST); + expect(await state(rebooted, stores, [OBJECT])).toEqual([[OBJECT, HOST, true, 1]]); + await m.unregisterPackage(HOST); + expect(await state(m, stores, [OBJECT])).toEqual([[OBJECT, HOST, true, 1]]); + }); + + it('the extender withdrawn (restoreExtendedObjectCopies): unregisterPackage(host) keeps the restored object in this process and after a restart (BEFORE: deleted)', async () => { + const stores: Stores = new Map(); + seed(stores, OBJECT); + const m = await bootPass(stores); + const { bridge, restore } = objectql(m, [OBJECT]); + await bridge(); + await restore(); + expect(await state(m, stores, [OBJECT])).toEqual([[OBJECT, HOST, false, 1]]); + + const rebooted = await bootPass(stores); + await rebooted.unregisterPackage(HOST); + expect(await state(rebooted, stores, [OBJECT])).toEqual([[OBJECT, HOST, false, 1]]); + await m.unregisterPackage(HOST); + expect(await state(m, stores, [OBJECT])).toEqual([[OBJECT, HOST, false, 1]]); + }); + + it('CONTROL the host\'s own object (its stored body carries the host\'s stamp), bridged and restored the same way, is still removed', async () => { + const stores: Stores = new Map(); + seed(stores, OBJECT, { _packageId: HOST }); + const m = await bootPass(stores); + const { bridge, restore } = objectql(m, [OBJECT]); + await bridge(); + await restore(); + const rebooted = await bootPass(stores); + await rebooted.unregisterPackage(HOST); + expect(await state(rebooted, stores, [OBJECT])).toEqual([[OBJECT, null, null, 0]]); + await m.unregisterPackage(HOST); + expect(await state(m, stores, [OBJECT])).toEqual([[OBJECT, null, null, 0]]); + }); +});