280 lines
9.3 KiB
TypeScript
280 lines
9.3 KiB
TypeScript
import assert from "node:assert/strict";
|
|
import { generateKeyPairSync } from "node:crypto";
|
|
import { test } from "node:test";
|
|
import { BadGatewayException, BadRequestException, ConflictException } from "@nestjs/common";
|
|
import { templatePackageRegistry } from "@personal-brand/config";
|
|
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import { join, resolve } from "node:path";
|
|
import { AdminMiniAppBuildService } from "../src/modules/admin/admin-miniapp-build.service.js";
|
|
import { AdminMiniAppUploadService } from "../src/modules/admin/admin-miniapp-upload.service.js";
|
|
import type { AdminMiniAppReleaseService } from "../src/modules/admin/admin-miniapp-release.service.js";
|
|
import { encryptMiniAppCredential } from "../src/modules/admin/miniapp-credential-crypto.js";
|
|
|
|
process.env.SESSION_SECRET = "upload-service-test-secret-1234567890";
|
|
|
|
const privateKey = generateKeyPairSync("rsa", {
|
|
modulusLength: 2048,
|
|
privateKeyEncoding: { type: "pkcs8", format: "pem" },
|
|
publicKeyEncoding: { type: "spki", format: "pem" },
|
|
}).privateKey;
|
|
process.env.MINIAPP_TEST_PRIVATE_KEY = privateKey;
|
|
|
|
const brandId = "brand-1";
|
|
const actorId = "admin-1";
|
|
|
|
function task(overrides: Record<string, unknown> = {}) {
|
|
return {
|
|
id: "task-1",
|
|
version: 7,
|
|
status: "built",
|
|
buildStatus: "idle",
|
|
updatedAt: new Date(),
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
function validBrandSettings() {
|
|
return {
|
|
appId: "wxtestsettings",
|
|
apiBaseUrl: "https://wechat.example.com/api",
|
|
};
|
|
}
|
|
|
|
function createHarness(
|
|
options: {
|
|
task?: Record<string, unknown>;
|
|
settings?: Record<string, unknown>;
|
|
exitCode?: number;
|
|
artifact?: boolean;
|
|
uploadError?: Error;
|
|
} = {},
|
|
) {
|
|
const artifactRoot =
|
|
options.artifact === false
|
|
? join(tmpdir(), "missing")
|
|
: mkdtempSync(join(tmpdir(), "miniapp-upload-"));
|
|
if (options.artifact !== false) writeFileSync(join(artifactRoot, "app.json"), "{}");
|
|
const updates: Record<string, unknown>[] = [];
|
|
const buildConfigs: Array<{ apiBaseUrl: string; appId: string; outputRoot: string }> = [];
|
|
const releases = {
|
|
uploadContext: async () => ({
|
|
task: task(options.task),
|
|
brand: {
|
|
templateKey: "food",
|
|
miniAppSettings: options.settings ?? validBrandSettings(),
|
|
},
|
|
}),
|
|
acquireAttempt: async (
|
|
_brandId: string,
|
|
_actorId: string,
|
|
_taskId: string,
|
|
phase: "build" | "upload",
|
|
) => ({
|
|
id: `${phase}-attempt`,
|
|
leaseToken: `${phase}-lease`,
|
|
attempt: 1,
|
|
leaseExpiresAt: new Date(Date.now() + 60_000),
|
|
}),
|
|
heartbeatAttempt: async () => ({}),
|
|
finishAttempt: async (
|
|
_brandId: string,
|
|
attemptId: string,
|
|
_leaseToken: string,
|
|
input: object,
|
|
) => {
|
|
updates.push({ kind: "attempt", attemptId, input });
|
|
return input;
|
|
},
|
|
updateBuild: async (_brandId: string, _actorId: string, _taskId: string, input: object) => {
|
|
updates.push({ kind: "build", input });
|
|
return input;
|
|
},
|
|
updateStatus: async (_brandId: string, _actorId: string, _taskId: string, input: object) => {
|
|
updates.push({ kind: "status", input });
|
|
return input;
|
|
},
|
|
} as unknown as AdminMiniAppReleaseService;
|
|
const builds = {
|
|
run: async (
|
|
_templateKey: string,
|
|
config: { apiBaseUrl: string; appId: string; outputRoot: string },
|
|
onLog: (message: string, stream: "stdout" | "stderr") => void,
|
|
) => {
|
|
buildConfigs.push(config);
|
|
onLog("build log", "stdout");
|
|
return { exitCode: options.exitCode ?? 0 };
|
|
},
|
|
} as unknown as AdminMiniAppBuildService;
|
|
const service = new AdminMiniAppUploadService(releases, builds);
|
|
return { service, updates, artifactRoot, buildConfigs };
|
|
}
|
|
|
|
function createHarnessWithCredential(
|
|
options: {
|
|
task?: Record<string, unknown>;
|
|
exitCode?: number;
|
|
artifact?: boolean;
|
|
} = {},
|
|
) {
|
|
const artifactRoot =
|
|
options.artifact === false
|
|
? join(tmpdir(), "missing")
|
|
: mkdtempSync(join(tmpdir(), "miniapp-upload-"));
|
|
if (options.artifact !== false) writeFileSync(join(artifactRoot, "app.json"), "{}");
|
|
const updates: Record<string, unknown>[] = [];
|
|
const buildConfigs: Array<{ apiBaseUrl: string; appId: string; outputRoot: string }> = [];
|
|
const releases = {
|
|
uploadContext: async () => ({
|
|
task: task(options.task),
|
|
brand: {
|
|
templateKey: "food",
|
|
miniAppSettings: {
|
|
...validBrandSettings(),
|
|
credential: encryptMiniAppCredential(process.env.MINIAPP_TEST_PRIVATE_KEY ?? ""),
|
|
},
|
|
},
|
|
}),
|
|
acquireAttempt: async (
|
|
_brandId: string,
|
|
_actorId: string,
|
|
_taskId: string,
|
|
phase: "build" | "upload",
|
|
) => ({
|
|
id: `${phase}-attempt`,
|
|
leaseToken: `${phase}-lease`,
|
|
attempt: 1,
|
|
leaseExpiresAt: new Date(Date.now() + 60_000),
|
|
}),
|
|
heartbeatAttempt: async () => ({}),
|
|
finishAttempt: async (
|
|
_brandId: string,
|
|
attemptId: string,
|
|
_leaseToken: string,
|
|
input: object,
|
|
) => {
|
|
updates.push({ kind: "attempt", attemptId, input });
|
|
return input;
|
|
},
|
|
updateBuild: async (_brandId: string, _actorId: string, _taskId: string, input: object) => {
|
|
updates.push({ kind: "build", input });
|
|
return input;
|
|
},
|
|
updateStatus: async (_brandId: string, _actorId: string, _taskId: string, input: object) => {
|
|
updates.push({ kind: "status", input });
|
|
return input;
|
|
},
|
|
} as unknown as AdminMiniAppReleaseService;
|
|
const builds = {
|
|
run: async (
|
|
_templateKey: string,
|
|
config: { apiBaseUrl: string; appId: string; outputRoot: string },
|
|
onLog: (message: string, stream: "stdout" | "stderr") => void,
|
|
) => {
|
|
buildConfigs.push(config);
|
|
onLog("build log", "stdout");
|
|
return { exitCode: options.exitCode ?? 0 };
|
|
},
|
|
} as unknown as AdminMiniAppBuildService;
|
|
return {
|
|
service: new AdminMiniAppUploadService(releases, builds),
|
|
updates,
|
|
artifactRoot,
|
|
buildConfigs,
|
|
};
|
|
}
|
|
|
|
test("upload blocks a currently building task before credentials are read", async () => {
|
|
const { service } = createHarness({
|
|
task: { buildStatus: "building", updatedAt: new Date() },
|
|
});
|
|
await assert.rejects(() => service.run(brandId, actorId, "task-1", {}), ConflictException);
|
|
});
|
|
|
|
test("upload rejects invalid app configuration before building", async () => {
|
|
const { service } = createHarness({
|
|
settings: { ...validBrandSettings(), appId: "touristappid" },
|
|
});
|
|
await assert.rejects(
|
|
() => service.run(brandId, actorId, "task-1", {}),
|
|
(error: unknown) => {
|
|
assert.ok(error instanceof Error);
|
|
assert.match(error.message, /AppID/);
|
|
return true;
|
|
},
|
|
);
|
|
});
|
|
|
|
test("failed build records logs and build failure state", async () => {
|
|
const { service, updates } = createHarnessWithCredential({ exitCode: 2 });
|
|
await assert.rejects(
|
|
() => service.run(brandId, actorId, "task-1", {}),
|
|
(error: unknown) => {
|
|
assert.ok(error instanceof BadRequestException);
|
|
const failedAttempt = updates.find(
|
|
(entry) => entry.kind === "attempt" && entry.attemptId === "build-attempt",
|
|
);
|
|
const logs = (failedAttempt?.input as { logs: Array<{ message: string }> }).logs;
|
|
assert.ok(logs.some((entry) => entry.message.includes("build log")));
|
|
assert.ok(logs.some((entry) => entry.message.includes("退出码 2")));
|
|
return true;
|
|
},
|
|
);
|
|
assert.equal(
|
|
(updates.find((entry) => entry.kind === "attempt")?.input as { status: string }).status,
|
|
"failed",
|
|
);
|
|
});
|
|
|
|
test("missing artifact records build failure without invoking upload", async () => {
|
|
const { service, updates, buildConfigs } = createHarnessWithCredential({ artifact: false });
|
|
const previousProjectPath = process.env.MINIAPP_ARTIFACT_ROOT;
|
|
process.env.MINIAPP_ARTIFACT_ROOT = join(tmpdir(), "missing-miniapp-artifacts");
|
|
try {
|
|
await assert.rejects(
|
|
() => service.run(brandId, actorId, "task-1", {}),
|
|
(error: unknown) => {
|
|
assert.ok(error instanceof BadRequestException);
|
|
assert.match((error as BadRequestException).message, /app\.json/);
|
|
return true;
|
|
},
|
|
);
|
|
assert.equal(
|
|
(updates.find((entry) => entry.kind === "attempt")?.input as { status: string }).status,
|
|
"failed",
|
|
);
|
|
assert.equal(
|
|
resolve(process.cwd(), "../taro", buildConfigs[0].outputRoot),
|
|
resolve(
|
|
process.env.MINIAPP_ARTIFACT_ROOT,
|
|
"releases",
|
|
brandId,
|
|
`acheng-campus-food@${templatePackageRegistry.find((item) => item.supportedIndustryTemplates.includes("food"))?.version}`,
|
|
"build-attempt",
|
|
"weapp",
|
|
),
|
|
);
|
|
} finally {
|
|
if (previousProjectPath === undefined) delete process.env.MINIAPP_ARTIFACT_ROOT;
|
|
else process.env.MINIAPP_ARTIFACT_ROOT = previousProjectPath;
|
|
}
|
|
});
|
|
|
|
test("upload rejects missing credentials before build", async () => {
|
|
const previous = process.env.WECHAT_UPLOAD_PRIVATE_KEY;
|
|
delete process.env.WECHAT_UPLOAD_PRIVATE_KEY;
|
|
try {
|
|
const { service } = createHarness();
|
|
await assert.rejects(
|
|
() => service.run(brandId, actorId, "task-1", {}),
|
|
(error: unknown) => {
|
|
assert.ok(error instanceof BadRequestException);
|
|
assert.match((error as BadRequestException).message, /WECHAT_UPLOAD_PRIVATE_KEY/);
|
|
return true;
|
|
},
|
|
);
|
|
} finally {
|
|
if (previous !== undefined) process.env.WECHAT_UPLOAD_PRIVATE_KEY = previous;
|
|
}
|
|
});
|