feat: 收口模板升级与阶段七持续回归

This commit is contained in:
que01 committed 2026-10-17 21:33:57 +08:00
1 parent ec16fff70e
commit 71c528de34
29 files changed
+1962 -304

No files matched your search

+25
View File
@@ -7,6 +7,7 @@ import {
IsObject,
IsOptional,
IsString,
ValidateNested,
MinLength,
Matches,
Max,
@@ -14,6 +15,7 @@ import {
} from "class-validator";
import { brandTemplateKeys } from "@personal-brand/config";
import type { BrandTemplateKey } from "@personal-brand/config";
import { Type } from "class-transformer";
export class UpdateBrandDto {
@IsOptional() @IsString() name?: string;
@IsOptional() @IsString() tagline?: string;
@@ -107,6 +109,29 @@ export class InstallTemplateDto {
@IsOptional() @IsUUID() templatePackageVersionId?: string;
}
export class UpgradeTemplateDto {
@IsUUID() templatePackageVersionId!: string;
@IsString() @MinLength(1) expectedContentChecksum!: string;
@IsString() @MinLength(1) expectedCurrentVersion!: string;
@IsOptional() @IsUUID() expectedCurrentPackageVersionId?: string | null;
@IsBoolean() confirm!: boolean;
@IsArray()
@ValidateNested({ each: true })
@Type(() => PreserveTemplateBindingDto)
preservedBindings!: PreserveTemplateBindingDto[];
}
export class PreserveTemplateBindingDto {
@IsString() key!: string;
@IsString() binding!: string;
@IsIn(["preserve"]) action!: "preserve";
}
export class RollbackTemplateDto {
@IsString() @MinLength(1) expectedCurrentVersion!: string;
@IsBoolean() confirm!: boolean;
}
export class PreviewTemplateSampleDto {
@IsOptional() @IsUUID() templatePackageVersionId?: string;
@IsOptional() @IsIn(["missing_only"]) strategy?: "missing_only";
@@ -27,7 +27,11 @@ export class AdminTemplatePackageController {
@Post("import")
async import(@Req() request: FastifyRequest) {
const { subject } = await this.access.requireTemplateAdmin(request);
return this.templates.importArchive(request, subject);
return this.templates.importArchive(
request,
subject,
request.headers["x-request-id"]?.toString() ?? request.id,
);
}
@Post(":id/publish")
@@ -14,6 +14,7 @@ import { promises as fs } from "node:fs";
import path from "node:path";
import { promisify } from "node:util";
import { PrismaService } from "../../prisma.service.js";
import { recordTemplateOperationFailure } from "./template-operation-failure.js";
const execFileAsync = promisify(execFile);
const MAX_ARCHIVE_BYTES = 50 * 1024 * 1024;
@@ -181,13 +182,15 @@ export class AdminTemplatePackageService {
};
}
async importArchive(request: FastifyRequest, actorId: string) {
async importArchive(request: FastifyRequest, actorId: string, requestId?: string) {
const part = await request.file({ limits: { files: 1, fileSize: MAX_ARCHIVE_BYTES } });
if (!part) throw new BadRequestException("请上传模板 archive 文件");
if (part.fieldname !== "archive") throw new BadRequestException("上传字段必须是 archive");
const chunks: Buffer[] = [];
let bytes = 0;
let storedArtifactPath: string | null = null;
let failurePackageKey: string | undefined;
let failureVersion: string | undefined;
try {
for await (const chunk of part.file) {
const buffer = Buffer.from(chunk as Uint8Array);
@@ -242,6 +245,8 @@ export class AdminTemplatePackageService {
path.join(packageRoot, "template.json"),
"template.json",
)) as Manifest;
failurePackageKey = typeof manifest.packageKey === "string" ? manifest.packageKey : undefined;
failureVersion = typeof manifest.version === "string" ? manifest.version : undefined;
const packageJson = jsonObject(
await this.readJson(path.join(packageRoot, "package.json"), "package.json"),
"package.json",
@@ -304,6 +309,7 @@ export class AdminTemplatePackageService {
errors: [],
fileCount: files.length,
extractedBytes: files.reduce((total, file) => total + file.bytes, 0),
files: checksums.files.map((file) => ({ ...file })),
},
contentChecksum: checksums.contentChecksum,
archiveChecksum,
@@ -328,6 +334,14 @@ export class AdminTemplatePackageService {
return { imported: true, idempotent: false, version: this.publicVersion(version) };
} catch (error) {
if (storedArtifactPath) await fs.rm(storedArtifactPath, { force: true });
await recordTemplateOperationFailure(this.prisma, {
action: "import",
error,
...(requestId ? { requestId } : {}),
actorId,
...(failurePackageKey ? { packageKey: failurePackageKey } : {}),
...(failureVersion ? { version: failureVersion } : {}),
});
throw error;
} finally {
await fs.rm(temporaryRoot, { recursive: true, force: true });
@@ -18,6 +18,7 @@ import type { BrandReleaseSnapshot } from "../../brand-release.service.js";
import { PrismaService } from "../../prisma.service.js";
import { assemblePublicWorkspace } from "../public/public-workspace.snapshot-assembler.js";
import { AdminTemplatePreviewAssetsService } from "./admin-template-preview-assets.service.js";
import { recordTemplateOperationFailure } from "./template-operation-failure.js";
function record(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
@@ -118,7 +119,18 @@ export class AdminTemplatePreviewService {
};
}
const projection = await this.buildPreview(id, industry);
let projection: Awaited<ReturnType<AdminTemplatePreviewService["buildPreview"]>>;
try {
projection = await this.buildPreview(id, industry);
} catch (error) {
await recordTemplateOperationFailure(this.prisma, {
action: "preview",
error,
...(requestId ? { requestId } : {}),
actorId,
});
throw error;
}
this.cleanupPreviewSessions();
const token = randomBytes(32).toString("hex");
const expiresAt = Date.now() + 15 * 60 * 1000;
@@ -15,6 +15,8 @@ import { AdminUploadService } from "./admin-upload.service.js";
import { AdminUploadController } from "./admin-upload.controller.js";
import { AdminTemplatePackageController } from "./admin-template-package.controller.js";
import { AdminTemplatePackageService } from "./admin-template-package.service.js";
import { TemplateOperationMetricsController } from "./template-operation-metrics.controller.js";
import { TemplateOperationMetricsService } from "./template-operation-metrics.service.js";
import { AdminTemplatePreviewService } from "./admin-template-preview.service.js";
import { AdminTemplatePreviewAssetsService } from "./admin-template-preview-assets.service.js";
@@ -29,6 +31,7 @@ import { AdminTemplatePreviewAssetsService } from "./admin-template-preview-asse
AdminLocalUploadController,
AdminBookingController,
AdminTemplatePackageController,
TemplateOperationMetricsController,
],
providers: [
AdminBrandConfigService,
@@ -40,6 +43,7 @@ import { AdminTemplatePreviewAssetsService } from "./admin-template-preview-asse
AdminTemplatePackageService,
AdminTemplatePreviewService,
AdminTemplatePreviewAssetsService,
TemplateOperationMetricsService,
],
})
export class AdminModule {}
@@ -0,0 +1,35 @@
import { HttpException } from "@nestjs/common";
import { PrismaService } from "../../prisma.service.js";
export async function recordTemplateOperationFailure(
prisma: PrismaService,
input: {
action: string;
error: unknown;
requestId?: string;
actorId?: string;
brandId?: string;
packageKey?: string;
version?: string;
},
): Promise<void> {
const status = input.error instanceof HttpException ? input.error.getStatus() : 500;
try {
await prisma.templateOperationFailureEvent.create({
data: {
action: input.action,
resultCode: `HTTP_${status}`,
...(input.requestId ? { requestId: input.requestId } : {}),
...(input.actorId ? { actorId: input.actorId } : {}),
...(input.brandId ? { brandId: input.brandId } : {}),
...(input.packageKey ? { packageKey: input.packageKey } : {}),
...(input.version ? { version: input.version } : {}),
},
});
await prisma.templateOperationFailureEvent.deleteMany({
where: { createdAt: { lt: new Date(Date.now() - 180 * 24 * 60 * 60 * 1000) } },
});
} catch {
// Failure telemetry must never replace the operation's original result.
}
}
@@ -0,0 +1,29 @@
import { Controller, Get, Query, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { Type } from "class-transformer";
import { IsInt, IsOptional, Max, Min } from "class-validator";
import { AdminAccessService } from "../../admin-access.service.js";
import { TemplateOperationMetricsService } from "./template-operation-metrics.service.js";
class TemplateOperationMetricsQueryDto {
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(1)
@Max(90)
days = 30;
}
@Controller("admin/template-operations")
export class TemplateOperationMetricsController {
constructor(
private readonly access: AdminAccessService,
private readonly metrics: TemplateOperationMetricsService,
) {}
@Get("failures")
async failures(@Req() request: FastifyRequest, @Query() query: TemplateOperationMetricsQueryDto) {
await this.access.requireTemplateAdmin(request);
return this.metrics.failures(query.days);
}
}
@@ -0,0 +1,52 @@
import { Injectable } from "@nestjs/common";
import { PrismaService } from "../../prisma.service.js";
const trackedActions = [
"import",
"preview",
"install",
"upgrade",
"rollback",
"install_conflict",
] as const;
@Injectable()
export class TemplateOperationMetricsService {
constructor(private readonly prisma: PrismaService) {}
async failures(days = 30) {
const since = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
const [templateEvents, releaseAttempts] = await Promise.all([
this.prisma.templateOperationFailureEvent.groupBy({
by: ["action"],
where: { createdAt: { gte: since } },
_count: { _all: true },
}),
this.prisma.miniAppReleaseAttempt.groupBy({
by: ["phase", "status"],
where: {
createdAt: { gte: since },
status: { in: ["failed", "timed_out"] },
},
_count: { _all: true },
}),
]);
const eventCounts = new Map(templateEvents.map((item) => [item.action, item._count._all]));
const buildUploadCounts = new Map<string, number>();
for (const item of releaseAttempts) {
const action = item.phase === "build" ? "build" : "upload";
buildUploadCounts.set(action, (buildUploadCounts.get(action) ?? 0) + item._count._all);
}
return {
since: since.toISOString(),
until: new Date().toISOString(),
days,
backfilled: false,
failures: [
...trackedActions.map((action) => ({ action, count: eventCounts.get(action) ?? 0 })),
{ action: "build", count: buildUploadCounts.get("build") ?? 0 },
{ action: "upload", count: buildUploadCounts.get("upload") ?? 0 },
],
};
}
}
@@ -1,11 +1,17 @@
import { Controller, Get, Post, Req } from "@nestjs/common";
import { Body, Controller, Get, Post, Req } from "@nestjs/common";
import type { FastifyRequest } from "fastify";
import { RollbackTemplateDto, UpgradeTemplateDto } from "../../admin.dto.js";
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
import { PrismaService } from "../../prisma.service.js";
import { recordTemplateOperationFailure } from "../admin/template-operation-failure.js";
import { requireAdminIdentity } from "./admin-access.identity.js";
@Controller("admin/workspace")
class AdminTemplateController {
constructor(private readonly templateWorkspace: TemplateWorkspaceService) {}
constructor(
private readonly templateWorkspace: TemplateWorkspaceService,
private readonly prisma: PrismaService,
) {}
@Get("template/preview")
preview(@Req() request: FastifyRequest): Promise<unknown> {
@@ -13,13 +19,58 @@ class AdminTemplateController {
}
@Post("template/upgrade")
upgrade(@Req() request: FastifyRequest): Promise<unknown> {
return this.templateWorkspace.upgrade(requireAdminIdentity(request).brandId);
async upgrade(
@Req() request: FastifyRequest,
@Body() body: UpgradeTemplateDto,
): Promise<unknown> {
const identity = requireAdminIdentity(request);
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
try {
return await this.templateWorkspace.upgrade(
identity.brandId,
body,
identity.subject,
requestId,
);
} catch (error) {
await recordTemplateOperationFailure(this.prisma, {
action:
error instanceof Error && error.name.includes("Conflict")
? "install_conflict"
: "upgrade",
error,
requestId,
actorId: identity.subject,
brandId: identity.brandId,
});
throw error;
}
}
@Post("template/rollback")
rollback(@Req() request: FastifyRequest): Promise<unknown> {
return this.templateWorkspace.rollback(requireAdminIdentity(request).brandId);
async rollback(
@Req() request: FastifyRequest,
@Body() body: RollbackTemplateDto,
): Promise<unknown> {
const identity = requireAdminIdentity(request);
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
try {
return await this.templateWorkspace.rollback(
identity.brandId,
identity.subject,
body,
requestId,
);
} catch (error) {
await recordTemplateOperationFailure(this.prisma, {
action: "rollback",
error,
requestId,
actorId: identity.subject,
brandId: identity.brandId,
});
throw error;
}
}
}
@@ -4,12 +4,15 @@ import { InstallTemplateDto } from "../../admin.dto.js";
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
import { requireAdminIdentity } from "./admin-access.identity.js";
import { AdminWorkspaceService } from "./admin-workspace.service.js";
import { PrismaService } from "../../prisma.service.js";
import { recordTemplateOperationFailure } from "../admin/template-operation-failure.js";
@Controller("admin/workspace")
class AdminWorkspacePreviewController {
constructor(
private readonly workspaceService: AdminWorkspaceService,
private readonly templateWorkspace: TemplateWorkspaceService,
private readonly prisma: PrismaService,
) {}
@Get()
@@ -23,12 +26,31 @@ class AdminWorkspacePreviewController {
}
@Post("install")
install(@Req() request: FastifyRequest, @Body() body: InstallTemplateDto): Promise<unknown> {
return this.templateWorkspace.install(
requireAdminIdentity(request).brandId,
body.templateKey,
body.templatePackageVersionId,
);
async install(
@Req() request: FastifyRequest,
@Body() body: InstallTemplateDto,
): Promise<unknown> {
const identity = requireAdminIdentity(request);
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
try {
return await this.templateWorkspace.install(
identity.brandId,
body.templateKey,
body.templatePackageVersionId,
);
} catch (error) {
await recordTemplateOperationFailure(this.prisma, {
action:
error instanceof Error && error.name.includes("Conflict")
? "install_conflict"
: "install",
error,
requestId,
actorId: identity.subject,
brandId: identity.brandId,
});
throw error;
}
}
}
+379 -44
View File
@@ -1,6 +1,8 @@
import { BadRequestException, Injectable } from "@nestjs/common";
import { BadRequestException, ConflictException, Injectable } from "@nestjs/common";
import type { TemplatePackageVersion } from "@prisma/client";
import { Prisma } from "@prisma/client";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import {
type BrandTemplateKey,
defaultBrandTemplateKey,
@@ -12,8 +14,11 @@ import {
isVisualTemplateCompatible,
} from "@personal-brand/config";
import type { CreateTrustContentDto, UpdateTrustContentDto } from "./admin.dto.js";
import type { RollbackTemplateDto, UpgradeTemplateDto } from "./admin.dto.js";
import { PrismaService } from "./prisma.service.js";
const execFileAsync = promisify(execFile);
@Injectable()
export class TemplateWorkspaceService {
constructor(private readonly prisma: PrismaService) {}
@@ -230,65 +235,230 @@ export class TemplateWorkspaceService {
const templateKey = await this.getEffectiveTemplateKey(brandId);
const template = getBrandTemplate(templateKey);
if (!template) throw new BadRequestException("当前行业模板不存在");
const [installation, fields] = await Promise.all([
const [installation, brand] = await Promise.all([
this.prisma.brandTemplateInstallation.findFirst({ where: { brandId } }),
this.prisma.brandFieldDefinition.findMany({ where: { brandId } }),
this.prisma.brandProfile.findUnique({ where: { id: brandId }, select: { config: true } }),
]);
// 品牌一直有行业模板,但版本台账可能还没建立;此时以模板目录的版本为准,不报错。
const currentVersion = installation?.templateVersion ?? template.version;
const config = record(brand?.config);
const visualTemplateKey =
installation?.visualTemplateKey ??
(typeof config.visualTemplateKey === "string" ? config.visualTemplateKey : undefined) ??
getDefaultVisualTemplateKey(templateKey);
const currentPackage = installation?.templatePackageVersionId
? await this.prisma.templatePackageVersion.findUnique({
where: { id: installation.templatePackageVersionId },
})
: null;
const targetPackage = visualTemplateKey
? await this.prisma.templatePackageVersion.findFirst({
where: { packageKey: visualTemplateKey, status: "published" },
orderBy: { importedAt: "desc" },
})
: null;
const targetManifest = record(targetPackage?.manifestSnapshot);
const currentManifest = record(currentPackage?.manifestSnapshot);
const currentDeclarations = manifestRecords(currentManifest.templateFields);
const targetDeclarations = manifestRecords(targetManifest.templateFields);
const currentByKey = new Map(currentDeclarations.map((item) => [String(item.key), item]));
const targetByKey = new Map(targetDeclarations.map((item) => [String(item.key), item]));
const addedBindings = targetDeclarations.filter((item) => !currentByKey.has(String(item.key)));
const removedBindings = currentDeclarations.filter(
(item) => !targetByKey.has(String(item.key)),
);
const changedBindings = targetDeclarations.flatMap((item) => {
const current = currentByKey.get(String(item.key));
if (!current || JSON.stringify(current) === JSON.stringify(item)) return [];
return [{ key: String(item.key), current, proposed: item }];
});
const conflicts = [
...addedBindings.flatMap((item) =>
hasBindingValue(config, item.binding)
? [
{
key: String(item.key),
binding: String(item.binding),
reason: "新增字段已有同路径品牌值,升级会原样保留",
},
]
: [],
),
...changedBindings.flatMap(({ key, current }) =>
hasBindingValue(config, current.binding)
? [{ key, binding: String(current.binding), reason: "该品牌配置已填写,升级不会覆盖" }]
: [],
),
...removedBindings.flatMap((item) =>
hasBindingValue(config, item.binding)
? [
{
key: String(item.key),
binding: String(item.binding),
reason: "新版不再声明该字段,已有品牌值仍会保留",
},
]
: [],
),
];
const currentEntrypoints = record(currentManifest.entrypoints);
const targetEntrypoints = record(targetManifest.entrypoints);
const currentAssets = manifestRecords(currentManifest.assetSlots);
const targetAssets = manifestRecords(targetManifest.assetSlots);
const [currentFiles, targetFiles] = await Promise.all([
currentPackage ? readPackageFiles(currentPackage) : Promise.resolve([]),
targetPackage ? readPackageFiles(targetPackage) : Promise.resolve([]),
]);
const currentCapabilities = stringList(currentManifest.requiredCapabilities);
const targetCapabilities = stringList(targetManifest.requiredCapabilities);
const visualManifest = getVisualTemplateManifest(visualTemplateKey);
return {
templateKey,
currentVersion,
latestVersion: template.version,
canUpgrade: currentVersion !== template.version,
latestVersion: targetPackage?.version ?? template.version,
currentPackageVersionId: currentPackage?.id ?? null,
currentContentChecksum:
currentPackage?.contentChecksum ?? installation?.contentChecksum ?? null,
targetPackageVersionId: targetPackage?.id ?? null,
targetContentChecksum: targetPackage?.contentChecksum ?? null,
canUpgrade: Boolean(targetPackage && targetPackage.id !== currentPackage?.id),
canRollback:
Array.isArray(installation?.previousSnapshots) && installation.previousSnapshots.length > 0,
missingFields: template.fields.filter(
(item) =>
!fields.some((current) => current.scope === item.scope && current.key === item.key),
),
changes: {
brandFields: { available: false, reason: "行业字段不由视觉模板包声明" },
templateBindings: {
added: addedBindings,
changed: changedBindings,
removed: removedBindings,
},
pages: compareRecords(currentEntrypoints, targetEntrypoints),
modules: {
available: Boolean(visualManifest),
source: "platform_visual_manifest",
packageUpgradeChangesRenderer: false,
pages:
visualManifest?.pages.map((page) => ({
key: page.key,
renderer: page.renderer ?? null,
modules: page.modules,
})) ?? [],
},
assets: {
slots: compareKeyedRecords(currentAssets, targetAssets),
files: compareFiles(currentFiles, targetFiles),
},
capabilities: {
added: targetCapabilities.filter((item) => !currentCapabilities.includes(item)),
removed: currentCapabilities.filter((item) => !targetCapabilities.includes(item)),
},
renderer: {
available: Boolean(visualManifest),
source: "platform_visual_manifest",
packageUpgradeChangesRenderer: false,
pages:
visualManifest?.pages.map((page) => ({
key: page.key,
renderer: page.renderer ?? null,
})) ?? [],
},
package: {
currentContentChecksum: currentPackage?.contentChecksum ?? null,
targetContentChecksum: targetPackage?.contentChecksum ?? null,
runtimeContract: {
current: currentManifest.runtimeContract ?? null,
target: targetManifest.runtimeContract ?? null,
},
},
},
conflicts,
};
}
async upgrade(brandId: string) {
async upgrade(brandId: string, body: UpgradeTemplateDto, actorId: string, requestId?: string) {
if (!body.confirm) throw new BadRequestException("升级模板必须显式确认");
const installation = await this.installation(brandId);
const template = getBrandTemplate(installation.templateKey);
if (!template) throw new BadRequestException("已安装模板不存在");
if (installation.templateVersion === template.version)
throw new BadRequestException("当前模板已经是最新版本");
const target = await this.prisma.templatePackageVersion.findUnique({
where: { id: body.templatePackageVersionId },
});
if (!target || target.status !== "published")
throw new BadRequestException("目标模板包版本不存在或未发布");
if (target.contentChecksum !== body.expectedContentChecksum)
throw new ConflictException("目标模板包内容已变化,请重新预览升级差异");
if (installation.templateVersion !== body.expectedCurrentVersion)
throw new ConflictException("品牌模板版本已变化,请重新预览升级差异");
if (
(body.expectedCurrentPackageVersionId ?? null) !==
(installation.templatePackageVersionId ?? null)
)
throw new ConflictException("当前模板包版本已变化,请重新预览升级差异");
const preview = await this.preview(brandId);
const expectedConflicts = preview.conflicts
.map(({ key, binding }) => `${key}\u0000${binding}`)
.sort();
const preserved = body.preservedBindings
.map(({ key, binding, action }) => {
if (action !== "preserve") throw new BadRequestException("当前只允许保留已有品牌配置");
return `${key}\u0000${binding}`;
})
.sort();
if (JSON.stringify(expectedConflicts) !== JSON.stringify(preserved))
throw new ConflictException("冲突处理与当前预览不一致,请重新预览并逐项确认");
const manifest = record(target.manifestSnapshot);
if (
target.packageKey !== installation.visualTemplateKey ||
manifest.packageKey !== target.packageKey ||
manifest.version !== target.version ||
!Array.isArray(manifest.supportedIndustryTemplates) ||
!manifest.supportedIndustryTemplates.includes(installation.templateKey)
)
throw new BadRequestException("目标模板包与当前品牌安装不兼容");
return this.prisma.$transaction(async (tx) => {
const fields = await tx.brandFieldDefinition.findMany({ where: { brandId } });
const addedFields = template.fields.filter(
(item) =>
!fields.some((current) => current.scope === item.scope && current.key === item.key),
);
await tx.brandFieldDefinition.createMany({
data: addedFields.map(({ scope, key, label, type, required }, index) => ({
brandId,
scope,
key,
label,
type,
required,
sortOrder: fields.length + index,
source: "template",
})),
});
const history = Array.isArray(installation.previousSnapshots)
? installation.previousSnapshots
: [];
const updated = await tx.brandTemplateInstallation.update({
where: { id: installation.id },
const claimed = await tx.brandTemplateInstallation.updateMany({
where: {
id: installation.id,
templateVersion: body.expectedCurrentVersion,
templatePackageVersionId: installation.templatePackageVersionId,
},
data: {
templateVersion: template.version,
configSnapshot: template as unknown as Prisma.InputJsonValue,
templatePackageVersionId: target.id,
contentChecksum: target.contentChecksum,
templateVersion: target.version,
configSnapshot: manifest as Prisma.InputJsonValue,
previousSnapshots: [...history, installation.configSnapshot],
},
});
return { installation: updated, addedFields };
if (claimed.count !== 1)
throw new ConflictException("品牌模板版本已变化,请重新预览升级差异");
const updated = await tx.brandTemplateInstallation.findUniqueOrThrow({
where: { id: installation.id },
});
await tx.templatePackageAuditLog.create({
data: {
templatePackageVersionId: target.id,
actorId,
action: "brand_upgrade",
...(requestId ? { requestId } : {}),
metadata: {
brandId,
fromVersionId: installation.templatePackageVersionId,
fromVersion: installation.templateVersion,
toVersionId: target.id,
toVersion: target.version,
contentChecksum: target.contentChecksum,
preservedBindings: body.preservedBindings.map(({ key, binding }) => ({ key, binding })),
},
},
});
return { installation: updated, preservedBindings: body.preservedBindings };
});
}
async rollback(brandId: string) {
async rollback(brandId: string, actorId: string, body: RollbackTemplateDto, requestId?: string) {
if (!body.confirm) throw new BadRequestException("回滚模板必须显式确认");
const installation = await this.installation(brandId);
if (installation.templateVersion !== body.expectedCurrentVersion)
throw new ConflictException("品牌模板版本已变化,请刷新后重试回滚");
const history = Array.isArray(installation.previousSnapshots)
? installation.previousSnapshots
: [];
@@ -297,13 +467,55 @@ export class TemplateWorkspaceService {
throw new BadRequestException("没有可回滚的模板版本");
const version = (previous as { version?: unknown }).version;
if (typeof version !== "string") throw new BadRequestException("模板快照无效");
const updated = await this.prisma.brandTemplateInstallation.update({
where: { id: installation.id },
data: {
templateVersion: version,
configSnapshot: previous,
previousSnapshots: history.slice(0, -1),
},
const previousManifest = record(previous);
const previousPackage =
typeof previousManifest.packageKey === "string"
? await this.prisma.templatePackageVersion.findFirst({
where: { packageKey: previousManifest.packageKey, version },
})
: null;
if (
previousPackage &&
(previousPackage.packageKey !== installation.visualTemplateKey ||
!stringList(record(previousPackage.manifestSnapshot).supportedIndustryTemplates).includes(
installation.templateKey,
))
)
throw new BadRequestException("上一版模板包与当前品牌行业或视觉模板不兼容");
const updated = await this.prisma.$transaction(async (tx) => {
const changed = await tx.brandTemplateInstallation.updateMany({
where: {
id: installation.id,
templateVersion: installation.templateVersion,
templatePackageVersionId: installation.templatePackageVersionId,
},
data: {
templateVersion: version,
templatePackageVersionId: previousPackage?.id ?? null,
contentChecksum: previousPackage?.contentChecksum ?? null,
configSnapshot: previous,
previousSnapshots: history.slice(0, -1),
},
});
if (changed.count !== 1) throw new ConflictException("品牌模板版本已变化,请刷新后重试回滚");
if (installation.templatePackageVersionId) {
await tx.templatePackageAuditLog.create({
data: {
templatePackageVersionId: installation.templatePackageVersionId,
actorId,
action: "brand_rollback",
...(requestId ? { requestId } : {}),
metadata: {
brandId,
fromVersionId: installation.templatePackageVersionId,
fromVersion: installation.templateVersion,
toVersionId: previousPackage?.id ?? null,
toVersion: version,
},
},
});
}
return tx.brandTemplateInstallation.findUniqueOrThrow({ where: { id: installation.id } });
});
return {
installation: updated,
@@ -312,8 +524,131 @@ export class TemplateWorkspaceService {
}
}
async function readPackageFiles(
version: Pick<
TemplatePackageVersion,
"artifactPath" | "validationReport" | "packageKey" | "version"
>,
): Promise<Record<string, unknown>[]> {
const stored = manifestRecords(record(version.validationReport).files);
if (stored.length) return stored;
const root = `${version.packageKey}-${version.version}`;
const checksumEntry = `${root}/checksums.json`;
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(version.packageKey) || root.includes("/")) return [];
try {
const { stdout: entries } = await execFileAsync("tar", ["-tzf", version.artifactPath], {
maxBuffer: 4 * 1024 * 1024,
});
if (!entries.split("\n").some((entry) => entry === checksumEntry)) return [];
const { stdout } = await execFileAsync("tar", ["-xOzf", version.artifactPath, checksumEntry], {
maxBuffer: 4 * 1024 * 1024,
});
return manifestRecords(record(JSON.parse(stdout)).files);
} catch {
return [];
}
}
function record(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
}
function manifestRecords(value: unknown): Record<string, unknown>[] {
return Array.isArray(value)
? value.filter((item): item is Record<string, unknown> =>
Boolean(item && typeof item === "object" && !Array.isArray(item)),
)
: [];
}
function stringList(value: unknown): string[] {
return Array.isArray(value)
? value.filter((item): item is string => typeof item === "string")
: [];
}
function hasBindingValue(config: Record<string, unknown>, binding: unknown): boolean {
if (typeof binding !== "string" || !binding.startsWith("brand.config.")) return false;
const value = binding
.slice("brand.config.".length)
.split(".")
.reduce<unknown>((current, key) => record(current)[key], config);
return value !== undefined && value !== null && value !== "";
}
function compareRecords(current: Record<string, unknown>, target: Record<string, unknown>) {
const currentKeys = Object.keys(current);
const targetKeys = Object.keys(target);
return {
added: targetKeys
.filter((key) => !(key in current))
.map((key) => ({ key, target: target[key] })),
removed: currentKeys
.filter((key) => !(key in target))
.map((key) => ({ key, current: current[key] })),
changed: targetKeys
.filter(
(key) => key in current && JSON.stringify(current[key]) !== JSON.stringify(target[key]),
)
.map((key) => ({ key, current: current[key], target: target[key] })),
};
}
function compareKeyedRecords(
current: Record<string, unknown>[],
target: Record<string, unknown>[],
) {
const currentByKey = new Map(
current
.filter((item) => typeof item.key === "string")
.map((item) => [item.key as string, item]),
);
const targetByKey = new Map(
target.filter((item) => typeof item.key === "string").map((item) => [item.key as string, item]),
);
return {
added: [...targetByKey].filter(([key]) => !currentByKey.has(key)).map(([, item]) => item),
removed: [...currentByKey].filter(([key]) => !targetByKey.has(key)).map(([, item]) => item),
changed: [...targetByKey].flatMap(([key, item]) => {
const previous = currentByKey.get(key);
return previous && JSON.stringify(previous) !== JSON.stringify(item)
? [{ key, current: previous, target: item }]
: [];
}),
};
}
function compareFiles(current: Record<string, unknown>[], target: Record<string, unknown>[]) {
const currentByPath = new Map(
current
.filter((item) => typeof item.path === "string")
.map((item) => [item.path as string, item]),
);
const targetByPath = new Map(
target
.filter((item) => typeof item.path === "string")
.map((item) => [item.path as string, item]),
);
const available = currentByPath.size > 0 && targetByPath.size > 0;
return {
available,
...(available
? {
added: [...targetByPath]
.filter(([path]) => !currentByPath.has(path))
.map(([, item]) => item),
removed: [...currentByPath]
.filter(([path]) => !targetByPath.has(path))
.map(([, item]) => item),
changed: [...targetByPath].flatMap(([path, item]) => {
const previous = currentByPath.get(path);
return previous && previous.sha256 !== item.sha256
? [{ path, current: previous, target: item }]
: [];
}),
}
: { reason: "版本验证报告未包含完整文件清单" }),
};
}