fix: 收口模板契约迁移预检
This commit is contained in:
1 parent
50b87e48de
commit
456171aa85
8 files changed
+673
-48
No files matched your search
@@ -0,0 +1,133 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { buildTemplateContractMigrationReport } from "../scripts/template-contract-migration-audit.mjs";
|
||||
|
||||
function brandRow(overrides = {}) {
|
||||
return {
|
||||
brandId: "brand-1",
|
||||
slug: "sample-brand",
|
||||
industry: "food",
|
||||
brandVisualTemplateKey: "acheng-campus-food",
|
||||
installationId: "installation-1",
|
||||
installationVisualTemplateKey: null,
|
||||
installationPackageVersionId: null,
|
||||
snapshotVisualTemplateKey: null,
|
||||
snapshotPackageKey: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function packageVersion(overrides = {}) {
|
||||
const manifestSnapshot = {
|
||||
packageKey: "acheng-campus-food",
|
||||
version: "1.0.2",
|
||||
visualTemplateKey: "acheng-campus-food",
|
||||
runtimeContract: "1.0",
|
||||
supportedIndustryTemplates: ["food"],
|
||||
previewFixture: { food: { schemaVersion: "1" } },
|
||||
};
|
||||
return {
|
||||
id: "version-1",
|
||||
packageKey: "acheng-campus-food",
|
||||
version: "1.0.2",
|
||||
status: "published",
|
||||
visualTemplateKey: "acheng-campus-food",
|
||||
manifestSnapshot,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
test("migration audit accepts a unique published version named by explicit legacy config", () => {
|
||||
const report = buildTemplateContractMigrationReport({
|
||||
brands: [brandRow()],
|
||||
versions: [packageVersion()],
|
||||
});
|
||||
|
||||
assert.equal(report.ready, true);
|
||||
assert.equal(report.brands[0].packageKey, "acheng-campus-food");
|
||||
assert.deepEqual(report.brands[0].blockers, []);
|
||||
});
|
||||
|
||||
test("migration audit uses manifest metadata instead of the redundant database renderer column", () => {
|
||||
const report = buildTemplateContractMigrationReport({
|
||||
brands: [brandRow()],
|
||||
versions: [packageVersion({ visualTemplateKey: null, status: "imported" })],
|
||||
});
|
||||
|
||||
assert.deepEqual(report.brands[0].blockers, ["matching_package_version_not_published"]);
|
||||
assert.equal(report.brands[0].candidates[0].version, "1.0.2");
|
||||
});
|
||||
|
||||
test("migration audit does not infer a package from the brand industry", () => {
|
||||
const report = buildTemplateContractMigrationReport({
|
||||
brands: [brandRow({ brandVisualTemplateKey: null })],
|
||||
versions: [packageVersion()],
|
||||
});
|
||||
|
||||
assert.equal(report.ready, false);
|
||||
assert.deepEqual(report.brands[0].blockers, ["explicit_package_declaration_missing"]);
|
||||
});
|
||||
|
||||
test("migration audit requires the explicitly named package version to be published", () => {
|
||||
const report = buildTemplateContractMigrationReport({
|
||||
brands: [brandRow()],
|
||||
versions: [packageVersion({ status: "imported" })],
|
||||
});
|
||||
|
||||
assert.deepEqual(report.brands[0].blockers, ["matching_package_version_not_published"]);
|
||||
assert.equal(report.brands[0].candidates[0].version, "1.0.2");
|
||||
});
|
||||
|
||||
test("migration audit blocks multiple valid published versions instead of picking the latest", () => {
|
||||
const report = buildTemplateContractMigrationReport({
|
||||
brands: [brandRow()],
|
||||
versions: [
|
||||
packageVersion(),
|
||||
packageVersion({
|
||||
id: "version-2",
|
||||
version: "1.0.3",
|
||||
manifestSnapshot: {
|
||||
...packageVersion().manifestSnapshot,
|
||||
version: "1.0.3",
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
assert.deepEqual(report.brands[0].blockers, ["published_package_version_ambiguous"]);
|
||||
});
|
||||
|
||||
test("uninstalled historical snapshots are reported without blocking mapped brands", () => {
|
||||
const report = buildTemplateContractMigrationReport({
|
||||
brands: [brandRow()],
|
||||
versions: [
|
||||
packageVersion(),
|
||||
packageVersion({
|
||||
id: "old-version",
|
||||
version: "1.0.1",
|
||||
status: "retired",
|
||||
visualTemplateKey: null,
|
||||
manifestSnapshot: { packageKey: "acheng-campus-food", version: "1.0.1" },
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
assert.equal(report.ready, true);
|
||||
assert.equal(report.summary.historicalInvalidVersionCount, 1);
|
||||
assert.deepEqual(report.invalidHistoricalVersions[0], {
|
||||
packageKey: "acheng-campus-food",
|
||||
version: "1.0.1",
|
||||
status: "retired",
|
||||
storedVisualTemplateKey: null,
|
||||
hasPreviewFixture: false,
|
||||
});
|
||||
});
|
||||
|
||||
test("migration audit blocks conflicting explicit package declarations", () => {
|
||||
const report = buildTemplateContractMigrationReport({
|
||||
brands: [brandRow({ installationVisualTemplateKey: "linjing-editorial" })],
|
||||
versions: [packageVersion()],
|
||||
});
|
||||
|
||||
assert.deepEqual(report.brands[0].blockers, ["legacy_package_declarations_conflict"]);
|
||||
});
|
||||
@@ -0,0 +1,208 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { cpSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
|
||||
const apiRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const migrationsRoot = path.join(apiRoot, "prisma/migrations");
|
||||
const targetMigration = "20261018120000_enforce_single_template_contract";
|
||||
|
||||
function run(args, env) {
|
||||
const result = spawnSync("pnpm", args, { cwd: apiRoot, env, encoding: "utf8" });
|
||||
if (result.status !== 0) {
|
||||
throw new Error(`${args.join(" ")} failed:\n${result.stdout}\n${result.stderr}`);
|
||||
}
|
||||
}
|
||||
|
||||
function assertDefined(value, message) {
|
||||
assert.ok(value, message);
|
||||
return value;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const databaseUrl = process.env.DATABASE_URL;
|
||||
if (!databaseUrl) throw new Error("DATABASE_URL is required for migration integration tests");
|
||||
|
||||
const schema = `pb_contract_migration_${randomUUID().replaceAll("-", "")}`;
|
||||
const testUrl = new URL(databaseUrl);
|
||||
testUrl.searchParams.set("schema", schema);
|
||||
const testEnvironment = { ...process.env, DATABASE_URL: testUrl.toString() };
|
||||
const tempRoot = mkdtempSync(path.join(os.tmpdir(), "pb-contract-migration-"));
|
||||
const tempPrisma = path.join(tempRoot, "prisma");
|
||||
const tempMigrations = path.join(tempPrisma, "migrations");
|
||||
const schemaPath = path.join(tempPrisma, "schema.prisma");
|
||||
const fixturePath = path.join(tempRoot, "legacy-fixture.sql");
|
||||
const admin = new PrismaClient();
|
||||
let createdSchema = false;
|
||||
|
||||
try {
|
||||
const schemaSource = readFileSync(path.join(apiRoot, "prisma/schema.prisma"), "utf8");
|
||||
const migrationDirs = readdirSync(migrationsRoot, { withFileTypes: true })
|
||||
.filter((entry) => entry.isDirectory() && entry.name !== targetMigration)
|
||||
.map((entry) => entry.name)
|
||||
.sort();
|
||||
assert.equal(migrationDirs.at(-1), "20261017120000_template_operation_failure_events");
|
||||
await admin.$executeRawUnsafe(`CREATE SCHEMA "${schema}"`);
|
||||
createdSchema = true;
|
||||
|
||||
const { mkdirSync, copyFileSync } = await import("node:fs");
|
||||
mkdirSync(tempMigrations, { recursive: true });
|
||||
writeFileSync(schemaPath, schemaSource);
|
||||
copyFileSync(
|
||||
path.join(migrationsRoot, "migration_lock.toml"),
|
||||
path.join(tempMigrations, "migration_lock.toml"),
|
||||
);
|
||||
for (const migration of migrationDirs) {
|
||||
cpSync(path.join(migrationsRoot, migration), path.join(tempMigrations, migration), {
|
||||
recursive: true,
|
||||
});
|
||||
}
|
||||
|
||||
run(["exec", "prisma", "migrate", "deploy", "--schema", schemaPath], testEnvironment);
|
||||
|
||||
const database = new PrismaClient({ datasourceUrl: testUrl.toString() });
|
||||
try {
|
||||
const actorId = randomUUID();
|
||||
const brandId = randomUUID();
|
||||
const packageId = randomUUID();
|
||||
const packageVersionId = randomUUID();
|
||||
const historicalPackageId = randomUUID();
|
||||
const historicalVersionId = randomUUID();
|
||||
const packageKey = "explicit-food-package";
|
||||
const manifest = {
|
||||
packageKey,
|
||||
version: "2.4.0",
|
||||
visualTemplateKey: packageKey,
|
||||
runtimeContract: "1.0",
|
||||
supportedIndustryTemplates: ["food"],
|
||||
previewFixture: { food: { schemaVersion: "1" } },
|
||||
};
|
||||
const legacySnapshot = { packageKey: "old-invalid-package", version: "1.0.0" };
|
||||
const checksum = "a".repeat(64);
|
||||
|
||||
await database.adminUser.create({
|
||||
data: {
|
||||
id: actorId,
|
||||
username: `migration-${randomUUID()}`,
|
||||
passwordHash: "unused",
|
||||
displayName: "Migration Fixture",
|
||||
},
|
||||
});
|
||||
await database.brandProfile.create({
|
||||
data: {
|
||||
id: brandId,
|
||||
slug: `migration-${randomUUID()}`,
|
||||
name: "Migration Fixture Brand",
|
||||
templateKey: "food",
|
||||
config: { visualTemplateKey: packageKey },
|
||||
},
|
||||
});
|
||||
await database.templatePackage.create({ data: { id: packageId, packageKey } });
|
||||
await database.templatePackageVersion.create({
|
||||
data: {
|
||||
id: packageVersionId,
|
||||
templatePackageId: packageId,
|
||||
packageKey,
|
||||
version: "2.4.0",
|
||||
displayName: "Current Food Package",
|
||||
status: "published",
|
||||
manifestSnapshot: manifest,
|
||||
validationReport: { errors: [] },
|
||||
contentChecksum: checksum,
|
||||
archiveChecksum: "b".repeat(64),
|
||||
artifactPath: "/fixture/current.tar.gz",
|
||||
importedById: actorId,
|
||||
},
|
||||
});
|
||||
await database.templatePackage.create({
|
||||
data: { id: historicalPackageId, packageKey: "old-invalid-package" },
|
||||
});
|
||||
await database.templatePackageVersion.create({
|
||||
data: {
|
||||
id: historicalVersionId,
|
||||
templatePackageId: historicalPackageId,
|
||||
packageKey: "old-invalid-package",
|
||||
version: "1.0.0",
|
||||
displayName: "Invalid Historical Package",
|
||||
status: "retired",
|
||||
manifestSnapshot: legacySnapshot,
|
||||
validationReport: { errors: [] },
|
||||
contentChecksum: "c".repeat(64),
|
||||
archiveChecksum: "d".repeat(64),
|
||||
artifactPath: "/fixture/historical.tar.gz",
|
||||
importedById: actorId,
|
||||
},
|
||||
});
|
||||
|
||||
await database.$executeRaw`
|
||||
INSERT INTO "BrandTemplateInstallation" (
|
||||
"id", "brandId", "templateKey", "templateVersion", "installedAt", "updatedAt",
|
||||
"configSnapshot", "previousSnapshots", "contentChecksum", "templatePackageVersionId",
|
||||
"visualTemplateKey"
|
||||
) VALUES (
|
||||
${randomUUID()}, ${brandId}, 'food', '1.0.0', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP,
|
||||
'{}'::jsonb, '[]'::jsonb, NULL, NULL, NULL
|
||||
)
|
||||
`;
|
||||
|
||||
const migrationSql = readFileSync(
|
||||
path.join(migrationsRoot, targetMigration, "migration.sql"),
|
||||
"utf8",
|
||||
);
|
||||
writeFileSync(fixturePath, migrationSql);
|
||||
run(
|
||||
["exec", "prisma", "db", "execute", "--schema", schemaPath, "--file", fixturePath],
|
||||
testEnvironment,
|
||||
);
|
||||
|
||||
const installation = assertDefined(
|
||||
await database.$queryRaw`
|
||||
SELECT "templatePackageVersionId", "templateVersion", "contentChecksum", "configSnapshot"
|
||||
FROM "BrandTemplateInstallation" WHERE "brandId" = ${brandId}
|
||||
`.then((rows) => rows[0]),
|
||||
"Migration should preserve and resolve the existing installation",
|
||||
);
|
||||
assert.equal(installation.templatePackageVersionId, packageVersionId);
|
||||
assert.equal(installation.templateVersion, "2.4.0");
|
||||
assert.equal(installation.contentChecksum, checksum);
|
||||
assert.equal(installation.configSnapshot.packageKey, packageKey);
|
||||
|
||||
const brandConfig = await database.$queryRaw`
|
||||
SELECT "config" FROM "BrandProfile" WHERE "id" = ${brandId}
|
||||
`;
|
||||
assert.equal(Object.hasOwn(brandConfig[0].config, "visualTemplateKey"), false);
|
||||
|
||||
const historical = await database.templatePackageVersion.findUniqueOrThrow({
|
||||
where: { id: historicalVersionId },
|
||||
select: { manifestSnapshot: true, status: true },
|
||||
});
|
||||
assert.deepEqual(historical.manifestSnapshot, legacySnapshot);
|
||||
assert.equal(historical.status, "retired");
|
||||
|
||||
const redundantColumns = await database.$queryRaw`
|
||||
SELECT column_name FROM information_schema.columns
|
||||
WHERE table_schema = current_schema()
|
||||
AND ((table_name = 'TemplatePackageVersion' AND column_name = 'visualTemplateKey')
|
||||
OR (table_name = 'BrandTemplateInstallation' AND column_name = 'visualTemplateKey'))
|
||||
`;
|
||||
assert.deepEqual(redundantColumns, []);
|
||||
} finally {
|
||||
await database.$disconnect();
|
||||
}
|
||||
|
||||
console.log("Template contract migration populated-data rehearsal passed");
|
||||
} finally {
|
||||
if (createdSchema) await admin.$executeRawUnsafe(`DROP SCHEMA "${schema}" CASCADE`);
|
||||
await admin.$disconnect();
|
||||
rmSync(tempRoot, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
Reference in new issue
Block a user