fix: 收口模板契约迁移预检
This commit is contained in:
1 parent
50b87e48de
commit
456171aa85
8 files changed
+673
-48
No files matched your search
@@ -8,10 +8,11 @@
|
||||
"lint": "eslint .",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"test": "tsx --test test/**/*.test.ts",
|
||||
"test:integration": "pnpm build && node --env-file=.env test/run-integration.cjs && pnpm --filter @personal-brand/api exec tsx --test test/http.upload.test.js",
|
||||
"test:integration": "pnpm build && node --env-file=.env test/template-contract-migration.integration.mjs && node --env-file=.env test/run-integration.cjs && pnpm --filter @personal-brand/api exec tsx --test test/http.upload.test.js",
|
||||
"clean": "rimraf dist",
|
||||
"start": "node dist/main.js",
|
||||
"db:generate": "prisma generate",
|
||||
"template:migration:audit": "node --env-file=.env scripts/template-contract-migration-audit.mjs",
|
||||
"db:migrate": "prisma migrate dev",
|
||||
"db:migrate:deploy": "prisma migrate deploy",
|
||||
"db:seed": "tsx prisma/seed.ts"
|
||||
|
||||
+114
-40
@@ -1,3 +1,5 @@
|
||||
BEGIN;
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
@@ -12,31 +14,90 @@ BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1
|
||||
FROM "BrandTemplateInstallation" installation
|
||||
LEFT JOIN "TemplatePackageVersion" package_version
|
||||
ON package_version."id" = installation."templatePackageVersionId"
|
||||
WHERE installation."templatePackageVersionId" IS NULL
|
||||
OR package_version."id" IS NULL
|
||||
OR package_version."status" <> 'published'
|
||||
JOIN "BrandProfile" brand ON brand."id" = installation."brandId"
|
||||
CROSS JOIN LATERAL (
|
||||
SELECT COUNT(DISTINCT declaration) AS distinct_count
|
||||
FROM unnest(ARRAY[
|
||||
NULLIF(installation."visualTemplateKey", ''),
|
||||
NULLIF(brand."config"->>'visualTemplateKey', ''),
|
||||
NULLIF(installation."configSnapshot"->>'visualTemplateKey', ''),
|
||||
NULLIF(installation."configSnapshot"->>'packageKey', '')
|
||||
]) AS declarations(declaration)
|
||||
) declarations
|
||||
WHERE declarations.distinct_count > 1
|
||||
) THEN
|
||||
RAISE EXCEPTION 'Template contract migration stopped: an installation has no exact package version';
|
||||
RAISE EXCEPTION 'Template contract migration stopped: explicit legacy package declarations disagree';
|
||||
END IF;
|
||||
|
||||
IF EXISTS (
|
||||
SELECT 1
|
||||
FROM "BrandTemplateInstallation" installation
|
||||
JOIN "TemplatePackageVersion" package_version
|
||||
JOIN "BrandProfile" brand ON brand."id" = installation."brandId"
|
||||
WHERE installation."templatePackageVersionId" IS NULL
|
||||
AND COALESCE(
|
||||
NULLIF(installation."visualTemplateKey", ''),
|
||||
NULLIF(brand."config"->>'visualTemplateKey', ''),
|
||||
NULLIF(installation."configSnapshot"->>'visualTemplateKey', ''),
|
||||
NULLIF(installation."configSnapshot"->>'packageKey', '')
|
||||
) IS NULL
|
||||
) THEN
|
||||
RAISE EXCEPTION 'Template contract migration stopped: an installation has no explicit legacy package declaration';
|
||||
END IF;
|
||||
|
||||
IF EXISTS (
|
||||
SELECT 1
|
||||
FROM "BrandTemplateInstallation" installation
|
||||
JOIN "BrandProfile" brand ON brand."id" = installation."brandId"
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT package_version."id"
|
||||
FROM "TemplatePackageVersion" package_version
|
||||
WHERE package_version."packageKey" = COALESCE(
|
||||
NULLIF(installation."visualTemplateKey", ''),
|
||||
NULLIF(brand."config"->>'visualTemplateKey', ''),
|
||||
NULLIF(installation."configSnapshot"->>'visualTemplateKey', ''),
|
||||
NULLIF(installation."configSnapshot"->>'packageKey', '')
|
||||
)
|
||||
AND package_version."status" = 'published'
|
||||
AND package_version."manifestSnapshot"->>'packageKey' = package_version."packageKey"
|
||||
AND package_version."manifestSnapshot"->>'visualTemplateKey' = package_version."packageKey"
|
||||
AND package_version."manifestSnapshot"->>'version' = package_version."version"
|
||||
AND package_version."manifestSnapshot"->>'runtimeContract' = '1.0'
|
||||
AND package_version."manifestSnapshot"->'supportedIndustryTemplates' ? brand."templateKey"
|
||||
AND jsonb_typeof(package_version."manifestSnapshot"->'previewFixture') = 'object'
|
||||
AND jsonb_typeof(package_version."manifestSnapshot"->'previewFixture'->brand."templateKey") = 'object'
|
||||
) candidate ON true
|
||||
WHERE installation."templatePackageVersionId" IS NULL
|
||||
GROUP BY installation."id"
|
||||
HAVING COUNT(candidate."id") <> 1
|
||||
) THEN
|
||||
RAISE EXCEPTION 'Template contract migration stopped: each unresolved installation must match exactly one published contract-valid package version';
|
||||
END IF;
|
||||
|
||||
IF EXISTS (
|
||||
SELECT 1
|
||||
FROM "BrandTemplateInstallation" installation
|
||||
LEFT JOIN "TemplatePackageVersion" package_version
|
||||
ON package_version."id" = installation."templatePackageVersionId"
|
||||
JOIN "BrandProfile" brand ON brand."id" = installation."brandId"
|
||||
WHERE installation."visualTemplateKey" IS DISTINCT FROM package_version."visualTemplateKey"
|
||||
OR package_version."visualTemplateKey" IS DISTINCT FROM package_version."packageKey"
|
||||
OR package_version."manifestSnapshot"->>'visualTemplateKey' IS DISTINCT FROM package_version."visualTemplateKey"
|
||||
OR package_version."manifestSnapshot"->>'packageKey' IS DISTINCT FROM package_version."packageKey"
|
||||
OR package_version."manifestSnapshot"->>'version' IS DISTINCT FROM package_version."version"
|
||||
OR NOT COALESCE(package_version."manifestSnapshot"->'supportedIndustryTemplates' ? brand."templateKey", false)
|
||||
OR installation."templateKey" IS DISTINCT FROM brand."templateKey"
|
||||
OR (installation."contentChecksum" IS NOT NULL AND installation."contentChecksum" IS DISTINCT FROM package_version."contentChecksum")
|
||||
WHERE installation."templatePackageVersionId" IS NOT NULL
|
||||
AND (
|
||||
package_version."id" IS NULL
|
||||
OR package_version."status" <> 'published'
|
||||
OR installation."templateKey" IS DISTINCT FROM brand."templateKey"
|
||||
OR installation."visualTemplateKey" IS NOT NULL
|
||||
AND installation."visualTemplateKey" IS DISTINCT FROM package_version."packageKey"
|
||||
OR package_version."manifestSnapshot"->>'visualTemplateKey' IS DISTINCT FROM package_version."packageKey"
|
||||
OR package_version."manifestSnapshot"->>'packageKey' IS DISTINCT FROM package_version."packageKey"
|
||||
OR package_version."manifestSnapshot"->>'version' IS DISTINCT FROM package_version."version"
|
||||
OR package_version."manifestSnapshot"->>'runtimeContract' IS DISTINCT FROM '1.0'
|
||||
OR NOT COALESCE(package_version."manifestSnapshot"->'supportedIndustryTemplates' ? brand."templateKey", false)
|
||||
OR jsonb_typeof(package_version."manifestSnapshot"->'previewFixture') IS DISTINCT FROM 'object'
|
||||
OR jsonb_typeof(package_version."manifestSnapshot"->'previewFixture'->brand."templateKey") IS DISTINCT FROM 'object'
|
||||
OR installation."contentChecksum" IS NOT NULL
|
||||
AND installation."contentChecksum" IS DISTINCT FROM package_version."contentChecksum"
|
||||
)
|
||||
) THEN
|
||||
RAISE EXCEPTION 'Template contract migration stopped: installation, brand, package row, or manifest disagree';
|
||||
RAISE EXCEPTION 'Template contract migration stopped: an existing installation disagrees with its exact package version';
|
||||
END IF;
|
||||
|
||||
IF EXISTS (
|
||||
@@ -55,38 +116,49 @@ BEGIN
|
||||
JOIN "TemplatePackageVersion" package_version
|
||||
ON package_version."id" = installation."templatePackageVersionId"
|
||||
WHERE brand."config" ? 'visualTemplateKey'
|
||||
AND brand."config"->>'visualTemplateKey' IS DISTINCT FROM package_version."visualTemplateKey"
|
||||
AND brand."config"->>'visualTemplateKey' IS DISTINCT FROM package_version."packageKey"
|
||||
) THEN
|
||||
RAISE EXCEPTION 'Template contract migration stopped: brand config visualTemplateKey conflicts with its installation';
|
||||
END IF;
|
||||
|
||||
IF EXISTS (
|
||||
SELECT 1
|
||||
FROM "BrandProfile" brand
|
||||
LEFT JOIN "BrandTemplateInstallation" installation ON installation."brandId" = brand."id"
|
||||
WHERE brand."config" ? 'visualTemplateKey'
|
||||
AND installation."id" IS NULL
|
||||
) THEN
|
||||
RAISE EXCEPTION 'Template contract migration stopped: brand config visualTemplateKey has no installation to verify against';
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM "TemplatePackageVersion" package_version
|
||||
WHERE package_version."visualTemplateKey" IS DISTINCT FROM package_version."packageKey"
|
||||
OR package_version."manifestSnapshot"->>'visualTemplateKey' IS DISTINCT FROM package_version."packageKey"
|
||||
OR package_version."manifestSnapshot"->>'packageKey' IS DISTINCT FROM package_version."packageKey"
|
||||
OR package_version."manifestSnapshot"->>'version' IS DISTINCT FROM package_version."version"
|
||||
) THEN
|
||||
RAISE EXCEPTION 'Template contract migration stopped: package metadata conflicts with its manifest';
|
||||
END IF;
|
||||
END $$;
|
||||
WITH resolved AS (
|
||||
SELECT
|
||||
installation."id" AS installation_id,
|
||||
package_version."id" AS package_version_id,
|
||||
package_version."version",
|
||||
package_version."contentChecksum",
|
||||
package_version."manifestSnapshot"
|
||||
FROM "BrandTemplateInstallation" installation
|
||||
JOIN "BrandProfile" brand ON brand."id" = installation."brandId"
|
||||
JOIN "TemplatePackageVersion" package_version ON package_version."packageKey" = COALESCE(
|
||||
NULLIF(installation."visualTemplateKey", ''),
|
||||
NULLIF(brand."config"->>'visualTemplateKey', ''),
|
||||
NULLIF(installation."configSnapshot"->>'visualTemplateKey', ''),
|
||||
NULLIF(installation."configSnapshot"->>'packageKey', '')
|
||||
)
|
||||
WHERE installation."templatePackageVersionId" IS NULL
|
||||
AND package_version."status" = 'published'
|
||||
AND package_version."manifestSnapshot"->>'packageKey' = package_version."packageKey"
|
||||
AND package_version."manifestSnapshot"->>'visualTemplateKey' = package_version."packageKey"
|
||||
AND package_version."manifestSnapshot"->>'version' = package_version."version"
|
||||
AND package_version."manifestSnapshot"->>'runtimeContract' = '1.0'
|
||||
AND package_version."manifestSnapshot"->'supportedIndustryTemplates' ? brand."templateKey"
|
||||
AND jsonb_typeof(package_version."manifestSnapshot"->'previewFixture') = 'object'
|
||||
AND jsonb_typeof(package_version."manifestSnapshot"->'previewFixture'->brand."templateKey") = 'object'
|
||||
)
|
||||
UPDATE "BrandTemplateInstallation" installation
|
||||
SET "templatePackageVersionId" = resolved.package_version_id,
|
||||
"templateVersion" = resolved."version",
|
||||
"contentChecksum" = resolved."contentChecksum",
|
||||
"configSnapshot" = resolved."manifestSnapshot"
|
||||
FROM resolved
|
||||
WHERE installation."id" = resolved.installation_id;
|
||||
|
||||
UPDATE "BrandTemplateInstallation" installation
|
||||
SET "templateVersion" = package_version."version",
|
||||
"contentChecksum" = package_version."contentChecksum"
|
||||
"contentChecksum" = package_version."contentChecksum",
|
||||
"configSnapshot" = package_version."manifestSnapshot"
|
||||
FROM "TemplatePackageVersion" package_version
|
||||
WHERE package_version."id" = installation."templatePackageVersionId";
|
||||
|
||||
@@ -105,3 +177,5 @@ ALTER TABLE "TemplatePackageVersion" DROP COLUMN "visualTemplateKey";
|
||||
|
||||
DROP INDEX "BrandTemplateInstallation_brandId_templateKey_key";
|
||||
CREATE UNIQUE INDEX "BrandTemplateInstallation_brandId_key" ON "BrandTemplateInstallation"("brandId");
|
||||
|
||||
COMMIT;
|
||||
@@ -0,0 +1,196 @@
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
|
||||
function object(value) {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
||||
}
|
||||
|
||||
function packageMetadataMatches(version, industry) {
|
||||
const manifest = object(version.manifestSnapshot);
|
||||
const fixture = object(manifest.previewFixture)[industry];
|
||||
return (
|
||||
manifest.packageKey === version.packageKey &&
|
||||
manifest.visualTemplateKey === version.packageKey &&
|
||||
manifest.version === version.version &&
|
||||
manifest.runtimeContract === "1.0" &&
|
||||
Array.isArray(manifest.supportedIndustryTemplates) &&
|
||||
manifest.supportedIndustryTemplates.includes(industry) &&
|
||||
fixture !== null &&
|
||||
typeof fixture === "object" &&
|
||||
!Array.isArray(fixture)
|
||||
);
|
||||
}
|
||||
|
||||
function packageMetadataIsConsistent(version) {
|
||||
const manifest = object(version.manifestSnapshot);
|
||||
const fixtures = object(manifest.previewFixture);
|
||||
return (
|
||||
manifest.packageKey === version.packageKey &&
|
||||
manifest.visualTemplateKey === version.packageKey &&
|
||||
manifest.version === version.version &&
|
||||
manifest.runtimeContract === "1.0" &&
|
||||
Array.isArray(manifest.supportedIndustryTemplates) &&
|
||||
manifest.supportedIndustryTemplates.length > 0 &&
|
||||
manifest.supportedIndustryTemplates.every((industry) => {
|
||||
const fixture = fixtures[industry];
|
||||
return fixture !== null && typeof fixture === "object" && !Array.isArray(fixture);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export function buildTemplateContractMigrationReport({ brands, versions }) {
|
||||
const grouped = new Map();
|
||||
for (const row of brands) {
|
||||
const entries = grouped.get(row.brandId) ?? [];
|
||||
entries.push(row);
|
||||
grouped.set(row.brandId, entries);
|
||||
}
|
||||
|
||||
const brandReports = [...grouped.values()].map((entries) => {
|
||||
const row = entries[0];
|
||||
const installations = entries.filter((entry) => entry.installationId);
|
||||
const base = {
|
||||
brandId: row.brandId,
|
||||
slug: row.slug,
|
||||
industry: row.industry,
|
||||
installationCount: installations.length,
|
||||
mappingSource: null,
|
||||
packageKey: null,
|
||||
candidates: [],
|
||||
blockers: [],
|
||||
};
|
||||
if (installations.length !== 1) {
|
||||
base.blockers.push(
|
||||
installations.length === 0 ? "installation_missing" : "multiple_installations",
|
||||
);
|
||||
return base;
|
||||
}
|
||||
|
||||
const installation = installations[0];
|
||||
const declarations = [
|
||||
["installation.visualTemplateKey", installation.installationVisualTemplateKey],
|
||||
["brand.config.visualTemplateKey", row.brandVisualTemplateKey],
|
||||
["installation.configSnapshot.visualTemplateKey", installation.snapshotVisualTemplateKey],
|
||||
["installation.configSnapshot.packageKey", installation.snapshotPackageKey],
|
||||
].filter(([, value]) => typeof value === "string" && value.trim());
|
||||
const declaredKeys = [...new Set(declarations.map(([, value]) => value))];
|
||||
if (declaredKeys.length > 1) {
|
||||
base.blockers.push("legacy_package_declarations_conflict");
|
||||
return base;
|
||||
}
|
||||
|
||||
const explicitPackageKey = declaredKeys[0] ?? null;
|
||||
base.mappingSource = declarations[0]?.[0] ?? null;
|
||||
base.packageKey = explicitPackageKey;
|
||||
if (!installation.installationPackageVersionId && !explicitPackageKey) {
|
||||
base.blockers.push("explicit_package_declaration_missing");
|
||||
return base;
|
||||
}
|
||||
|
||||
const matches = installation.installationPackageVersionId
|
||||
? versions.filter((version) => version.id === installation.installationPackageVersionId)
|
||||
: versions.filter(
|
||||
(version) =>
|
||||
version.packageKey === explicitPackageKey &&
|
||||
packageMetadataMatches(version, row.industry),
|
||||
);
|
||||
base.candidates = matches.map((version) => ({
|
||||
id: version.id,
|
||||
packageKey: version.packageKey,
|
||||
version: version.version,
|
||||
status: version.status,
|
||||
}));
|
||||
|
||||
if (installation.installationPackageVersionId) {
|
||||
const [version] = matches;
|
||||
if (
|
||||
!version ||
|
||||
version.status !== "published" ||
|
||||
!packageMetadataMatches(version, row.industry) ||
|
||||
(explicitPackageKey && explicitPackageKey !== version.packageKey)
|
||||
) {
|
||||
base.blockers.push("linked_package_version_invalid");
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
const published = matches.filter((version) => version.status === "published");
|
||||
if (published.length === 1) return base;
|
||||
if (published.length > 1) base.blockers.push("published_package_version_ambiguous");
|
||||
else if (matches.length) base.blockers.push("matching_package_version_not_published");
|
||||
else base.blockers.push("matching_contract_package_version_missing");
|
||||
return base;
|
||||
});
|
||||
|
||||
const invalidHistoricalVersions = versions
|
||||
.filter((version) => !packageMetadataIsConsistent(version))
|
||||
.map((version) => ({
|
||||
packageKey: version.packageKey,
|
||||
version: version.version,
|
||||
status: version.status,
|
||||
storedVisualTemplateKey: version.visualTemplateKey ?? null,
|
||||
hasPreviewFixture: Boolean(object(version.manifestSnapshot).previewFixture),
|
||||
}));
|
||||
const blocked = brandReports.filter((brand) => brand.blockers.length);
|
||||
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
readOnly: true,
|
||||
ready: blocked.length === 0,
|
||||
summary: {
|
||||
brandCount: brandReports.length,
|
||||
readyCount: brandReports.length - blocked.length,
|
||||
blockedCount: blocked.length,
|
||||
historicalInvalidVersionCount: invalidHistoricalVersions.length,
|
||||
},
|
||||
brands: brandReports,
|
||||
invalidHistoricalVersions,
|
||||
};
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const prisma = new PrismaClient();
|
||||
try {
|
||||
const [brands, versions] = await Promise.all([
|
||||
prisma.$queryRaw`
|
||||
SELECT
|
||||
brand."id" AS "brandId",
|
||||
brand."slug",
|
||||
brand."templateKey" AS "industry",
|
||||
brand."config"->>'visualTemplateKey' AS "brandVisualTemplateKey",
|
||||
installation."id" AS "installationId",
|
||||
installation."visualTemplateKey" AS "installationVisualTemplateKey",
|
||||
installation."templatePackageVersionId" AS "installationPackageVersionId",
|
||||
installation."configSnapshot"->>'visualTemplateKey' AS "snapshotVisualTemplateKey",
|
||||
installation."configSnapshot"->>'packageKey' AS "snapshotPackageKey"
|
||||
FROM "BrandProfile" brand
|
||||
LEFT JOIN "BrandTemplateInstallation" installation
|
||||
ON installation."brandId" = brand."id"
|
||||
ORDER BY brand."slug", installation."id"
|
||||
`,
|
||||
prisma.$queryRaw`
|
||||
SELECT
|
||||
"id",
|
||||
"packageKey",
|
||||
"version",
|
||||
"status",
|
||||
"visualTemplateKey",
|
||||
"manifestSnapshot"
|
||||
FROM "TemplatePackageVersion"
|
||||
ORDER BY "packageKey", "version"
|
||||
`,
|
||||
]);
|
||||
process.stdout.write(
|
||||
`${JSON.stringify(buildTemplateContractMigrationReport({ brands, versions }), null, 2)}\n`,
|
||||
);
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
}
|
||||
@@ -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;
|
||||
});
|
||||
@@ -35,9 +35,11 @@
|
||||
|
||||
## 迁移计划
|
||||
|
||||
1. 盘点品牌行业、config 视觉键、安装行、包版本和发布快照,输出只读不一致报告。
|
||||
2. 对存在唯一明确来源的品牌,迁移为每品牌唯一安装行,并绑定已发布 package version、版本与 checksum;无法唯一映射的品牌保持不变并列为阻断项。
|
||||
3. 在失败即停迁移中校验一品牌一安装、精确版本引用、package key/version/checksum/行业声明及旧视觉键一致;成功后删除 config JSON 键及安装/版本表重复 renderer 列,并约束一品牌唯一安装。
|
||||
4. 将 API、Admin、Runtime、发布快照、bootstrap 和构建路径切换到安装记录;缺失/损坏状态显式失败。
|
||||
5. 删除默认映射、包外 sample fallback、旧格式推断和聚合字段兼容读写,补授权、成功和失败集成测试。
|
||||
6. 运行 template doctor、数据库迁移、API integration、Admin production build、Taro 双端构建及完整格式/类型门禁。
|
||||
1. 使用 `pnpm template:migration:audit` 盘点品牌行业、旧视觉键、安装行和包版本;该命令只读,明确报告候选版本和阻断原因。
|
||||
2. 仅可用品牌或安装记录中已有的明确 package key 作为一次性迁移来源。必须恰好匹配一个已发布版本,且 manifest 自身的 package key、version、visual renderer key、行业声明和 preview fixture 一致;不得按行业名推断 package key 或按版本号排序挑选。
|
||||
3. 对唯一明确的映射回填 package version id、version、checksum 和 manifest snapshot。无映射、候选未发布、多候选、声明冲突或安装缺失均失败即停,由管理员先显式解决。
|
||||
4. 未被品牌安装引用的历史无效快照保留原文供审计,不因缺少新契约字段而阻断迁移;其预览/安装仍由当前 manifest 契约校验拒绝。已安装版本必须通过完整迁移前置校验。
|
||||
5. 成功后删除 config JSON 键及安装/版本表重复 renderer 列,并约束一品牌唯一安装。
|
||||
6. 将 API、Admin、Runtime、发布快照、bootstrap 和构建路径切换到安装记录;缺失/损坏状态显式失败。
|
||||
7. 删除默认映射、包外 sample fallback、旧格式推断和聚合字段兼容读写,补授权、成功和失败集成测试。
|
||||
8. 运行 template doctor、数据库迁移、API integration、Admin production build、Taro 双端构建及完整格式/类型门禁。
|
||||
+10
-1
@@ -57,6 +57,15 @@ export default tseslint.config(
|
||||
},
|
||||
{
|
||||
...tseslint.configs.disableTypeChecked,
|
||||
files: ["apps/admin/template-preview-css.mjs"],
|
||||
files: [
|
||||
"apps/admin/template-preview-css.mjs",
|
||||
"apps/api/scripts/template-contract-migration-audit.mjs",
|
||||
"apps/api/test/template-contract-migration-audit.test.mjs",
|
||||
"apps/api/test/template-contract-migration.integration.mjs",
|
||||
],
|
||||
languageOptions: {
|
||||
parserOptions: { project: false, projectService: false },
|
||||
globals: { console: "readonly", process: "readonly", URL: "readonly" },
|
||||
},
|
||||
},
|
||||
);
|
||||
@@ -42,6 +42,8 @@
|
||||
"build:taro:food": "pnpm --filter @personal-brand/taro build:h5 && pnpm --filter @personal-brand/taro build:weapp",
|
||||
"build:taro:linjing": "TEMPLATE_KEY=linjing-editorial pnpm --filter @personal-brand/taro build:h5 && TEMPLATE_KEY=linjing-editorial pnpm --filter @personal-brand/taro build:weapp",
|
||||
"template:doctor": "node scripts/template-doctor.mjs",
|
||||
"template:migration:audit": "pnpm --filter @personal-brand/api template:migration:audit",
|
||||
"test:template-migration-audit": "node --test apps/api/test/template-contract-migration-audit.test.mjs",
|
||||
"check:local-media": "node scripts/check-local-media.mjs",
|
||||
"test:template-doctor": "node --test scripts/test/template-doctor.test.mjs"
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user