Skip to content

Commit 7c35c69

Browse files
committed
fix(cloud-connection): purge reaches only the unmanaged copies this door made
A door-private record of each copy (beside the install ledger, removed by an uninstall cleanup) is now what lets the purge reach a base without a ledger entry; every other writable base keeps the 404. A copy made without sample data says so. Pins for a save after a purge, a publish after a purge, and a dataset that carries files. Claude-Session: https://claude.ai/code/session_01FEkQ5pQJCx8STEq28nr3Ej Co-Authored-By: Claude <noreply@anthropic.com>
1 parent da697f3 commit 7c35c69

5 files changed

Lines changed: 358 additions & 22 deletions

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

Lines changed: 86 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
*/
2828

2929
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
30-
import { mkdtempSync, rmSync } from 'node:fs';
30+
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
3131
import { join } from 'node:path';
3232
import { tmpdir } from 'node:os';
3333
// The runtime binder the door's step 1d loads lazily — paid here, at module
@@ -751,6 +751,7 @@ describe('install-local — an unmanaged copy\'s sample data, asked for with `se
751751
}
752752
return { sourcePackageId: source.id, targetPackageId, namespace: source.namespace, copiedCount: copied.length, copied, strippedLocks: [] };
753753
});
754+
const cleanups = new Map<string, (args: { packageId: string }) => Promise<{ success: boolean; removed: number; error?: string }>>();
754755
const getMetaItem = vi.fn(async ({ type, name, packageId }: { type: string; name: string; packageId?: string }) => {
755756
const row: any = (tables.sys_metadata ?? []).find((r) => r.type === type && r.name === name && (!packageId || r.package_id === packageId));
756757
if (!row) throw Object.assign(new Error(`${type} '${name}' not found`), { code: 'NOT_FOUND', status: 404 });
@@ -771,7 +772,10 @@ describe('install-local — an unmanaged copy\'s sample data, asked for with `se
771772
auth: installerAuthService(INSTALLER),
772773
objectql: withInstallerGrants(engine, INSTALLER),
773774
metadata: { getObject: async (name: string) => objects.get(name) },
774-
protocol: { importUnmanagedPackage, getMetaItem },
775+
protocol: {
776+
importUnmanagedPackage, getMetaItem,
777+
registerUninstallCleanup: (name: string, cleanup: any) => { cleanups.set(name, cleanup); },
778+
},
775779
};
776780
const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() };
777781
const ctx = {
@@ -797,7 +801,7 @@ describe('install-local — an unmanaged copy\'s sample data, asked for with `se
797801
logger,
798802
};
799803
}
800-
return { tables, writes, seedRows, packages, importUnmanagedPackage, getMetaItem, boot };
804+
return { tables, writes, seedRows, packages, importUnmanagedPackage, getMetaItem, cleanups, boot };
801805
}
802806

