feat: 收口小程序构建上传阶段
This commit is contained in:
1 parent
6420b85019
commit
ec16fff70e
23 files changed
+1185
-104
No files matched your search
@@ -1,20 +1,22 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { spawn } from "node:child_process";
|
||||
import { REPOSITORY_ROOT } from "./miniapp-artifact.js";
|
||||
import { miniappBuildTimeoutMs } from "./miniapp-build-status.js";
|
||||
|
||||
interface BuildProcess {
|
||||
stdout: NodeJS.ReadableStream;
|
||||
stderr: NodeJS.ReadableStream;
|
||||
on: (event: "close" | "error", listener: (code: number | null) => void) => void;
|
||||
kill: (signal?: NodeJS.Signals) => boolean;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AdminMiniAppBuildService {
|
||||
run(
|
||||
templateKey: string,
|
||||
buildConfig: { apiBaseUrl: string; appId: string },
|
||||
buildConfig: { apiBaseUrl: string; appId: string; outputRoot: string },
|
||||
onLog: (message: string, stream: "stdout" | "stderr") => void,
|
||||
): Promise<{ exitCode: number }> {
|
||||
): Promise<{ exitCode: number; timedOut?: boolean }> {
|
||||
return new Promise((resolvePromise, rejectPromise) => {
|
||||
const child = spawn("pnpm", ["--filter", "@personal-brand/taro", "build:weapp"], {
|
||||
cwd: REPOSITORY_ROOT,
|
||||
@@ -24,6 +26,7 @@ export class AdminMiniAppBuildService {
|
||||
TARO_ENV: "weapp",
|
||||
API_BASE_URL: buildConfig.apiBaseUrl,
|
||||
WEAPP_APP_ID: buildConfig.appId,
|
||||
MINIAPP_OUTPUT_ROOT: buildConfig.outputRoot,
|
||||
},
|
||||
shell: process.platform === "win32",
|
||||
}) as BuildProcess;
|
||||
@@ -40,8 +43,26 @@ export class AdminMiniAppBuildService {
|
||||
};
|
||||
readStream(child.stdout, "stdout");
|
||||
readStream(child.stderr, "stderr");
|
||||
child.on("close", (code) => resolvePromise({ exitCode: code ?? 1 }));
|
||||
child.on("error", () => rejectPromise(new Error("小程序构建进程启动失败")));
|
||||
let settled = false;
|
||||
const timer = setTimeout(() => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
onLog("构建超过允许时长,已终止构建进程", "stderr");
|
||||
child.kill("SIGKILL");
|
||||
resolvePromise({ exitCode: 124, timedOut: true });
|
||||
}, miniappBuildTimeoutMs());
|
||||
child.on("close", (code) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
resolvePromise({ exitCode: code ?? 1 });
|
||||
});
|
||||
child.on("error", () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
rejectPromise(new Error("小程序构建进程启动失败"));
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -5,8 +5,33 @@ import {
|
||||
NotFoundException,
|
||||
} from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
|
||||
const DEFAULT_ATTEMPT_LEASE_MS = 30 * 60 * 1000;
|
||||
type AttemptPhase = "build" | "upload";
|
||||
type AttemptStatus = "running" | "succeeded" | "failed" | "timed_out";
|
||||
const attemptResponseSelect = {
|
||||
id: true,
|
||||
phase: true,
|
||||
attempt: true,
|
||||
status: true,
|
||||
leaseExpiresAt: true,
|
||||
startedAt: true,
|
||||
heartbeatAt: true,
|
||||
finishedAt: true,
|
||||
artifactPath: true,
|
||||
externalId: true,
|
||||
error: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
} as const;
|
||||
|
||||
export function miniAppAttemptLeaseMs(configured = process.env.MINIAPP_ATTEMPT_LEASE_MS): number {
|
||||
const parsed = Number(configured);
|
||||
return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_ATTEMPT_LEASE_MS;
|
||||
}
|
||||
|
||||
const transitions: Record<string, string[]> = {
|
||||
built: ["uploaded", "under_review", "failed"],
|
||||
uploaded: ["under_review", "failed"],
|
||||
@@ -24,10 +49,22 @@ export class AdminMiniAppReleaseService {
|
||||
async latest(brandId: string) {
|
||||
return this.prisma.miniAppReleaseTask.findFirst({
|
||||
where: { brandId },
|
||||
include: {
|
||||
attempts: { select: attemptResponseSelect, orderBy: { createdAt: "asc" } },
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
}
|
||||
|
||||
async get(brandId: string, taskId: string) {
|
||||
return this.prisma.miniAppReleaseTask.findFirst({
|
||||
where: { id: taskId, brandId },
|
||||
include: {
|
||||
attempts: { select: attemptResponseSelect, orderBy: { createdAt: "asc" } },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async settings(brandId: string) {
|
||||
const brand = await this.prisma.brandProfile.findUnique({
|
||||
where: { id: brandId },
|
||||
@@ -41,7 +78,7 @@ export class AdminMiniAppReleaseService {
|
||||
this.prisma.miniAppReleaseTask.findFirst({ where: { id: taskId, brandId } }),
|
||||
this.prisma.brandProfile.findUniqueOrThrow({
|
||||
where: { id: brandId },
|
||||
select: { miniAppSettings: true, templateKey: true },
|
||||
select: { miniAppSettings: true, templateKey: true, slug: true },
|
||||
}),
|
||||
]);
|
||||
if (!task) throw new BadRequestException("小程序发布任务不存在");
|
||||
@@ -58,6 +95,9 @@ export class AdminMiniAppReleaseService {
|
||||
async list(brandId: string): Promise<unknown[]> {
|
||||
return this.prisma.miniAppReleaseTask.findMany({
|
||||
where: { brandId },
|
||||
include: {
|
||||
attempts: { select: attemptResponseSelect, orderBy: { createdAt: "asc" } },
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 50,
|
||||
});
|
||||
@@ -129,6 +169,10 @@ export class AdminMiniAppReleaseService {
|
||||
? { buildLogs: input.buildLogs as Prisma.InputJsonValue }
|
||||
: {}),
|
||||
...(input.buildStatus ? { buildStatus: input.buildStatus } : {}),
|
||||
...(input.status === "uploaded" ? { uploadStatus: "uploaded" } : {}),
|
||||
...(input.status === "under_review" ? { reviewStatus: "under_review" } : {}),
|
||||
...(input.status === "approved" ? { reviewStatus: "approved" } : {}),
|
||||
...(input.status === "rejected" ? { reviewStatus: "rejected" } : {}),
|
||||
audit,
|
||||
},
|
||||
});
|
||||
@@ -149,6 +193,7 @@ export class AdminMiniAppReleaseService {
|
||||
buildStatus?: "idle" | "building" | "success" | "failed";
|
||||
error?: string | null;
|
||||
buildLogs?: unknown;
|
||||
artifactPath?: string | null;
|
||||
},
|
||||
): Promise<unknown> {
|
||||
const task = await this.prisma.miniAppReleaseTask.findFirst({
|
||||
@@ -164,6 +209,7 @@ export class AdminMiniAppReleaseService {
|
||||
...(input.buildLogs !== undefined
|
||||
? { buildLogs: input.buildLogs as Prisma.InputJsonValue }
|
||||
: {}),
|
||||
...(input.artifactPath !== undefined ? { artifactPath: input.artifactPath } : {}),
|
||||
...(input.buildStatus ? { buildStatus: input.buildStatus } : {}),
|
||||
...(buildStatusChanged
|
||||
? {
|
||||
@@ -180,6 +226,222 @@ export class AdminMiniAppReleaseService {
|
||||
});
|
||||
}
|
||||
|
||||
async acquireAttempt(
|
||||
brandId: string,
|
||||
actorId: string,
|
||||
taskId: string,
|
||||
phase: AttemptPhase,
|
||||
): Promise<{ id: string; leaseToken: string; attempt: number; leaseExpiresAt: Date }> {
|
||||
try {
|
||||
return await this.prisma.$transaction(
|
||||
async (tx) => {
|
||||
const task = await tx.miniAppReleaseTask.findFirst({
|
||||
where: { id: taskId, brandId },
|
||||
});
|
||||
if (!task) throw new NotFoundException("小程序发布任务不存在");
|
||||
|
||||
const now = new Date();
|
||||
const active = await tx.miniAppReleaseAttempt.findFirst({
|
||||
where: { taskId, phase, status: "running" },
|
||||
orderBy: { attempt: "desc" },
|
||||
});
|
||||
if (active) {
|
||||
if (active.leaseExpiresAt > now)
|
||||
throw new ConflictException("该小程序操作正在进行中,请稍后");
|
||||
await tx.miniAppReleaseAttempt.update({
|
||||
where: { id: active.id },
|
||||
data: {
|
||||
status: "timed_out",
|
||||
error: "操作租约已过期,按中断处理",
|
||||
finishedAt: now,
|
||||
},
|
||||
});
|
||||
await tx.miniAppReleaseTask.update({
|
||||
where: { id: taskId },
|
||||
data:
|
||||
phase === "build"
|
||||
? { buildStatus: "failed", error: "操作租约已过期,按中断处理" }
|
||||
: { uploadStatus: "timed_out", error: "操作租约已过期,按中断处理" },
|
||||
});
|
||||
}
|
||||
|
||||
const previous = await tx.miniAppReleaseAttempt.findFirst({
|
||||
where: { taskId, phase },
|
||||
orderBy: { attempt: "desc" },
|
||||
select: { attempt: true },
|
||||
});
|
||||
const leaseExpiresAt = new Date(now.getTime() + miniAppAttemptLeaseMs());
|
||||
const created = await tx.miniAppReleaseAttempt.create({
|
||||
data: {
|
||||
taskId,
|
||||
brandId,
|
||||
actorId,
|
||||
phase,
|
||||
attempt: (previous?.attempt ?? 0) + 1,
|
||||
leaseToken: randomBytes(32).toString("hex"),
|
||||
leaseExpiresAt,
|
||||
},
|
||||
});
|
||||
await tx.miniAppReleaseTask.update({
|
||||
where: { id: taskId },
|
||||
data:
|
||||
phase === "build"
|
||||
? { buildStatus: "building", error: null }
|
||||
: { uploadStatus: "uploading", error: null },
|
||||
});
|
||||
return {
|
||||
id: created.id,
|
||||
leaseToken: created.leaseToken,
|
||||
attempt: created.attempt,
|
||||
leaseExpiresAt: created.leaseExpiresAt,
|
||||
};
|
||||
},
|
||||
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable },
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2034")
|
||||
throw new ConflictException("该小程序操作刚被其他请求占用,请刷新后重试");
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async heartbeatAttempt(
|
||||
brandId: string,
|
||||
attemptId: string,
|
||||
leaseToken: string,
|
||||
input: { logs?: unknown; artifactPath?: string },
|
||||
): Promise<unknown> {
|
||||
const attempt = await this.prisma.miniAppReleaseAttempt.findFirst({
|
||||
where: { id: attemptId, brandId },
|
||||
});
|
||||
if (!attempt) throw new NotFoundException("小程序操作记录不存在");
|
||||
const now = new Date();
|
||||
if (attempt.status !== "running" || attempt.leaseToken !== leaseToken)
|
||||
throw new ConflictException("小程序操作租约已失效");
|
||||
if (attempt.leaseExpiresAt <= now) {
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
await tx.miniAppReleaseAttempt.updateMany({
|
||||
where: { id: attempt.id, brandId, status: "running", leaseToken },
|
||||
data: { status: "timed_out", finishedAt: now, error: "操作租约已过期" },
|
||||
});
|
||||
await tx.miniAppReleaseTask.update({
|
||||
where: { id: attempt.taskId },
|
||||
data:
|
||||
attempt.phase === "build"
|
||||
? { buildStatus: "failed", error: "操作租约已过期" }
|
||||
: { uploadStatus: "timed_out", error: "操作租约已过期" },
|
||||
});
|
||||
});
|
||||
throw new ConflictException("小程序操作租约已过期");
|
||||
}
|
||||
const updateResult = await this.prisma.miniAppReleaseAttempt.updateMany({
|
||||
where: {
|
||||
id: attempt.id,
|
||||
brandId,
|
||||
status: "running",
|
||||
leaseToken,
|
||||
leaseExpiresAt: { gt: now },
|
||||
},
|
||||
data: {
|
||||
heartbeatAt: now,
|
||||
leaseExpiresAt: new Date(now.getTime() + miniAppAttemptLeaseMs()),
|
||||
...(input.logs !== undefined ? { logs: input.logs as Prisma.InputJsonValue } : {}),
|
||||
...(input.artifactPath ? { artifactPath: input.artifactPath } : {}),
|
||||
},
|
||||
});
|
||||
if (updateResult.count !== 1) throw new ConflictException("小程序操作租约已失效");
|
||||
const updated = await this.prisma.miniAppReleaseAttempt.findFirst({
|
||||
where: { id: attempt.id, brandId },
|
||||
});
|
||||
if (input.logs !== undefined && attempt.phase === "build") {
|
||||
await this.prisma.miniAppReleaseTask.update({
|
||||
where: { id: attempt.taskId },
|
||||
data: { buildLogs: input.logs as Prisma.InputJsonValue },
|
||||
});
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
async finishAttempt(
|
||||
brandId: string,
|
||||
attemptId: string,
|
||||
leaseToken: string,
|
||||
input: {
|
||||
status: Exclude<AttemptStatus, "running">;
|
||||
error?: string | null;
|
||||
logs?: unknown;
|
||||
artifactPath?: string | null;
|
||||
externalId?: string | null;
|
||||
},
|
||||
): Promise<unknown> {
|
||||
const result = await this.prisma.$transaction(
|
||||
async (tx) => {
|
||||
const attempt = await tx.miniAppReleaseAttempt.findFirst({
|
||||
where: { id: attemptId, brandId },
|
||||
});
|
||||
if (!attempt) throw new NotFoundException("小程序操作记录不存在");
|
||||
const now = new Date();
|
||||
if (attempt.status !== "running" || attempt.leaseToken !== leaseToken)
|
||||
throw new ConflictException("小程序操作租约已失效");
|
||||
if (attempt.leaseExpiresAt <= now && input.status !== "timed_out") {
|
||||
await tx.miniAppReleaseAttempt.update({
|
||||
where: { id: attempt.id },
|
||||
data: { status: "timed_out", finishedAt: now, error: "操作租约已过期" },
|
||||
});
|
||||
await tx.miniAppReleaseTask.update({
|
||||
where: { id: attempt.taskId },
|
||||
data:
|
||||
attempt.phase === "build"
|
||||
? { buildStatus: "failed", error: "操作租约已过期" }
|
||||
: { uploadStatus: "timed_out", error: "操作租约已过期" },
|
||||
});
|
||||
return { expired: true as const, finished: null };
|
||||
}
|
||||
const finished = await tx.miniAppReleaseAttempt.update({
|
||||
where: { id: attempt.id },
|
||||
data: {
|
||||
status: input.status,
|
||||
finishedAt: now,
|
||||
heartbeatAt: now,
|
||||
...(input.error !== undefined ? { error: input.error } : {}),
|
||||
...(input.logs !== undefined ? { logs: input.logs as Prisma.InputJsonValue } : {}),
|
||||
...(input.artifactPath !== undefined ? { artifactPath: input.artifactPath } : {}),
|
||||
...(input.externalId !== undefined ? { externalId: input.externalId } : {}),
|
||||
},
|
||||
});
|
||||
const taskData: Prisma.MiniAppReleaseTaskUpdateInput =
|
||||
attempt.phase === "build"
|
||||
? {
|
||||
buildStatus:
|
||||
input.status === "succeeded" ? ("success" as const) : ("failed" as const),
|
||||
...(input.error !== undefined ? { error: input.error } : {}),
|
||||
...(input.logs !== undefined
|
||||
? { buildLogs: input.logs as Prisma.InputJsonValue }
|
||||
: {}),
|
||||
...(input.artifactPath !== undefined ? { artifactPath: input.artifactPath } : {}),
|
||||
}
|
||||
: {
|
||||
uploadStatus:
|
||||
input.status === "succeeded"
|
||||
? ("uploaded" as const)
|
||||
: input.status === "timed_out"
|
||||
? ("timed_out" as const)
|
||||
: ("failed" as const),
|
||||
...(input.error !== undefined ? { error: input.error } : {}),
|
||||
...(input.externalId
|
||||
? { weappUploadId: input.externalId, status: "uploaded" as const }
|
||||
: {}),
|
||||
...(input.status !== "succeeded" ? { status: "failed" as const } : {}),
|
||||
};
|
||||
await tx.miniAppReleaseTask.update({ where: { id: attempt.taskId }, data: taskData });
|
||||
return { expired: false as const, finished };
|
||||
},
|
||||
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable },
|
||||
);
|
||||
if (result.expired) throw new ConflictException("小程序操作租约已过期");
|
||||
return result.finished;
|
||||
}
|
||||
|
||||
private audit(value: Prisma.JsonValue | null, entry: Record<string, unknown>) {
|
||||
return [...(Array.isArray(value) ? value : []), entry] as Prisma.InputJsonValue[];
|
||||
}
|
||||
|
||||
@@ -8,8 +8,15 @@ import { existsSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { getTemplatePackageManifest, templatePackageRegistry } from "@personal-brand/config";
|
||||
import { AdminMiniAppBuildService } from "./admin-miniapp-build.service.js";
|
||||
import { AdminMiniAppReleaseService } from "./admin-miniapp-release.service.js";
|
||||
import { miniappProjectPath } from "./miniapp-artifact.js";
|
||||
import {
|
||||
AdminMiniAppReleaseService,
|
||||
miniAppAttemptLeaseMs,
|
||||
} from "./admin-miniapp-release.service.js";
|
||||
import {
|
||||
miniappReleaseOutputRoot,
|
||||
miniappReleaseProjectPath,
|
||||
miniappTaroOutputRoot,
|
||||
} from "./miniapp-artifact.js";
|
||||
import { miniappApiBaseUrl, weappAppId } from "./miniapp-build-config.js";
|
||||
import { buildingStaleMs, isStaleBuilding } from "./miniapp-build-status.js";
|
||||
import { decryptMiniAppCredential } from "./miniapp-credential-crypto.js";
|
||||
@@ -22,12 +29,12 @@ interface BuildLog {
|
||||
stream: "stdout" | "stderr";
|
||||
}
|
||||
|
||||
function miniAppTemplateKey(industryTemplateKey: string): string | null {
|
||||
function miniAppTemplateManifest(industryTemplateKey: string) {
|
||||
return (
|
||||
getTemplatePackageManifest(industryTemplateKey)?.packageKey ??
|
||||
getTemplatePackageManifest(industryTemplateKey) ??
|
||||
templatePackageRegistry.find((item) =>
|
||||
item.supportedIndustryTemplates.includes(industryTemplateKey),
|
||||
)?.packageKey ??
|
||||
) ??
|
||||
null
|
||||
);
|
||||
}
|
||||
@@ -68,66 +75,115 @@ export class AdminMiniAppUploadService {
|
||||
`上传私钥无法解析(${keyInspection.reason ?? "PEM 格式错误"})。请在“小程序上传配置”里重新粘贴完整私钥。`,
|
||||
);
|
||||
|
||||
const templateKey = miniAppTemplateKey(brand.templateKey);
|
||||
if (!templateKey) throw new BadRequestException("当前品牌模板没有可上传的小程序包");
|
||||
const templateManifest = miniAppTemplateManifest(brand.templateKey);
|
||||
if (!templateManifest) throw new BadRequestException("当前品牌模板没有可上传的小程序包");
|
||||
const templateKey = templateManifest.packageKey;
|
||||
const buildConfig = { apiBaseUrl: miniappApiBaseUrl(settings.apiBaseUrl), appId };
|
||||
const projectPath = miniappProjectPath(templateKey);
|
||||
const buildLogs = [
|
||||
log(`开始构建 ${templateKey} 微信小程序`, "stdout"),
|
||||
log(`请求地址 ${buildConfig.apiBaseUrl},AppID ${buildConfig.appId}`, "stdout"),
|
||||
];
|
||||
if (staleBuilding)
|
||||
buildLogs.push(
|
||||
log(
|
||||
`上一次构建已超过 ${Math.round(buildingStaleMs() / 60000)} 分钟没有进展,按中断处理并重新构建`,
|
||||
"stderr",
|
||||
),
|
||||
);
|
||||
let projectPath = typeof task.artifactPath === "string" ? task.artifactPath : null;
|
||||
const canReuseArtifact =
|
||||
(task.status === "built" || task.status === "failed") &&
|
||||
task.buildStatus === "success" &&
|
||||
projectPath !== null &&
|
||||
existsSync(projectPath) &&
|
||||
existsSync(resolve(projectPath, "app.json"));
|
||||
let buildLogs = this.buildLogs(task.buildLogs);
|
||||
|
||||
if (task.status === "failed") {
|
||||
await this.releases.updateStatus(brandId, actorId, taskId, {
|
||||
status: "built",
|
||||
buildLogs,
|
||||
buildStatus: "building",
|
||||
});
|
||||
} else {
|
||||
if (!canReuseArtifact) {
|
||||
const buildAttempt = await this.releases.acquireAttempt(brandId, actorId, taskId, "build");
|
||||
const outputRoot = miniappReleaseOutputRoot(
|
||||
brand.slug ?? brandId,
|
||||
templateKey,
|
||||
templateManifest.version,
|
||||
buildAttempt.id,
|
||||
);
|
||||
projectPath = miniappReleaseProjectPath(
|
||||
brand.slug ?? brandId,
|
||||
templateKey,
|
||||
templateManifest.version,
|
||||
buildAttempt.id,
|
||||
);
|
||||
buildLogs = [
|
||||
log(`开始构建 ${templateKey}@${templateManifest.version} 微信小程序`, "stdout"),
|
||||
log(`请求地址 ${buildConfig.apiBaseUrl},AppID ${buildConfig.appId}`, "stdout"),
|
||||
];
|
||||
if (staleBuilding)
|
||||
buildLogs.push(
|
||||
log(
|
||||
`上一次构建已超过 ${Math.round(buildingStaleMs() / 60000)} 分钟没有进展,按中断处理并重新构建`,
|
||||
"stderr",
|
||||
),
|
||||
);
|
||||
await this.releases.updateBuild(brandId, actorId, taskId, {
|
||||
buildLogs,
|
||||
buildStatus: "building",
|
||||
artifactPath: projectPath,
|
||||
error: null,
|
||||
});
|
||||
|
||||
const result = await this.builds.run(
|
||||
templateKey,
|
||||
{ ...buildConfig, outputRoot: miniappTaroOutputRoot(projectPath) },
|
||||
(message, stream) => {
|
||||
buildLogs.push(log(message, stream));
|
||||
const heartbeat = { logs: buildLogs } as { logs: BuildLog[]; artifactPath?: string };
|
||||
if (projectPath) heartbeat.artifactPath = projectPath;
|
||||
void this.releases
|
||||
.heartbeatAttempt(brandId, buildAttempt.id, buildAttempt.leaseToken, heartbeat)
|
||||
.catch(() => undefined);
|
||||
},
|
||||
);
|
||||
if (result.exitCode !== 0) {
|
||||
buildLogs.push(
|
||||
log(
|
||||
result.timedOut ? "构建超时,已终止构建进程" : `构建失败,退出码 ${result.exitCode}`,
|
||||
"stderr",
|
||||
),
|
||||
);
|
||||
await this.releases.finishAttempt(brandId, buildAttempt.id, buildAttempt.leaseToken, {
|
||||
status: result.timedOut ? "timed_out" : "failed",
|
||||
error: result.timedOut ? "小程序构建超时,请稍后重试" : "小程序构建失败,请查看构建日志",
|
||||
logs: buildLogs,
|
||||
artifactPath: projectPath,
|
||||
});
|
||||
throw new BadRequestException(
|
||||
result.timedOut ? "小程序构建超时,请稍后重试" : "小程序构建失败,请查看构建日志",
|
||||
);
|
||||
}
|
||||
if (
|
||||
!projectPath ||
|
||||
!existsSync(projectPath) ||
|
||||
!existsSync(resolve(projectPath, "app.json"))
|
||||
) {
|
||||
buildLogs.push(log(`构建完成但缺少产物:${projectPath ?? "unknown"}/app.json`, "stderr"));
|
||||
await this.releases.finishAttempt(brandId, buildAttempt.id, buildAttempt.leaseToken, {
|
||||
status: "failed",
|
||||
error: "小程序构建产物缺少 app.json",
|
||||
logs: buildLogs,
|
||||
artifactPath: projectPath,
|
||||
});
|
||||
throw new BadRequestException(`小程序构建产物缺少 app.json:${projectPath}`);
|
||||
}
|
||||
buildLogs.push(log("构建完成,开始上传微信", "stdout"));
|
||||
await this.releases.finishAttempt(brandId, buildAttempt.id, buildAttempt.leaseToken, {
|
||||
status: "succeeded",
|
||||
logs: buildLogs,
|
||||
artifactPath: projectPath,
|
||||
});
|
||||
}
|
||||
|
||||
const result = await this.builds.run(templateKey, buildConfig, (message, stream) => {
|
||||
buildLogs.push(log(message, stream));
|
||||
void this.releases
|
||||
.updateBuild(brandId, actorId, taskId, { buildLogs, buildStatus: "building" })
|
||||
.catch(() => undefined);
|
||||
});
|
||||
if (result.exitCode !== 0) {
|
||||
buildLogs.push(log(`构建失败,退出码 ${result.exitCode}`, "stderr"));
|
||||
await this.releases.updateBuild(brandId, actorId, taskId, {
|
||||
error: "小程序构建失败,请查看构建日志",
|
||||
buildLogs,
|
||||
buildStatus: "failed",
|
||||
});
|
||||
throw new BadRequestException("小程序构建失败,请查看构建日志");
|
||||
}
|
||||
if (!existsSync(projectPath) || !existsSync(resolve(projectPath, "app.json"))) {
|
||||
buildLogs.push(log(`构建完成但缺少产物:${projectPath}/app.json`, "stderr"));
|
||||
await this.releases.updateBuild(brandId, actorId, taskId, {
|
||||
error: "小程序构建产物缺少 app.json",
|
||||
buildLogs,
|
||||
buildStatus: "failed",
|
||||
});
|
||||
throw new BadRequestException(`小程序构建产物缺少 app.json:${projectPath}`);
|
||||
}
|
||||
|
||||
buildLogs.push(log("构建完成,开始上传微信", "stdout"));
|
||||
await this.releases.updateBuild(brandId, actorId, taskId, {
|
||||
buildLogs,
|
||||
buildStatus: "success",
|
||||
});
|
||||
if (!projectPath) throw new BadRequestException("小程序构建产物不存在,请重新构建");
|
||||
const uploadAttempt = await this.releases.acquireAttempt(brandId, actorId, taskId, "upload");
|
||||
const uploadHeartbeat = setInterval(
|
||||
() => {
|
||||
void this.releases
|
||||
.heartbeatAttempt(brandId, uploadAttempt.id, uploadAttempt.leaseToken, {
|
||||
artifactPath: projectPath ?? undefined,
|
||||
})
|
||||
.catch(() => undefined);
|
||||
},
|
||||
Math.max(1_000, Math.floor(miniAppAttemptLeaseMs() / 3)),
|
||||
);
|
||||
uploadHeartbeat.unref();
|
||||
try {
|
||||
const uploadResult = await runMiniAppUpload({
|
||||
projectPath,
|
||||
@@ -137,27 +193,42 @@ export class AdminMiniAppUploadService {
|
||||
desc: input.desc ?? `brand content v${task.version}`,
|
||||
robot: input.robot ?? 1,
|
||||
});
|
||||
return this.releases.updateStatus(brandId, actorId, taskId, {
|
||||
status: "uploaded",
|
||||
buildLogs,
|
||||
buildStatus: "success",
|
||||
weappUploadId:
|
||||
typeof uploadResult.strUint64Version === "string"
|
||||
? uploadResult.strUint64Version
|
||||
: String(task.version),
|
||||
const externalId =
|
||||
typeof uploadResult.strUint64Version === "string"
|
||||
? uploadResult.strUint64Version
|
||||
: String(task.version);
|
||||
await this.releases.finishAttempt(brandId, uploadAttempt.id, uploadAttempt.leaseToken, {
|
||||
status: "succeeded",
|
||||
externalId,
|
||||
artifactPath: projectPath,
|
||||
});
|
||||
return this.releases.get(brandId, taskId);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "微信代码上传失败";
|
||||
await this.releases.updateStatus(brandId, actorId, taskId, {
|
||||
status: "failed",
|
||||
buildLogs,
|
||||
buildStatus: "failed",
|
||||
await this.releases.finishAttempt(brandId, uploadAttempt.id, uploadAttempt.leaseToken, {
|
||||
status: message.includes("超时") ? "timed_out" : "failed",
|
||||
error: message,
|
||||
artifactPath: projectPath,
|
||||
});
|
||||
throw new BadGatewayException(message);
|
||||
} finally {
|
||||
clearInterval(uploadHeartbeat);
|
||||
}
|
||||
}
|
||||
|
||||
private buildLogs(value: unknown): BuildLog[] {
|
||||
return Array.isArray(value)
|
||||
? value.filter(
|
||||
(item): item is BuildLog =>
|
||||
Boolean(item) &&
|
||||
typeof item === "object" &&
|
||||
typeof (item as BuildLog).at === "string" &&
|
||||
typeof (item as BuildLog).message === "string" &&
|
||||
((item as BuildLog).stream === "stdout" || (item as BuildLog).stream === "stderr"),
|
||||
)
|
||||
: [];
|
||||
}
|
||||
|
||||
private requiredEnv(name: string): string {
|
||||
const value = process.env[name];
|
||||
if (!value) throw new BadRequestException(`${name} 未配置`);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { resolve } from "node:path";
|
||||
import { relative, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
export const REPOSITORY_ROOT = fileURLToPath(new URL("../../../../..", import.meta.url));
|
||||
@@ -12,3 +12,43 @@ export function miniappArtifactRoot(configured = process.env.MINIAPP_ARTIFACT_RO
|
||||
export function miniappProjectPath(templatePackageKey: string): string {
|
||||
return resolve(miniappArtifactRoot(), templatePackageKey, "weapp");
|
||||
}
|
||||
|
||||
export function miniappReleaseOutputRoot(
|
||||
brandSlug: string,
|
||||
templateKey: string,
|
||||
templateVersion: string,
|
||||
attemptId: string,
|
||||
): string {
|
||||
for (const [label, value] of [
|
||||
["brand slug", brandSlug],
|
||||
["template key", templateKey],
|
||||
["template version", templateVersion],
|
||||
["attempt id", attemptId],
|
||||
] as const) {
|
||||
if (!/^[a-zA-Z0-9._-]+$/.test(value))
|
||||
throw new Error(`Invalid ${label} for miniapp artifact path`);
|
||||
}
|
||||
return resolve(
|
||||
miniappArtifactRoot(),
|
||||
"releases",
|
||||
brandSlug,
|
||||
`${templateKey}@${templateVersion}`,
|
||||
attemptId,
|
||||
);
|
||||
}
|
||||
|
||||
export function miniappReleaseProjectPath(
|
||||
brandSlug: string,
|
||||
templateKey: string,
|
||||
templateVersion: string,
|
||||
attemptId: string,
|
||||
): string {
|
||||
return resolve(
|
||||
miniappReleaseOutputRoot(brandSlug, templateKey, templateVersion, attemptId),
|
||||
"weapp",
|
||||
);
|
||||
}
|
||||
|
||||
export function miniappTaroOutputRoot(outputRoot: string): string {
|
||||
return relative(resolve(REPOSITORY_ROOT, "apps/taro"), outputRoot);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
const DEFAULT_STALE_MS = 15 * 60 * 1000;
|
||||
const DEFAULT_STALE_MS = 30 * 60 * 1000;
|
||||
const DEFAULT_BUILD_TIMEOUT_MS = 20 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* 构建进程可能被系统杀掉或随 API 一起退出,此时任务会永久停在 `building`。
|
||||
@@ -18,3 +19,8 @@ export function isStaleBuilding(
|
||||
if (Number.isNaN(updatedAt)) return false;
|
||||
return now - updatedAt >= buildingStaleMs();
|
||||
}
|
||||
|
||||
export function miniappBuildTimeoutMs(configured = process.env.MINIAPP_BUILD_TIMEOUT_MS): number {
|
||||
const parsed = Number(configured);
|
||||
return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_BUILD_TIMEOUT_MS;
|
||||
}
|
||||
Reference in new issue
Block a user