240 lines
8.4 KiB
TypeScript
240 lines
8.4 KiB
TypeScript
import assert from "node:assert/strict";
|
|
import { test } from "node:test";
|
|
import { ConflictException } from "@nestjs/common";
|
|
import { AdminMiniAppReleaseService } from "../src/modules/admin/admin-miniapp-release.service.js";
|
|
import type { PrismaService } from "../src/prisma.service.js";
|
|
|
|
const brandId = "brand-1";
|
|
const taskId = "task-1";
|
|
const actorId = "admin-1";
|
|
|
|
function createHarness(initialAttempts: Array<Record<string, unknown>> = []) {
|
|
const task = {
|
|
id: taskId,
|
|
brandId,
|
|
status: "built",
|
|
buildStatus: "idle",
|
|
uploadStatus: "idle",
|
|
reviewStatus: "not_submitted",
|
|
};
|
|
const attempts = [...initialAttempts];
|
|
const findAttempt = (where: Record<string, unknown>) =>
|
|
attempts
|
|
.filter((item) => Object.entries(where).every(([key, value]) => item[key] === value))
|
|
.sort((left, right) => Number(right.attempt) - Number(left.attempt))[0] ?? null;
|
|
let sequence = attempts.length + 1;
|
|
const tx = {
|
|
miniAppReleaseTask: {
|
|
findFirst: async () => task,
|
|
update: async ({ data }: { data: Record<string, unknown> }) => {
|
|
Object.assign(task, data);
|
|
return task;
|
|
},
|
|
},
|
|
miniAppReleaseAttempt: {
|
|
findFirst: async ({ where }: { where: Record<string, unknown> }) => findAttempt(where),
|
|
create: async ({ data }: { data: Record<string, unknown> }) => {
|
|
const created = { id: `attempt-${sequence++}`, status: "running", ...data };
|
|
attempts.push(created);
|
|
return created;
|
|
},
|
|
update: async ({ where, data }: { where: { id: string }; data: Record<string, unknown> }) => {
|
|
const item = attempts.find((candidate) => candidate.id === where.id);
|
|
if (!item) throw new Error("attempt missing");
|
|
Object.assign(item, data);
|
|
return item;
|
|
},
|
|
updateMany: async ({
|
|
where,
|
|
data,
|
|
}: {
|
|
where: {
|
|
id: string;
|
|
status: string;
|
|
leaseToken: string;
|
|
leaseExpiresAt?: { gt: Date };
|
|
};
|
|
data: Record<string, unknown>;
|
|
}) => {
|
|
const item = attempts.find(
|
|
(candidate) =>
|
|
candidate.id === where.id &&
|
|
candidate.status === where.status &&
|
|
candidate.leaseToken === where.leaseToken &&
|
|
(!where.leaseExpiresAt || (candidate.leaseExpiresAt as Date) > where.leaseExpiresAt.gt),
|
|
);
|
|
if (!item) return { count: 0 };
|
|
Object.assign(item, data);
|
|
return { count: 1 };
|
|
},
|
|
},
|
|
};
|
|
const prisma = {
|
|
$transaction: async (callback: (value: typeof tx) => unknown) => callback(tx),
|
|
miniAppReleaseAttempt: tx.miniAppReleaseAttempt,
|
|
miniAppReleaseTask: tx.miniAppReleaseTask,
|
|
} as unknown as PrismaService;
|
|
return { service: new AdminMiniAppReleaseService(prisma), attempts, task };
|
|
}
|
|
|
|
test("同一任务同一阶段的有效 lease 拒绝并发操作", async () => {
|
|
const { service } = createHarness();
|
|
const first = await service.acquireAttempt(brandId, actorId, taskId, "build");
|
|
assert.equal(first.attempt, 1);
|
|
await assert.rejects(
|
|
() => service.acquireAttempt(brandId, actorId, taskId, "build"),
|
|
ConflictException,
|
|
);
|
|
});
|
|
|
|
test("过期 lease 会先收敛为 timed_out,再允许新的 attempt 接管", async () => {
|
|
const expiredAt = new Date(Date.now() - 1_000);
|
|
const { service, attempts } = createHarness([
|
|
{
|
|
id: "expired-attempt",
|
|
taskId,
|
|
brandId,
|
|
phase: "upload",
|
|
attempt: 1,
|
|
status: "running",
|
|
leaseToken: "expired-token",
|
|
leaseExpiresAt: expiredAt,
|
|
},
|
|
]);
|
|
const next = await service.acquireAttempt(brandId, actorId, taskId, "upload");
|
|
assert.equal(next.attempt, 2);
|
|
assert.equal(attempts[0].status, "timed_out");
|
|
assert.equal(attempts[0].finishedAt instanceof Date, true);
|
|
});
|
|
|
|
test("服务进程重建后从持久化记录恢复,并接管已过期的 build attempt", async () => {
|
|
const expiredAt = new Date(Date.now() - 1_000);
|
|
const { attempts } = createHarness([
|
|
{
|
|
id: "worker-before-restart",
|
|
taskId,
|
|
brandId,
|
|
phase: "build",
|
|
attempt: 1,
|
|
status: "running",
|
|
leaseToken: "old-worker-token",
|
|
leaseExpiresAt: expiredAt,
|
|
},
|
|
]);
|
|
const persistentTask = {
|
|
id: taskId,
|
|
brandId,
|
|
status: "built",
|
|
buildStatus: "building",
|
|
uploadStatus: "idle",
|
|
reviewStatus: "not_submitted",
|
|
};
|
|
const persistentTx = {
|
|
miniAppReleaseTask: {
|
|
findFirst: async () => persistentTask,
|
|
update: async ({ data }: { data: Record<string, unknown> }) => {
|
|
Object.assign(persistentTask, data);
|
|
return persistentTask;
|
|
},
|
|
},
|
|
miniAppReleaseAttempt: {
|
|
findFirst: async ({ where }: { where: Record<string, unknown> }) =>
|
|
attempts
|
|
.filter((item) => Object.entries(where).every(([key, value]) => item[key] === value))
|
|
.sort((left, right) => Number(right.attempt) - Number(left.attempt))[0] ?? null,
|
|
create: async ({ data }: { data: Record<string, unknown> }) => {
|
|
const created = {
|
|
id: "worker-after-restart",
|
|
status: "running",
|
|
...data,
|
|
};
|
|
attempts.push(created);
|
|
return created;
|
|
},
|
|
update: async ({ where, data }: { where: { id: string }; data: Record<string, unknown> }) => {
|
|
const item = attempts.find((candidate) => candidate.id === where.id);
|
|
if (!item) throw new Error("attempt missing");
|
|
Object.assign(item, data);
|
|
return item;
|
|
},
|
|
},
|
|
};
|
|
const prisma = {
|
|
$transaction: async (callback: (value: typeof persistentTx) => unknown) =>
|
|
callback(persistentTx),
|
|
...persistentTx,
|
|
} as unknown as PrismaService;
|
|
const restartedService = new AdminMiniAppReleaseService(prisma);
|
|
|
|
const recovered = await restartedService.acquireAttempt(brandId, actorId, taskId, "build");
|
|
|
|
assert.equal(recovered.attempt, 2);
|
|
assert.equal(attempts[0].status, "timed_out");
|
|
assert.equal(persistentTask.buildStatus, "building");
|
|
});
|
|
|
|
test("heartbeat 遇到过期上传 lease 时将任务阶段收敛为 timed_out", async () => {
|
|
const expiredAt = new Date(Date.now() - 1_000);
|
|
const { service, attempts, task } = createHarness([
|
|
{
|
|
id: "expired-attempt",
|
|
taskId,
|
|
brandId,
|
|
phase: "upload",
|
|
attempt: 1,
|
|
status: "running",
|
|
leaseToken: "expired-token",
|
|
leaseExpiresAt: expiredAt,
|
|
},
|
|
]);
|
|
task.uploadStatus = "uploading";
|
|
await assert.rejects(
|
|
() => service.heartbeatAttempt(brandId, "expired-attempt", "expired-token", {}),
|
|
ConflictException,
|
|
);
|
|
assert.equal(attempts[0].status, "timed_out");
|
|
assert.equal(task.uploadStatus, "timed_out");
|
|
});
|
|
|
|
test("错误 lease 不能结束操作,正确 lease 结束上传后更新阶段状态", async () => {
|
|
const { service, task, attempts } = createHarness();
|
|
const attempt = await service.acquireAttempt(brandId, actorId, taskId, "upload");
|
|
await assert.rejects(
|
|
() => service.finishAttempt(brandId, attempt.id, "wrong-token", { status: "succeeded" }),
|
|
ConflictException,
|
|
);
|
|
await service.finishAttempt(brandId, attempt.id, attempt.leaseToken, {
|
|
status: "succeeded",
|
|
externalId: "wechat-upload-1",
|
|
});
|
|
assert.equal(attempts[0].status, "succeeded");
|
|
assert.equal(task.uploadStatus, "uploaded");
|
|
assert.equal(task.status, "uploaded");
|
|
});
|
|
|
|
test("heartbeat 续租并更新日志,结束后的 attempt 拒绝迟到 heartbeat", async () => {
|
|
const { service, attempts } = createHarness();
|
|
const attempt = await service.acquireAttempt(brandId, actorId, taskId, "build");
|
|
await service.heartbeatAttempt(brandId, attempt.id, attempt.leaseToken, {
|
|
logs: [{ message: "compile" }],
|
|
});
|
|
assert.deepEqual(attempts[0].logs, [{ message: "compile" }]);
|
|
await service.finishAttempt(brandId, attempt.id, attempt.leaseToken, { status: "succeeded" });
|
|
await assert.rejects(
|
|
() => service.heartbeatAttempt(brandId, attempt.id, attempt.leaseToken, { logs: [] }),
|
|
ConflictException,
|
|
);
|
|
assert.equal(attempts[0].status, "succeeded");
|
|
});
|
|
|
|
test("执行结束时 lease 已过期会持久化 timed_out,而不是回滚为 running", async () => {
|
|
const { service, attempts } = createHarness();
|
|
const attempt = await service.acquireAttempt(brandId, actorId, taskId, "upload");
|
|
attempts[0].leaseExpiresAt = new Date(Date.now() - 1);
|
|
await assert.rejects(
|
|
() => service.finishAttempt(brandId, attempt.id, attempt.leaseToken, { status: "succeeded" }),
|
|
ConflictException,
|
|
);
|
|
assert.equal(attempts[0].status, "timed_out");
|
|
});
|