Skip to content

Commit 4e87db6

Browse files
committed
fix(cloud-connection): read the unmanaged copy's seed receipt by name, pinned on a real boot
The list read serves no stored seed item (a seed body has no name), so the receipt is read item by item through the by-name read: the names come from the import's answer on install, and from the base's active seed rows on purge. Claude-Session: https://claude.ai/code/session_01FEkQ5pQJCx8STEq28nr3Ej Co-Authored-By: Claude <noreply@anthropic.com>
1 parent c755f13 commit 4e87db6

4 files changed

Lines changed: 288 additions & 48 deletions

File tree

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@objectstack/cloud-connection': patch
3+
'@objectstack/metadata-protocol': patch
4+
---
5+
6+
feat(cloud-connection,metadata-protocol): an unmanaged install can copy the package's sample data, when asked (`seedSampleData: true`), owned by the installer and purged by its seed receipt
7+
8+
Clause-②: yes (widening)
9+
Metadata-protocol: none
10+
11+
- **`POST /marketplace/install-local` accepts `seedSampleData`** beside `installMode: 'unmanaged'`. It is off by default: without it an unmanaged copy loads no row, as before, and answers the same `seeded: { mode: 'skipped' }`. With `true`, the copy loads the package's `data` datasets once, inline, and answers `seeded: { mode: 'inline', inserted, updated, skipped, errors }` beside `copied`. Every row is owned by the person who installed it (`owner_id` and `created_by`); rows the package wrote under several personas all land under that one owner. Lookups between the copied rows resolve in load order, exactly as on a managed install, and a dataset's `files` map is loaded as on a managed install too (each row's `sys_file` is minted). `seedSampleData` that is not a boolean, or one sent with a managed install (which always loads its data), answers 400 `INVALID_REQUEST` before anything is written.
12+
- **The seed receipt.** The copy writes each dataset as a `seed` item of the new base (`<object>_seed`, then `<object>_seed_2` for a second dataset of the same object), in the environment's own metadata. Under `targetNamespace` only the dataset's `object` follows the rename; its records and `externalId` are copied verbatim, so the values a lookup or a purge matches never change. A dataset the copy cannot write (no `object`, no `records` array) is refused with 400 before any write, and a `seed` item the save door refuses rolls the whole copy back, as every other copied item does. A re-run is still refused with 409.
13+
- **`POST /marketplace/install-local/:id/purge-sample-data` on a copy** reads that receipt and deletes exactly the rows it names, matched by `externalId` (a row the person wrote survives). A receipt that cannot be read answers 503 and deletes nothing. Purge before uninstalling the copy: an uninstall removes the receipt with the base, and leaves the rows.
14+
- **`importUnmanagedPackage`** (metadata-protocol) takes the door-stated `seedData: true`, read off before the request is parsed, like `actor`. The published `ImportUnmanagedPackageRequestSchema` is unchanged.
15+
16+
A boot never applies the receipt, so a restart after the copy or after the purge inserts no row; a copied `seed` item saved or published later behaves as every environment `seed` item does (create-only, matched by `externalId`).

‎packages/cloud-connection/src/marketplace-install-local-install-modes.test.ts‎

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -651,23 +651,25 @@ describe('install-local — an unmanaged copy\'s sample data, asked for with `se
651651
* registers the copied objects, writes each dataset the door asks for as
652652
* a `seed` item of the new base (the verb's own pins live in
653653
* `@objectstack/metadata-protocol`'s `package-unmanaged-install.test.ts`),
654-
* and serves them back through `getMetaItems`. `tables` and `seedItems`
655-
* outlive a mount, so a second mount is a restart over the same database.
654+
* (a `sys_metadata` row of the base, as the store holds it), and serves
655+
* each back through the by-name `getMetaItem`. `tables` outlives a mount,
656+
* so a second mount is a restart over the same database.
656657
*/
657658
function world() {
658659
const tables: Record<string, Row[]> = {};
659660
const objects = new Map<string, any>();
660661
const packages = new Map<string, { manifest: Record<string, unknown> }>();
661-
const seedItems = new Map<string, Record<string, unknown>>();
662662
const writes: string[] = [];
663663
let nextId = 0;
664664
const known = (object: string) => {
665665
if (!objects.has(object)) throw new Error(`Object '${object}' not found`);
666666
return (tables[object] ??= []);
667667
};
668668
// The platform tables the loader probes (`sys_organization`, the landed-key
669-
// ledger) hold no row here; every other unknown object is refused.
670-
const readable = (object: string) => (object.startsWith('sys_') && !objects.has(object) ? [] : known(object));
669+
// ledger) hold no row here, `sys_metadata` holds the seed receipt; every
670+
// other unknown object is refused.
671+
const readable = (object: string) => (object.startsWith('sys_') && !objects.has(object) ? (tables[object] ?? []) : known(object));
672+
const seedRows = () => (tables.sys_metadata ?? []).filter((row) => row.type === 'seed');
671673
const matches = (row: Row, where: Record<string, unknown>) => Object.entries(where).every(([k, v]) => {
672674
if (k.startsWith('$')) throw new Error(`engine double: combinator '${k}' is not implemented`);
673675
if (v === null) return row[k] == null;
@@ -738,18 +740,19 @@ describe('install-local — an unmanaged copy\'s sample data, asked for with `se
738740
if (request.seedData === true) {
739741
for (const d of source.data ?? []) {
740742
const name = `${d.object}_seed`;
741-
seedItems.set(name, { ...d, _packageId: targetPackageId });
743+
(tables.sys_metadata ??= []).push({
744+
id: `m${++nextId}`, type: 'seed', name, package_id: targetPackageId, state: 'active', metadata: { ...d },
745+
} as Row);
742746
copied.push({ type: 'seed', name });
743747
}
744748
}
745749
return { sourcePackageId: source.id, targetPackageId, namespace: source.namespace, copiedCount: copied.length, copied, strippedLocks: [] };
746750
});
747-
const getMetaItems = vi.fn(async ({ type, packageId }: { type: string; packageId?: string }) => ({
748-
type,
749-
items: type !== 'seed' ? [] : [...seedItems.values()]
750-
.filter((b) => !packageId || b._packageId === packageId)
751-
.map((b) => ({ ...b, _diagnostics: { valid: true } })),
752-
}));
751+
const getMetaItem = vi.fn(async ({ type, name, packageId }: { type: string; name: string; packageId?: string }) => {
752+
const row: any = (tables.sys_metadata ?? []).find((r) => r.type === type && r.name === name && (!packageId || r.package_id === packageId));
753+
if (!row) throw Object.assign(new Error(`${type} '${name}' not found`), { code: 'NOT_FOUND', status: 404 });
754+
return { type, name, item: { ...row.metadata, _packageId: row.package_id }, lock: 'none', editable: true };
755+
});
753756

754757
async function boot() {
755758
const routes = new Map<string, Handler>();
@@ -765,7 +768,7 @@ describe('install-local — an unmanaged copy\'s sample data, asked for with `se
765768
auth: installerAuthService(INSTALLER),
766769
objectql: withInstallerGrants(engine, INSTALLER),
767770
metadata: { getObject: async (name: string) => objects.get(name) },
768-
protocol: { importUnmanagedPackage, getMetaItems },
771+
protocol: { importUnmanagedPackage, getMetaItem },
769772
};
770773
const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() };
771774
const ctx = {
@@ -791,7 +794,7 @@ describe('install-local — an unmanaged copy\'s sample data, asked for with `se
791794
logger,
792795
};
793796
}
794-
return { tables, writes, seedItems, packages, importUnmanagedPackage, getMetaItems, boot };
797+
return { tables, writes, seedRows, packages, importUnmanagedPackage, getMetaItem, boot };
795798
}
796799

797800
it('off by default: the import is not asked for the sample data, no row lands, and the answer says it was skipped', async () => {
@@ -804,7 +807,7 @@ describe('install-local — an unmanaged copy\'s sample data, asked for with `se
804807
mode: 'skipped',
805808
reason: 'an unmanaged install copies metadata, not data: the package\'s sample data was not loaded',
806809
});
807-
expect(w.seedItems.size).toBe(0);
810+
expect(w.seedRows()).toEqual([]);
808811
expect(w.writes).toEqual([]);
809812
});
810813

@@ -894,7 +897,7 @@ describe('install-local — an unmanaged copy\'s sample data, asked for with `se
894897
const h = await w.boot();
895898
expect((await h.purge('com.example.nothing')).status).toBe(404);
896899
await h.install({ manifest: seededCrm(), installMode: 'unmanaged', seedSampleData: true });
897-
w.getMetaItems.mockRejectedValueOnce(new Error('sys_metadata is unreachable'));
900+
w.getMetaItem.mockRejectedValueOnce(new Error('sys_metadata is unreachable'));
898901
const before = w.writes.length;
899902
const res = await h.purge('com.example.crm-copy');
900903
expect(res.status).toBe(503);

‎packages/cloud-connection/src/marketplace-install-local-plugin.ts‎

Lines changed: 67 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -859,14 +859,25 @@ type UnmanagedImporter = {
859859
};
860860

861861
/**
862-
* [#30808] The protocol's list read, asked for an unmanaged copy's seed
863-
* receipt — typed from the producer's own method, asked as a capability
864-
* question at the call site, as {@link UnmanagedImporter} is.
862+
* [#30808] The protocol's by-name read, asked for each item of an unmanaged
863+
* copy's seed receipt — typed from the producer's own method, asked as a
864+
* capability question at the call site, as {@link UnmanagedImporter} is.
865+
*
866+
* Not the list read: a `seed` body declares no `name` (`SeedSchema` is
867+
* closed and has none), and the list keys every stored item by its body's
868+
* `name`, so `getMetaItems({ type: 'seed' })` serves no stored seed item at
869+
* all. The by-name read serves each one.
865870
*/
866871
type UnmanagedCopySeedReader = {
867-
getMetaItems?: ObjectStackProtocolImplementation['getMetaItems'];
872+
getMetaItem?: ObjectStackProtocolImplementation['getMetaItem'];
868873
};
869874

875+
/**
876+
* [#30808] The store read that names the seed items an unmanaged copy's base
877+
* holds, for a purge, which has no import answer to name them from.
878+
*/
879+
type UnmanagedCopySeedNameStore = Pick<IObjectQLEngine, 'find'>;
880+
870881
/**
871882
* [#30808] The metadata type an unmanaged copy's seed receipt is stored as:
872883
* `seed`, the registry's seed-data type (`DEFAULT_METADATA_TYPE_REGISTRY`),
@@ -4717,42 +4728,65 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
47174728
* holds in the environment ledger — what the import wrote when the install
47184729
* asked for the sample data ({@link installUnmanaged}) — each projected to
47194730
* the dataset it declares (the members `SeedSchema` declares, so the
4720-
* served envelope's `_packageId` / `_diagnostics` never reach the loader).
4731+
* served envelope's keys never reach the loader).
47214732
*
4722-
* Read through the protocol's own list, scoped to the base. `datasets` is
4723-
* empty when the base holds no seed item; `failure` says why the receipt
4724-
* could not be read at all, never folded into "no sample data".
4733+
* `names` are the receipt's item names: the import's own answer on an
4734+
* install, or {@link unmanagedCopySeedNames} on a purge. Each body is read
4735+
* through the protocol's by-name read, scoped to the base. `failure` says
4736+
* why the receipt could not be read whole — an item that is not served, or
4737+
* not a dataset, fails it — and is never folded into "no sample data".
47254738
*/
47264739
private readUnmanagedCopySeedReceipt = async (
47274740
ctx: PluginContext,
47284741
packageId: string,
4742+
names: readonly string[],
47294743
): Promise<{ datasets: PurgeSeedDataset[]; failure?: undefined } | { datasets?: undefined; failure: string }> => {
47304744
let protocol: UnmanagedCopySeedReader | undefined;
47314745
try { protocol = ctx.getService<UnmanagedCopySeedReader>('protocol'); } catch { /* no protocol service */ }
4732-
if (!protocol || typeof protocol.getMetaItems !== 'function') {
4746+
if (!protocol || typeof protocol.getMetaItem !== 'function') {
47334747
return { failure: 'the metadata protocol is not available on this runtime' };
47344748
}
4735-
let answer: unknown;
4736-
try {
4737-
answer = await protocol.getMetaItems({ type: UNMANAGED_COPY_SEED_TYPE, packageId });
4738-
} catch (err: any) {
4739-
return { failure: `the base's seed items could not be read: ${err?.message ?? err}` };
4740-
}
4741-
const listed: unknown[] = Array.isArray((answer as { items?: unknown } | null)?.items)
4742-
? (answer as { items: unknown[] }).items
4743-
: [];
47444749
const datasets: PurgeSeedDataset[] = [];
4745-
for (const entry of listed) {
4746-
const body = isPlainObject((entry as { item?: unknown } | null)?.item) ? (entry as { item: unknown }).item : entry;
4747-
if (!isPlainObject(body)) continue;
4748-
// Scoped to the base: an entry another package holds is never its receipt.
4749-
if (typeof body._packageId === 'string' && body._packageId !== packageId) continue;
4750-
const dataset = seedDatasetOfReceiptItem(body);
4751-
if (dataset) datasets.push(dataset);
4750+
for (const name of names) {
4751+
let answer: unknown;
4752+
try {
4753+
answer = await protocol.getMetaItem({ type: UNMANAGED_COPY_SEED_TYPE, name, packageId });
4754+
} catch (err: any) {
4755+
return { failure: `the seed item '${name}' of the base '${packageId}' could not be read: ${err?.message ?? err}` };
4756+
}
4757+
const dataset = seedDatasetOfReceiptItem((answer as { item?: unknown } | null)?.item);
4758+
if (!dataset) return { failure: `the base '${packageId}' serves no dataset under the seed item '${name}'` };
4759+
datasets.push(dataset);
47524760
}
47534761
return { datasets };
47544762
};
47554763

4764+
/**
4765+
* [#30808] The names of the `seed` items an unmanaged copy's base holds —
4766+
* its active rows in the environment's metadata store, read as the system
4767+
* (the purge door already authorized the caller). Only the names: each
4768+
* body is read through the protocol ({@link readUnmanagedCopySeedReceipt}).
4769+
*/
4770+
private unmanagedCopySeedNames = async (
4771+
ctx: PluginContext,
4772+
packageId: string,
4773+
): Promise<{ names: string[]; failure?: undefined } | { names?: undefined; failure: string }> => {
4774+
let store: UnmanagedCopySeedNameStore | undefined;
4775+
try { store = ctx.getService<UnmanagedCopySeedNameStore>('objectql'); } catch { /* no data engine */ }
4776+
if (!store || typeof store.find !== 'function') return { failure: 'the data engine is not available on this runtime' };
4777+
try {
4778+
const rows = await store.find('sys_metadata', {
4779+
where: { type: UNMANAGED_COPY_SEED_TYPE, package_id: packageId, state: 'active' },
4780+
fields: ['name'],
4781+
context: { isSystem: true },
4782+
});
4783+
const list: unknown[] = Array.isArray(rows) ? rows : Array.isArray((rows as any)?.records) ? (rows as any).records : [];
4784+
return { names: [...new Set(list.map((row: any) => row?.name).filter((n): n is string => typeof n === 'string'))] };
4785+
} catch (err: any) {
4786+
return { failure: `the base's seed items could not be listed: ${err?.message ?? err}` };
4787+
}
4788+
};
4789+
47564790
/**
47574791
* [#30808 · #30324 option C · #30680 answer A] The rows of an unmanaged
47584792
* copy's sample data, loaded from the seed receipt the import just wrote
@@ -4776,12 +4810,11 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
47764810
): Promise<{ mode: 'inline' | 'skipped' | 'refused'; inserted?: number; updated?: number; skipped?: number; errors?: number; reason?: string; errorSample?: string }> => {
47774811
const { manifest, targetPackageId, copied, userId } = args;
47784812
const appId = String(manifest?.id ?? targetPackageId);
4779-
const receiptCount = copied.filter((item) => item.type === UNMANAGED_COPY_SEED_TYPE).length;
4780-
if (receiptCount === 0) return { mode: 'skipped', reason: 'no-datasets' };
4781-
const receipt = await this.readUnmanagedCopySeedReceipt(ctx, targetPackageId);
4782-
if (receipt.failure !== undefined || receipt.datasets.length !== receiptCount) {
4783-
const reason = receipt.failure
4784-
?? `the base '${targetPackageId}' serves ${receipt.datasets.length} of the ${receiptCount} seed item(s) the copy wrote`;
4813+
const receiptNames = copied.filter((item) => item.type === UNMANAGED_COPY_SEED_TYPE).map((item) => item.name);
4814+
if (receiptNames.length === 0) return { mode: 'skipped', reason: 'no-datasets' };
4815+
const receipt = await this.readUnmanagedCopySeedReceipt(ctx, targetPackageId, receiptNames);
4816+
if (receipt.failure !== undefined) {
4817+
const reason = receipt.failure;
47854818
ctx.logger?.warn?.(`[MarketplaceInstallLocal] ${appId}: the unmanaged copy's sample data was not loaded — ${reason}`);
47864819
return { mode: 'skipped', reason: `seed-receipt-unread: ${reason}` };
47874820
}
@@ -5442,7 +5475,9 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
54425475
let ql: NamespaceHoldingEngine | undefined;
54435476
try { ql = ctx.getService<NamespaceHoldingEngine>('objectql'); } catch { return null; /* no data engine — no base */ }
54445477
if (!ql?.registry?.getPackage?.(packageId) || !isWritablePackage(ql, packageId)) return null;
5445-
const receipt = await this.readUnmanagedCopySeedReceipt(ctx, packageId);
5478+
const listed = await this.unmanagedCopySeedNames(ctx, packageId);
5479+
if (listed.failure !== undefined) return { failure: listed.failure };
5480+
const receipt = await this.readUnmanagedCopySeedReceipt(ctx, packageId, listed.names);
54465481
return receipt.failure !== undefined ? { failure: receipt.failure } : { datasets: receipt.datasets };
54475482
};
54485483

0 commit comments

Comments
 (0)