Skip to content

Commit c755f13

Browse files
committed
test(cloud-connection,metadata-protocol): pin the unmanaged seed copy at the door and on publish
Claude-Session: https://claude.ai/code/session_01FEkQ5pQJCx8STEq28nr3Ej Co-Authored-By: Claude <noreply@anthropic.com>
1 parent e6e90d8 commit c755f13

2 files changed

Lines changed: 304 additions & 0 deletions

File tree

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

Lines changed: 276 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -626,3 +626,279 @@ describe('install-local — Q6 after a RENAMED copy: the managed install is admi
626626
expect(h.ledgerHas('com.example.crm')).toBe(false);
627627
});
628628
});
629+
630+
describe('install-local — an unmanaged copy\'s sample data, asked for with `seedSampleData` (#30808)', () => {
631+
type Row = Record<string, unknown> & { id: string };
632+
/** The audit/ownership columns every user-authored object carries. */
633+
const OWNED = { owner_id: { type: 'lookup', reference: 'sys_user' }, created_by: { type: 'lookup', reference: 'sys_user' } };
634+
/** Account ← contact, the contact naming its account by the account's natural key; listed child first. */
635+
const seededCrm = (extra: Record<string, unknown> = {}) => crm({
636+
installModes: BOTH,
637+
objects: [
638+
{ name: 'crm_account', label: 'Account', fields: { name: { type: 'text' }, ...OWNED } },
639+
{ name: 'crm_contact', label: 'Contact', fields: { email: { type: 'text' }, account: { type: 'lookup', reference: 'crm_account' }, ...OWNED } },
640+
],
641+
data: [
642+
{ object: 'crm_contact', externalId: 'email', records: [{ email: 'ada@acme.test', account: 'Acme' }] },
643+
{ object: 'crm_account', externalId: 'name', records: [{ name: 'Acme' }, { name: 'Globex' }] },
644+
],
645+
...extra,
646+
});
647+
648+
/**
649+
* The door over an in-memory data engine the REAL `SeedLoaderService`
650+
* writes through, and a protocol double standing in for the import: it
651+
* registers the copied objects, writes each dataset the door asks for as
652+
* a `seed` item of the new base (the verb's own pins live in
653+
* `@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.
656+
*/
657+
function world() {
658+
const tables: Record<string, Row[]> = {};
659+
const objects = new Map<string, any>();
660+
const packages = new Map<string, { manifest: Record<string, unknown> }>();
661+
const seedItems = new Map<string, Record<string, unknown>>();
662+
const writes: string[] = [];
663+
let nextId = 0;
664+
const known = (object: string) => {
665+
if (!objects.has(object)) throw new Error(`Object '${object}' not found`);
666+
return (tables[object] ??= []);
667+
};
668+
// 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));
671+
const matches = (row: Row, where: Record<string, unknown>) => Object.entries(where).every(([k, v]) => {
672+
if (k.startsWith('$')) throw new Error(`engine double: combinator '${k}' is not implemented`);
673+
if (v === null) return row[k] == null;
674+
if (v && typeof v === 'object') {
675+
const ops = Object.keys(v);
676+
if (ops.length !== 1 || ops[0] !== '$in') throw new Error(`engine double: operator(s) ${ops.join(', ')} not implemented`);
677+
return ((v as { $in: unknown[] }).$in).includes(row[k]);
678+
}
679+
return row[k] === v;
680+
});
681+
const engine: any = {
682+
syncSchemas: vi.fn(async () => undefined),
683+
manifests: new Map(),
684+
getSchema: (name: string) => objects.get(name),
685+
registry: {
686+
getAllPackages: () => [],
687+
getNamespaceOwners: () => [],
688+
getPackage: (id: string) => packages.get(id),
689+
getObject: (name: string) => objects.get(name),
690+
},
691+
async find(object: string, query?: any): Promise<unknown[]> {
692+
const rows = readable(object).filter((row) => matches(row, query?.where ?? {}));
693+
return (typeof query?.limit === 'number' ? rows.slice(0, query.limit) : rows).map((row) => ({ ...row }));
694+
},
695+
// One record, or the batch the loader inserts a dataset in.
696+
async insert(object: string, record: Record<string, unknown> | Record<string, unknown>[]): Promise<Row | Row[]> {
697+
const one = (r: Record<string, unknown>) => {
698+
const row = { ...r, id: `r${++nextId}` } as Row;
699+
known(object).push(row);
700+
writes.push(`insert ${object}`);
701+
return { ...row };
702+
};
703+
return Array.isArray(record) ? record.map(one) : one(record);
704+
},
705+
async update(object: string, data: Record<string, unknown>, options: any) {
706+
let n = 0;
707+
for (const row of known(object)) {
708+
if (!matches(row, options?.where ?? {})) continue;
709+
Object.assign(row, data);
710+
n += 1;
711+
}
712+
return n;
713+
},
714+
async delete(object: string, options?: any): Promise<boolean> {
715+
const id = String(options?.where?.id ?? '');
716+
const table = known(object);
717+
const at = table.findIndex((r) => r.id === id);
718+
if (at < 0) return false;
719+
table.splice(at, 1);
720+
writes.push(`delete ${object}`);
721+
return true;
722+
},
723+
};
724+
const importUnmanagedPackage = vi.fn(async (request: any) => {
725+
const source = request.manifest;
726+
const targetPackageId = `${source.id}-copy`;
727+
if (packages.has(targetPackageId)) {
728+
throw Object.assign(new Error(`Package '${targetPackageId}' already exists.`), {
729+
code: 'RESOURCE_CONFLICT', status: 409, details: { targetPackageId },
730+
});
731+
}
732+
packages.set(targetPackageId, { manifest: { id: targetPackageId, namespace: source.namespace } });
733+
const copied: Array<{ type: string; name: string }> = [];
734+
for (const o of source.objects ?? []) {
735+
objects.set(o.name, o);
736+
copied.push({ type: 'object', name: o.name });
737+
}
738+
if (request.seedData === true) {
739+
for (const d of source.data ?? []) {
740+
const name = `${d.object}_seed`;
741+
seedItems.set(name, { ...d, _packageId: targetPackageId });
742+
copied.push({ type: 'seed', name });
743+
}
744+
}
745+
return { sourcePackageId: source.id, targetPackageId, namespace: source.namespace, copiedCount: copied.length, copied, strippedLocks: [] };
746+
});
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+
}));
753+
754+
async function boot() {
755+
const routes = new Map<string, Handler>();
756+
const rawApp = {
757+
get: (p: string, h: Handler) => routes.set(`GET ${p}`, h),
758+
post: (p: string, h: Handler) => routes.set(`POST ${p}`, h),
759+
delete: (p: string, h: Handler) => routes.set(`DELETE ${p}`, h),
760+
};
761+
const hooks = new Map<string, any>();
762+
const register = vi.fn(async () => undefined);
763+
const services: Record<string, any> = {
764+
manifest: { register },
765+
auth: installerAuthService(INSTALLER),
766+
objectql: withInstallerGrants(engine, INSTALLER),
767+
metadata: { getObject: async (name: string) => objects.get(name) },
768+
protocol: { importUnmanagedPackage, getMetaItems },
769+
};
770+
const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() };
771+
const ctx = {
772+
hook: (e: string, h: any) => hooks.set(e, h),
773+
getService: (name: string) => {
774+
if (name === 'http-server') return { getRawApp: () => rawApp };
775+
const svc = services[name];
776+
if (svc === undefined) throw new Error(`no ${name}`);
777+
return svc;
778+
},
779+
registerService: (name: string, svc: unknown) => { services[name] = svc; },
780+
logger,
781+
};
782+
const plugin = new MarketplaceInstallLocalPlugin({ controlPlaneUrl: 'off', storageDir: dir });
783+
await plugin.start(ctx as any);
784+
await hooks.get('kernel:ready')?.();
785+
register.mockClear();
786+
const purgeC = (manifestId: string) => ({ ...makeC(undefined), req: { ...makeC(undefined).req, param: (k: string) => (k === 'manifestId' ? manifestId : undefined) } });
787+
return {
788+
install: (body: unknown) => routes.get(`POST ${ROUTE}`)!(makeC(body)),
789+
purge: (manifestId: string) => routes.get(`POST ${ROUTE}/:manifestId/purge-sample-data`)!(purgeC(manifestId)),
790+
register,
791+
logger,
792+
};
793+
}
794+
return { tables, writes, seedItems, packages, importUnmanagedPackage, getMetaItems, boot };
795+
}
796+
797+
it('off by default: the import is not asked for the sample data, no row lands, and the answer says it was skipped', async () => {
798+
const w = world();
799+
const h = await w.boot();
800+
const res = await h.install({ manifest: seededCrm(), installMode: 'unmanaged' });
801+
expect(res.status, JSON.stringify(res.payload)).toBe(200);
802+
expect(w.importUnmanagedPackage.mock.calls[0]![0]).not.toHaveProperty('seedData');
803+
expect(res.payload.data.seeded).toEqual({
804+
mode: 'skipped',
805+
reason: 'an unmanaged install copies metadata, not data: the package\'s sample data was not loaded',
806+
});
807+
expect(w.seedItems.size).toBe(0);
808+
expect(w.writes).toEqual([]);
809+
});
810+
811+
it('asked for: the rows land from the stored seed items, owned by the installer, the lookup resolved in load order', async () => {
812+
const w = world();
813+
const h = await w.boot();
814+
const res = await h.install({ manifest: seededCrm(), installMode: 'unmanaged', seedSampleData: true });
815+
expect(res.status, JSON.stringify(res.payload)).toBe(200);
816+
expect(w.importUnmanagedPackage.mock.calls[0]![0]).toMatchObject({ seedData: true, actor: INSTALLER });
817+
expect(res.payload.data.seeded).toEqual({ mode: 'inline', inserted: 3, updated: 0, skipped: 0, errors: 0 });
818+
const acme = w.tables.crm_account!.find((r) => r.name === 'Acme')!;
819+
expect(w.tables.crm_account!.map((r) => r.name).sort()).toEqual(['Acme', 'Globex']);
820+
// The contact's `account: 'Acme'` is the parent row's id: the account dataset loaded first.
821+
expect(w.tables.crm_contact).toEqual([expect.objectContaining({ email: 'ada@acme.test', account: acme.id })]);
822+
for (const row of [...w.tables.crm_account!, ...w.tables.crm_contact!]) {
823+
expect({ owner_id: row.owner_id, created_by: row.created_by }).toEqual({ owner_id: INSTALLER, created_by: INSTALLER });
824+
}
825+
// Nothing is ledgered or registered under the package's id.
826+
expect(h.register).not.toHaveBeenCalled();
827+
expect(new LocalManifestSource(dir).read('com.example.crm').entry).toBeNull();
828+
});
829+
830+
it('the purge of the copy\'s base deletes exactly the sample rows; a row the customer wrote in a seeded object stays', async () => {
831+
const w = world();
832+
const h = await w.boot();
833+
await h.install({ manifest: seededCrm(), installMode: 'unmanaged', seedSampleData: true });
834+
w.tables.crm_account!.push({ id: 'u1', name: 'Initech', owner_id: INSTALLER });
835+
const res = await h.purge('com.example.crm-copy');
836+
expect(res.status, JSON.stringify(res.payload)).toBe(200);
837+
expect(res.payload).toEqual({
838+
success: true,
839+
data: { manifestId: 'com.example.crm-copy', deleted: 3, skipped: 0, errors: 0, withSampleData: false },
840+
});
841+
expect(w.tables.crm_account!.map((r) => r.id)).toEqual(['u1']);
842+
expect(w.tables.crm_contact).toEqual([]);
843+
// The receipt stays: a second purge finds nothing left to delete.
844+
const again = await h.purge('com.example.crm-copy');
845+
expect(again.payload.data).toMatchObject({ deleted: 0, skipped: 3, errors: 0 });
846+
});
847+
848+
it('a restart after the copy, and after the purge, re-inserts nothing', async () => {
849+
const w = world();
850+
const first = await w.boot();
851+
await first.install({ manifest: seededCrm(), installMode: 'unmanaged', seedSampleData: true });
852+
const loaded = w.writes.length;
853+
await w.boot();
854+
expect(w.writes.length).toBe(loaded);
855+
const third = await w.boot();
856+
await third.purge('com.example.crm-copy');
857+
const purged = w.writes.length;
858+
await w.boot();
859+
expect(w.writes.length).toBe(purged);
860+
expect(w.tables.crm_account).toEqual([]);
861+
});
862+
863+
it('a re-run is refused 409 by the import before anything is loaded again', async () => {
864+
const w = world();
865+
const h = await w.boot();
866+
await h.install({ manifest: seededCrm(), installMode: 'unmanaged', seedSampleData: true });
867+
const before = w.writes.length;
868+
const res = await h.install({ manifest: seededCrm(), installMode: 'unmanaged', seedSampleData: true });
869+
expect(res.status).toBe(409);
870+
expect(res.payload.error.code).toBe('RESOURCE_CONFLICT');
871+
expect(w.writes.length).toBe(before);
872+
});
873+
874+
it('`seedSampleData` that is not a boolean, or beside a managed install: 400 INVALID_REQUEST, nothing imported or registered', async () => {
875+
for (const body of [
876+
{ manifest: seededCrm(), installMode: 'unmanaged', seedSampleData: 'yes' },
877+
{ manifest: seededCrm(), seedSampleData: true },
878+
{ manifest: seededCrm(), installMode: 'managed', seedSampleData: false },
879+
]) {
880+
const w = world();
881+
const h = await w.boot();
882+
const res = await h.install(body);
883+
expect(res.status, JSON.stringify(body)).toBe(400);
884+
expect(res.payload.error.code).toBe('INVALID_REQUEST');
885+
expect(res.payload.error.message).toContain('seedSampleData');
886+
expect(w.importUnmanagedPackage).not.toHaveBeenCalled();
887+
expect(h.register).not.toHaveBeenCalled();
888+
expect(w.writes).toEqual([]);
889+
}
890+
});
891+
892+
it('the purge of an id that is no installed base still answers 404; an unreadable receipt answers 503 and deletes nothing', async () => {
893+
const w = world();
894+
const h = await w.boot();
895+
expect((await h.purge('com.example.nothing')).status).toBe(404);
896+
await h.install({ manifest: seededCrm(), installMode: 'unmanaged', seedSampleData: true });
897+
w.getMetaItems.mockRejectedValueOnce(new Error('sys_metadata is unreachable'));
898+
const before = w.writes.length;
899+
const res = await h.purge('com.example.crm-copy');
900+
expect(res.status).toBe(503);
901+
expect(res.payload.error.code).toBe('SERVICE_UNAVAILABLE');
902+
expect(w.writes.length).toBe(before);
903+
});
904+
});