803807
it('off by default: the import is not asked for the sample data, no row lands, and the answer says it was skipped', async () => {
@@ -907,4 +911,83 @@ describe('install-local — an unmanaged copy\'s sample data, asked for with `se
907911
expect(res.payload.error.code).toBe('SERVICE_UNAVAILABLE');
908912
expect(w.writes.length).toBe(before);
909913
});
914+
915+
// ── [#30808] The door's record of the copies it made: the purge reaches those bases and no other ──
916+
917+
const COPY_RECORD = () => join(dir, 'unmanaged-copies', 'com.example.crm-copy.json');
918+
919+
it('a Studio-authored writable base with published seed items is refused at purge: 404, nothing deleted', async () => {
920+
const w = world();
921+
const h = await w.boot();
922+
// The copy registers the objects; its own rows are the customer's from here on.
923+
await h.install({ manifest: seededCrm(), installMode: 'unmanaged', seedSampleData: true });
924+
// A base the Studio authored: writable, installed, with a published `seed`
925+
// item whose records name rows that exist — everything the receipt read
926+
// would match, and no record of this door's.
927+
w.packages.set('com.example.studio', { manifest: { id: 'com.example.studio', namespace: 'studio' } });
928+
w.tables.sys_metadata!.push({
929+
id: 'studio-seed', type: 'seed', name: 'crm_account_seed', package_id: 'com.example.studio', state: 'active',
930+
metadata: { object: 'crm_account', externalId: 'name', records: [{ name: 'Acme' }] },
931+
} as Row);
932+
const before = w.writes.length;
933+
const rows = w.tables.crm_account!.length;
934+
const res = await h.purge('com.example.studio');
935+
expect(res.status, JSON.stringify(res.payload)).toBe(404);
936+
expect(res.payload.error.code).toBe('RESOURCE_NOT_FOUND');
937+
expect(w.writes.length).toBe(before);
938+
expect(w.tables.crm_account!.length).toBe(rows);
939+
});
940+
941+
it('a copy made before the record existed is not reached: no record, 404, nothing deleted', async () => {
942+
const w = world();
943+
const h = await w.boot();
944+
await h.install({ manifest: seededCrm(), installMode: 'unmanaged', seedSampleData: true });
945+
expect(existsSync(COPY_RECORD())).toBe(true);
946+
rmSync(join(dir, 'unmanaged-copies'), { recursive: true, force: true });
947+
const before = w.writes.length;
948+
const rows = w.tables.crm_account!.length;
949+
const res = await h.purge('com.example.crm-copy');
950+
expect(res.status, JSON.stringify(res.payload)).toBe(404);
951+
expect(w.writes.length).toBe(before);
952+
expect(w.tables.crm_account!.length).toBe(rows);
953+
});
954+
955+
it('the record sits beside the ledger, never read as an install entry; an unreadable record answers 503 and deletes nothing', async () => {
956+
const w = world();
957+
const h = await w.boot();
958+
await h.install({ manifest: seededCrm(), installMode: 'unmanaged', seedSampleData: true });
959+
expect(JSON.parse(readFileSync(COPY_RECORD(), 'utf8'))).toMatchObject({
960+
baseId: 'com.example.crm-copy', sourcePackageId: 'com.example.crm', seeded: true, copiedBy: INSTALLER,
961+
});
962+
const listing = new LocalManifestSource(dir).list();
963+
expect([listing.entries, listing.skipped]).toEqual([[], []]);
964+
writeFileSync(COPY_RECORD(), '{ not json');
965+
const before = w.writes.length;
966+
const res = await h.purge('com.example.crm-copy');
967+
expect(res.status, JSON.stringify(res.payload)).toBe(503);
968+
expect(w.writes.length).toBe(before);
969+
});
970+
971+
it('a copy made without the sample data answers that no sample data was copied — not "declares no seed datasets"', async () => {
972+
const w = world();
973+
const h = await w.boot();
974+
await h.install({ manifest: seededCrm(), installMode: 'unmanaged' });
975+
const res = await h.purge('com.example.crm-copy');
976+
expect(res.status, JSON.stringify(res.payload)).toBe(400);
977+
expect(res.payload.error.code).toBe('NOTHING_TO_PURGE');
978+
expect(res.payload.error.message).toContain('No sample data was copied into \'com.example.crm-copy\'');
979+
expect(res.payload.error.message).not.toContain('declares no seed datasets');
980+
});
981+
982+
it('uninstalling the copy removes its record through the protocol\'s uninstall cleanups; the purge then answers 404', async () => {
983+
const w = world();
984+
const h = await w.boot();
985+
await h.install({ manifest: seededCrm(), installMode: 'unmanaged', seedSampleData: true });
986+
const cleanup = w.cleanups.get('install-local:unmanaged-copy-record');
987+
expect(typeof cleanup).toBe('function');
988+
expect(await cleanup!({ packageId: 'com.example.crm-copy' })).toEqual({ success: true, removed: 1 });
989+
expect(existsSync(COPY_RECORD())).toBe(false);
990+
expect(await cleanup!({ packageId: 'com.example.crm-copy' })).toEqual({ success: true, removed: 0 });
991+
expect((await h.purge('com.example.crm-copy')).status).toBe(404);
992+
});
910993
});

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