‎packages/metadata-protocol/src/package-unmanaged-install.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1289,6 +1289,34 @@ describe('the sample data, copied when the door asks — the seed receipt (#3080
12891289
});
12901290

12911291

1292+
it('a copied seed item is an environment seed item like any other: re-saved, or drafted and published, it loads no row twice', async () => {
1293+
const { protocol, table, writes } = makeProtocol();
1294+
await protocol.importUnmanagedPackage({ manifest: seededBody(), seedData: true });
1295+
// The install's one organization, and the rows the install door loaded
1296+
// from the receipt (`seedSampleData`) under it.
1297+
table('sys_organization').push({ id: 'org_1', name: 'Acme Corp' });
1298+
table('crm_account').push(
1299+
{ id: 'a1', title: 'Acme', organization_id: 'org_1' },
1300+
{ id: 'a2', title: 'crm_lead', organization_id: 'org_1' },
1301+
);
1302+
const stored = seedRows(table).find((r) => r.name === 'crm_account_seed')!.body;
1303+
const inserts = () => writes.filter((w) => w.op === 'insert' && w.table === 'crm_account').length;
1304+
1305+
// A plain save of the item writes metadata only: a seed is applied when it is PUBLISHED.
1306+
await protocol.saveMetaItem({ type: 'seed', name: 'crm_account_seed', item: stored, mode: 'publish', packageId: 'com.example.crm-copy' });
1307+
expect(inserts()).toBe(0);
1308+
1309+
// Drafted and published, it is applied — create-only (`ignore`, the spec default): every record already has its row.
1310+
await protocol.saveMetaItem({ type: 'seed', name: 'crm_account_seed', item: stored, mode: 'draft', packageId: 'com.example.crm-copy' });
1311+
const published = await protocol.publishPackageDrafts({ packageId: 'com.example.crm-copy' });
1312+
expect(published.seedApplied).toMatchObject({
1313+
success: true, inserted: 0, updated: 0,
1314+
landed: [{ object: 'crm_account', inserted: { total: 0 }, matched: { ids: ['a1', 'a2'], total: 2 } }],
1315+
});
1316+
expect(inserts()).toBe(0);
1317+
expect(table('crm_account').map((r) => r.title)).toEqual(['Acme', 'crm_lead']);
1318+
});
1319+
12921320
it('`seedData` is the door\'s, never the published request\'s: the declaration still refuses an undeclared key', async () => {
12931321
const { protocol } = makeProtocol();
12941322
const err = await refusalOf(() => protocol.importUnmanagedPackage({ manifest: seededBody(), withSampleData: true }));

0 commit comments

Comments
 (0)