Lines changed: 80 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,7 @@ import { ConnectionCredentialStore } from './connection-credential-store.js';
312312
import { readJsonRequestBody } from './request-json-body.js';
313313
import { MARKETPLACE_INSTALLED_UI_BUNDLE } from './marketplace-ui.js';
314314
import { countSeedRows, matchSeedRows, purgeSeedRows, seedDatasetOfReceiptItem, type PurgeSeedDataset } from './marketplace-install-local-purge.js';
315+
import { UnmanagedCopyRecord } from './marketplace-install-local-unmanaged-copies.js';
315316
import {
316317
isStampableOwner,
317318
stampSeedOwner,
@@ -324,6 +325,7 @@ import type {
324325
} from '@objectstack/spec/contracts';
325326
import type {
326327
DeletePackageRequest,
328+
UninstallCleanup,
327329
UninstallCleanupOutcome,
328330
UninstallDeclared,
329331
ObjectStackProtocolImplementation,
@@ -885,6 +887,9 @@ type UnmanagedCopySeedNameStore = Pick<IObjectQLEngine, 'find'>;
885887
*/
886888
const UNMANAGED_COPY_SEED_TYPE = 'seed';
887889

890+
/** [#30808] The uninstall cleanup that removes the door's record of a copy ({@link UnmanagedCopyRecord}). */
891+
const UNMANAGED_COPY_RECORD_UNINSTALL_CLEANUP = 'install-local:unmanaged-copy-record';
892+
888893
/**
889894
* [ADR-0146 D2 / D3, #30106] The three verbs a pair install composes, typed
890895
* from the producer's own method signatures and asked as a capability
@@ -1550,10 +1555,18 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
15501555
*/
15511556
private readonly refusedAtRehydrate = new Map<string, { installedAt: string; marker: NotLoadedMarker }>();
15521557

1558+
/**
1559+
* [#30808] The unmanaged copies this door made, beside the ledger
1560+
* ({@link UnmanagedCopyRecord}): the only bases its purge reaches without
1561+
* a ledger entry.
1562+
*/
1563+
private readonly unmanagedCopies: UnmanagedCopyRecord;
1564+
15531565
constructor(config: MarketplaceInstallLocalPluginConfig = {}) {
15541566
this.cloudUrl = resolveCloudUrl(config.controlPlaneUrl);
15551567
this.ledger = new LocalManifestSource(config.storageDir);
15561568
this.storageDir = this.ledger.dir;
1569+
this.unmanagedCopies = new UnmanagedCopyRecord(this.storageDir);
15571570
this.credentials = new ConnectionCredentialStore();
15581571
}
15591572

@@ -1580,6 +1593,9 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
15801593
// 1. Rehydrate previously installed packages so they survive restart.
15811594
await this.rehydrate(ctx);
15821595

1596+
// [#30808] An uninstalled copy leaves the door's record of it.
1597+
this.registerUnmanagedCopyCleanup(ctx);
1598+
15831599
// 2. Mount HTTP endpoints.
15841600
// [#4251] Read canonical-first with a REAL per-name fallback:
15851601
// `getService` THROWS for an empty slot, so a single try around
@@ -4684,6 +4700,25 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
46844700
+ `${userId ? ` by ${userId}` : ''}. Nothing is registered under '${manifestId}'; the copy follows no upgrade.`,
46854701
);
46864702
if (withheldMaps.length > 0) ctx.logger?.warn?.(withheldMapsLogLine(manifestId, 'unmanaged', withheldMaps));
4703+
// [#30808] The door's record of this copy, in the same act — before
4704+
// any row is loaded, so a load that fails partway is still purgeable.
4705+
// A record that cannot be written leaves the copy unreachable by the
4706+
// purge (its 404), never reachable by mistake; the operator is told.
4707+
try {
4708+
this.unmanagedCopies.write({
4709+
baseId: result.targetPackageId,
4710+
sourcePackageId: result.sourcePackageId,
4711+
...(result.sourceVersion !== undefined ? { sourceVersion: result.sourceVersion } : {}),
4712+
seeded: seedSampleData,
4713+
copiedAt: new Date().toISOString(),
4714+
...(userId ? { copiedBy: userId } : {}),
4715+
});
4716+
} catch (err: any) {
4717+
ctx.logger?.warn?.(
4718+
`[MarketplaceInstallLocal] the record of the unmanaged copy '${result.targetPackageId}' could not be written `
4719+
+ `under ${this.unmanagedCopies.dir}: ${err?.message ?? err}. Its sample data cannot be purged through this door.`,
4720+
);
4721+
}
46874722
const declaresSeeds = unmanagedInstallValueCarries(packageBody.data);
46884723
// [#30808] Asked for: the rows, from the receipt the verb just wrote.
46894724
const seeded = seedSampleData
@@ -5427,12 +5462,23 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
54275462
return c.json({ success: false, error: { code: 'INVALID_REQUEST', message: 'manifestId path param required.' } }, 400);
54285463
}
54295464
// [#30808] An unmanaged copy writes no install-ledger entry: its base
5430-
// holds the seed receipt instead, and the purge deletes by it.
5465+
// holds the seed receipt instead, and the purge deletes by it — for a
5466+
// base this door copied ({@link UnmanagedCopyRecord}) and no other.
54315467
if (!this.ledger.has(manifestId)) {
54325468
const copy = await this.unmanagedCopyPurgeDatasets(ctx, manifestId);
54335469
if (copy === null) {
54345470
return c.json({ success: false, error: { code: 'RESOURCE_NOT_FOUND', message: `No marketplace install for ${manifestId}.` } }, 404);
54355471
}
5472+
if ('notSeeded' in copy) {
5473+
return c.json({
5474+
success: false,
5475+
error: {
5476+
code: 'NOTHING_TO_PURGE',
5477+
message: `No sample data was copied into '${manifestId}': it was installed unmanaged without `
5478+
+ '`seedSampleData`. Nothing was deleted.',
5479+
},
5480+
}, 400);
5481+
}
54365482
if ('failure' in copy) {
54375483
ctx.logger?.warn?.(`[MarketplaceInstallLocal] purge of the unmanaged copy ${manifestId} refused: ${copy.failure}`);
54385484
return c.json({
@@ -5445,7 +5491,8 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
54455491
},
54465492
}, 503);
54475493
}
5448-
return this.purgeSeedDatasets(c, ctx, manifestId, copy.datasets, null);
5494+
return this.purgeSeedDatasets(c, ctx, manifestId, copy.datasets, null,
5495+
`The sample data receipt of '${manifestId}' holds no seed item any more, so no row can be matched. Nothing was deleted.`);
54495496
}
54505497
// #5426 — same shape as reseed: `has()` said the file is there, so a
54515498
// missing entry here is an unreadable one, and the operator gets the
@@ -5462,19 +5509,45 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
54625509
return this.purgeSeedDatasets(c, ctx, manifestId, seedDatasetsOf(entry.manifest), entry);
54635510
};
54645511

5512+
/**
5513+
* [#30808] Remove the door's record of a copy when its base is uninstalled
5514+
* (the protocol's uninstall cleanups, which `deletePackage` runs), so a
5515+
* later base under the same id is never taken for the copy. A protocol
5516+
* without the cleanup registry leaves the records as they are; the purge
5517+
* still answers 404 for a record whose base is gone.
5518+
*/
5519+
private registerUnmanagedCopyCleanup = (ctx: PluginContext): void => {
5520+
let protocol: { registerUninstallCleanup?: (name: string, cleanup: UninstallCleanup) => void } | undefined;
5521+
try { protocol = ctx.getService<typeof protocol>('protocol'); } catch { return; /* no protocol service */ }
5522+
if (!protocol || typeof protocol.registerUninstallCleanup !== 'function') return;
5523+
protocol.registerUninstallCleanup(UNMANAGED_COPY_RECORD_UNINSTALL_CLEANUP, async ({ packageId }) => {
5524+
try {
5525+
return { success: true, removed: this.unmanagedCopies.remove(packageId) ? 1 : 0 };
5526+
} catch (err: any) {
5527+
return { success: false, removed: 0, error: String(err?.message ?? err) };
5528+
}
5529+
});
5530+
};
5531+
54655532
/**
54665533
* [#30808] The datasets a purge of an UNMANAGED COPY deletes by: its
54675534
* base's seed receipt ({@link readUnmanagedCopySeedReceipt}). `null` when
5468-
* `packageId` is no installed writable base — the purge's 404, as for no
5469-
* install at all; `failure` when the receipt could not be read.
5535+
* `packageId` is no copy this door made ({@link UnmanagedCopyRecord}) or
5536+
* is no longer an installed writable base — the purge's 404, as for no
5537+
* install at all; `notSeeded` for a copy made without the sample data;
5538+
* `failure` when the record or the receipt could not be read.
54705539
*/
54715540
private unmanagedCopyPurgeDatasets = async (
54725541
ctx: PluginContext,
54735542
packageId: string,
5474-
): Promise<{ datasets: PurgeSeedDataset[] } | { failure: string } | null> => {
5543+
): Promise<{ datasets: PurgeSeedDataset[] } | { notSeeded: true } | { failure: string } | null> => {
5544+
const record = this.unmanagedCopies.read(packageId);
5545+
if (record.failure !== undefined) return { failure: record.failure };
5546+
if (record.entry === null) return null;
54755547
let ql: NamespaceHoldingEngine | undefined;
54765548
try { ql = ctx.getService<NamespaceHoldingEngine>('objectql'); } catch { return null; /* no data engine — no base */ }
54775549
if (!ql?.registry?.getPackage?.(packageId) || !isWritablePackage(ql, packageId)) return null;
5550+
if (!record.entry.seeded) return { notSeeded: true };
54785551
const listed = await this.unmanagedCopySeedNames(ctx, packageId);
54795552
if (listed.failure !== undefined) return { failure: listed.failure };
54805553
const receipt = await this.readUnmanagedCopySeedReceipt(ctx, packageId, listed.names);
@@ -5493,12 +5566,13 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
54935566
manifestId: string,
54945567
datasets: PurgeSeedDataset[],
54955568
entry: InstalledEntry | null,
5569+
nothingToPurge = 'This package declares no seed datasets.',
54965570
): Promise<Response> => {
54975571

54985572
if (datasets.length === 0) {
54995573
return c.json({
55005574
success: false,
5501-
error: { code: 'NOTHING_TO_PURGE', message: 'This package declares no seed datasets.' },
5575+
error: { code: 'NOTHING_TO_PURGE', message: nothingToPurge },
55025576
}, 400);
55035577
}
55045578

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

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ import { tmpdir } from 'node:os';
3232
import { assertEngineDeleteDispatch } from '@objectstack/metadata-core';
3333
import { SEED_WRITE_EXECUTION_CONTEXT } from '@objectstack/spec/kernel';
3434

35-
import { countSeedRows, matchSeedRows, purgeSeedRows, type PurgeSeedDataset, type SeedMatchProblem } from './marketplace-install-local-purge.js';
35+
import { countSeedRows, matchSeedRows, purgeSeedRows, seedDatasetOfReceiptItem, type PurgeSeedDataset, type SeedMatchProblem } from './marketplace-install-local-purge.js';
3636
import { MarketplaceInstallLocalPlugin } from './marketplace-install-local-plugin.js';
3737
import { LocalManifestSource } from './local-manifest-source.js';
3838
import { installerAuthService, installerEmail, INSTALLER_USER_ID, withInstallerGrants } from './install-local-principal.fixtures.js';
@@ -744,3 +744,19 @@ describe('GET …/sample-data — how many sample rows a purge would delete now
744744
expect(logger.warn.mock.calls.map((c) => String(c[0])).join('\n')).toContain('refused Counting sample data');
745745
});
746746
});
747+
748+
describe('seedDatasetOfReceiptItem — a served seed item as the dataset it declares (#30808)', () => {
749+
it('keeps every member SeedSchema declares, `files` included, and drops a key it does not declare', () => {
750+
const files = { 'fixtures/hello.txt': { contentType: 'text/plain', size: 2, sha256: 'a'.repeat(64), data: 'aGk=' } };
751+
const dataset = seedDatasetOfReceiptItem({
752+
object: 'crm_account', externalId: 'name', records: [{ name: 'Acme' }], files, _diagnostics: { valid: true },
753+
});
754+
expect(dataset).toEqual({ object: 'crm_account', externalId: 'name', records: [{ name: 'Acme' }], files });
755+
});
756+
757+
it('answers undefined for anything that is not a dataset', () => {
758+
expect([null, [], 'x', { object: 'crm_account' }, { records: [] }].map(seedDatasetOfReceiptItem)).toEqual([
759+
undefined, undefined, undefined, undefined, undefined,
760+
]);
761+
});
762+
});

0 commit comments

Comments
 (0)