衔接异步任务前后端并记录自动回归进度,竞争复审待完成
This commit is contained in:
1 parent
13872ea3b1
commit
9e666be522
18 files changed
+767
-104
No files matched your search
@@ -2,6 +2,7 @@ import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
|
||||
import { settingsPayload } from "./SettingsPayload.js";
|
||||
import { deploymentSummary, serverAuthLabel } from "./DeploymentFeedback.js";
|
||||
import { useDomainForm } from "./DomainForm.js";
|
||||
import { useTaskMonitor } from "./TaskMonitor.js";
|
||||
|
||||
const defaultDNSVerificationTimeoutSeconds = 60;
|
||||
const aliyunDNSVerificationTimeoutSeconds = 6;
|
||||
@@ -75,6 +76,11 @@ export function useDashboard() {
|
||||
const taskDetailsError = ref("");
|
||||
const deploymentResult = ref(null);
|
||||
const domainActionRunning = ref(false);
|
||||
const taskMonitor = useTaskMonitor({
|
||||
fetchAdmin, tasks, deploymentResult, showTaskDetails, taskDetails,
|
||||
taskAttempts, taskDetailsLoading, taskDetailsError,
|
||||
refreshResources: refreshTaskResources,
|
||||
});
|
||||
const hasOpenModal = computed(
|
||||
() =>
|
||||
showForm.value ||
|
||||
@@ -549,6 +555,28 @@ export function useDashboard() {
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshTaskResources(signal) {
|
||||
// 任务结束后只刷新运行数据,不覆盖用户正在编辑的系统设置或表单。
|
||||
const responses = await Promise.all([
|
||||
fetchAdmin("/api/v1/status", { signal }),
|
||||
fetchAdmin("/api/v1/domains", { signal }),
|
||||
fetchAdmin("/api/v1/certificates", { signal }),
|
||||
fetchAdmin("/api/v1/audit-logs?limit=20", { signal }),
|
||||
]);
|
||||
if (responses.some((response) => !response.ok)) throw new Error("刷新任务关联数据失败");
|
||||
const [statusResult, domainResult, certificateResult, auditResult] = await Promise.all(
|
||||
responses.map((response) => response.json()),
|
||||
);
|
||||
if (signal.aborted) return;
|
||||
if (![domainResult, certificateResult, auditResult].every((result) => Array.isArray(result.items))) {
|
||||
throw new Error("任务关联数据响应不完整");
|
||||
}
|
||||
status.value = statusResult;
|
||||
domains.value = domainResult.items;
|
||||
certificates.value = certificateResult.items;
|
||||
auditLogs.value = auditResult.items;
|
||||
}
|
||||
|
||||
async function runDomainAction(item, action, successMessage) {
|
||||
if (domainActionRunning.value) return;
|
||||
domainActionRunning.value = true;
|
||||
@@ -559,12 +587,26 @@ export function useDashboard() {
|
||||
notice.value = "";
|
||||
try {
|
||||
const options = { method: "POST" };
|
||||
if (action === "issue") {
|
||||
if (action === "issue" || action === "deploy") {
|
||||
const suffix = crypto.randomUUID ? crypto.randomUUID() : createRandomSuffix();
|
||||
options.headers = { "Idempotency-Key": `issue-${item.id}-${suffix}` };
|
||||
options.headers = { "Idempotency-Key": `${action}-${item.id}-${suffix}` };
|
||||
}
|
||||
const response = await fetchAdmin(`/api/v1/domains/${item.id}/${action}`, options);
|
||||
const result = await response.json().catch(() => ({}));
|
||||
if (response.status === 202 && !result.task?.id) {
|
||||
throw new Error("服务未返回任务编号,请在运行概览确认是否已接收,勿重复提交");
|
||||
}
|
||||
if (response.ok && result.task?.id && (response.status === 202 || result.accepted || result.replayed)) {
|
||||
notice.value = `任务已提交:${result.task.id},可在运行概览查看执行结果`;
|
||||
if (action === "deploy") {
|
||||
deploymentResult.value = {
|
||||
domain: item.name, running: false, pending: true,
|
||||
taskID: result.task.id, taskStatus: result.task.status,
|
||||
taskMessage: result.task.message || "", report: null, error: "", queryError: "",
|
||||
};
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (action === "deploy") {
|
||||
deploymentResult.value = {
|
||||
domain: item.name,
|
||||
@@ -601,39 +643,6 @@ export function useDashboard() {
|
||||
return runDomainAction(item, "deploy", `已提交 ${item.name} 的证书部署`);
|
||||
}
|
||||
|
||||
async function openTaskDetails(item) {
|
||||
showTaskDetails.value = true;
|
||||
taskDetails.value = null;
|
||||
taskAttempts.value = [];
|
||||
taskDetailsError.value = "";
|
||||
taskDetailsLoading.value = true;
|
||||
try {
|
||||
const [taskResponse, attemptsResponse] = await Promise.all([
|
||||
fetchAdmin(`/api/v1/tasks/${item.id}`),
|
||||
fetchAdmin(`/api/v1/tasks/${item.id}/attempts`),
|
||||
]);
|
||||
if (!taskResponse.ok) {
|
||||
throw new Error(await responseError(taskResponse, "读取任务详情失败"));
|
||||
}
|
||||
if (!attemptsResponse.ok) {
|
||||
throw new Error(await responseError(attemptsResponse, "读取任务尝试记录失败"));
|
||||
}
|
||||
taskDetails.value = await taskResponse.json();
|
||||
taskAttempts.value = (await attemptsResponse.json()).items || [];
|
||||
} catch (err) {
|
||||
taskDetailsError.value = err.message || "读取任务详情失败";
|
||||
} finally {
|
||||
taskDetailsLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function closeTaskDetails() {
|
||||
showTaskDetails.value = false;
|
||||
taskDetails.value = null;
|
||||
taskAttempts.value = [];
|
||||
taskDetailsError.value = "";
|
||||
}
|
||||
|
||||
async function cancelTask(item) {
|
||||
if (!window.confirm("确定取消这项正在执行的证书任务吗?")) return;
|
||||
error.value = "";
|
||||
@@ -642,8 +651,11 @@ export function useDashboard() {
|
||||
const response = await fetchAdmin(`/api/v1/tasks/${item.id}`, { method: "DELETE" });
|
||||
const result = await response.json().catch(() => ({}));
|
||||
if (!response.ok) throw new Error(result.error || "取消任务失败");
|
||||
notice.value = "证书任务已取消";
|
||||
notice.value = response.status === 202 || result.task?.status === "cancelling"
|
||||
? "正在取消,等待任务停止和部署收尾;此时不能重试"
|
||||
: "证书任务已取消";
|
||||
await loadData();
|
||||
await taskMonitor.refreshTaskStatus();
|
||||
} catch (err) {
|
||||
error.value = err.message || "取消任务失败";
|
||||
}
|
||||
@@ -656,8 +668,9 @@ export function useDashboard() {
|
||||
const response = await fetchAdmin(`/api/v1/tasks/${item.id}/retry`, { method: "POST" });
|
||||
const result = await response.json().catch(() => ({}));
|
||||
if (!response.ok) throw new Error(result.error || "重试任务失败");
|
||||
notice.value = "证书任务已重新执行";
|
||||
notice.value = "重试已提交,请在任务详情查看本次执行结果";
|
||||
await loadData();
|
||||
await taskMonitor.refreshTaskStatus();
|
||||
} catch (err) {
|
||||
error.value = err.message || "重试任务失败";
|
||||
}
|
||||
@@ -1022,6 +1035,7 @@ export function useDashboard() {
|
||||
|
||||
return {
|
||||
...domainForm,
|
||||
...taskMonitor,
|
||||
status,
|
||||
currentUser,
|
||||
canManageSystemSettings,
|
||||
@@ -1112,8 +1126,6 @@ export function useDashboard() {
|
||||
deployDomain,
|
||||
cancelTask,
|
||||
retryTask,
|
||||
openTaskDetails,
|
||||
closeTaskDetails,
|
||||
showTaskDetails,
|
||||
taskDetails,
|
||||
taskAttempts,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import assert from "node:assert/strict";
|
||||
import "./DeploymentResult.test.js";
|
||||
import "./TaskMonitor.test.js";
|
||||
import "./DashboardLogout.test.js";
|
||||
import "./DomainModal.test.js";
|
||||
import "./DomainForm.test.js";
|
||||
@@ -139,6 +140,7 @@ test("完整页面逐个渲染六个板块,每次只有一个内容标题", as
|
||||
app.component("ProjectManagement", { render: () => Vue.h("h2", headings.projects) });
|
||||
app.component("DNSAccounts", { render: () => Vue.h("h2", headings["dns-accounts"]) });
|
||||
app.component("DeploymentResult", { render: () => null });
|
||||
app.component("TaskDeploymentResults", { render: () => null });
|
||||
const warnings = [];
|
||||
app.config.warnHandler = (message) => warnings.push(message);
|
||||
const html = await renderToString(app);
|
||||
|
||||
@@ -10,6 +10,7 @@ import DashboardNavigation from "./DashboardNavigation.vue";
|
||||
import { useDashboardNavigation } from "./DashboardNavigation.js";
|
||||
import { useDashboard } from "./Dashboard.js";
|
||||
import DeploymentResult from "./DeploymentResult.vue";
|
||||
import TaskDeploymentResults from "./TaskDeploymentResults.vue";
|
||||
|
||||
const dashboard = useDashboard();
|
||||
const {
|
||||
@@ -37,6 +38,8 @@ const {
|
||||
saving,
|
||||
error,
|
||||
notice,
|
||||
taskQueryError,
|
||||
taskDeploymentReport,
|
||||
formError,
|
||||
showForm,
|
||||
editingId,
|
||||
@@ -152,6 +155,7 @@ const { activeSection, activeLabel, sections, selectSection } = useDashboardNavi
|
||||
<div class="dashboard-messages" aria-live="polite">
|
||||
<p v-if="error" class="error-banner">{{ error }}</p>
|
||||
<p v-if="notice" class="notice-banner">{{ notice }}</p>
|
||||
<p v-if="taskQueryError" class="error-banner" role="alert">{{ taskQueryError }}</p>
|
||||
</div>
|
||||
|
||||
<div class="dashboard-workspace">
|
||||
@@ -504,8 +508,8 @@ const { activeSection, activeLabel, sections, selectSection } = useDashboardNavi
|
||||
<button class="close-button" type="button" aria-label="关闭" @click="closeTaskDetails">×</button>
|
||||
</div>
|
||||
<div v-if="taskDetailsLoading" class="empty-state">正在读取任务详情……</div>
|
||||
<p v-else-if="taskDetailsError" class="form-error">{{ taskDetailsError }}</p>
|
||||
<template v-else-if="taskDetails">
|
||||
<p v-if="taskDetailsError" class="form-error" role="alert">{{ taskDetailsError }}</p>
|
||||
<template v-if="taskDetails">
|
||||
<div class="task-detail-summary">
|
||||
<div><span>当前状态</span><strong class="tag" :class="statusClass(taskDetails.status)">{{ displayLabel(taskStatusLabels, taskDetails.status) }}</strong></div>
|
||||
<div><span>执行阶段</span><strong>{{ taskStageLabel(taskDetails.stage) }}</strong></div>
|
||||
@@ -516,6 +520,7 @@ const { activeSection, activeLabel, sections, selectSection } = useDashboardNavi
|
||||
<span>任务信息</span>
|
||||
<p>{{ taskDetails.message || "无附加信息" }}</p>
|
||||
</div>
|
||||
<TaskDeploymentResults v-if="taskDeploymentReport" :report="taskDeploymentReport" />
|
||||
<h3 class="modal-section-title">执行尝试</h3>
|
||||
<div v-if="taskAttempts.length === 0" class="empty-state compact-empty">暂无执行尝试记录</div>
|
||||
<div v-else class="attempt-list">
|
||||
|
||||
@@ -2,6 +2,14 @@ export function serverAuthLabel(server) {
|
||||
return server.password_configured ? "SSH 密码已配置" : "SSH 密码未配置";
|
||||
}
|
||||
|
||||
export function taskExecutionLabel(status) {
|
||||
return {
|
||||
queued: "排队中", running: "执行中", retry_wait: "等待重试",
|
||||
cancelling: "正在取消,等待收尾", cancelled: "已取消",
|
||||
success: "已完成", failed: "失败", partial_success: "部分成功",
|
||||
}[status] || "等待确认状态";
|
||||
}
|
||||
|
||||
export function deploymentSummary(report) {
|
||||
if (!report || !Array.isArray(report.results)) return "未收到有效部署结果";
|
||||
if (report.status !== "success" && report.recovery_status === "success") {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup>
|
||||
import { deploymentStatusLabel, deploymentSummary } from "./DeploymentFeedback.js";
|
||||
import { deploymentStatusLabel, deploymentSummary, taskExecutionLabel } from "./DeploymentFeedback.js";
|
||||
|
||||
defineProps({ result: { type: Object, required: true } });
|
||||
defineEmits(["close"]);
|
||||
@@ -27,8 +27,14 @@ defineEmits(["close"]);
|
||||
@click="$emit('close')"
|
||||
>×</button>
|
||||
</div>
|
||||
<p v-if="result.running" role="status">正在连接服务器、推送证书并校验重载,请稍候……</p>
|
||||
<p v-if="result.running" role="status">正在提交操作,请稍候……</p>
|
||||
<template v-else>
|
||||
<template v-if="result.taskID">
|
||||
<p class="muted">任务编号:{{ result.taskID }}</p>
|
||||
<p role="status">{{ taskExecutionLabel(result.taskStatus) }}:{{ result.taskMessage }}</p>
|
||||
<p v-if="result.pending" class="muted">任务已在后台接收,可关闭此窗口,在运行概览继续查看;请勿重复提交。</p>
|
||||
<p v-if="result.queryError" class="form-error" role="alert">{{ result.queryError }}</p>
|
||||
</template>
|
||||
<p v-if="result.certificateImported" role="status">证书已导入并保存。</p>
|
||||
<p v-if="result.error" class="form-error" role="alert">{{ result.error }}</p>
|
||||
<p v-if="result.report" class="deployment-summary" role="status">
|
||||
@@ -49,7 +55,7 @@ defineEmits(["close"]);
|
||||
</span>
|
||||
</article>
|
||||
</div>
|
||||
<p class="muted">各服务器结果记录文件推送、配置校验与重载;站点 HTTPS 校验单独汇总,不代表逐台服务器均已验证。</p>
|
||||
<p v-if="result.report" class="muted">各服务器结果仅记录本次尝试的推送结果,整体状态以任务终态为准;不能据此推断每台站点的 HTTPS 校验均通过。</p>
|
||||
</template>
|
||||
<div class="modal-actions">
|
||||
<button class="secondary-button" type="button" :disabled="result.running" @click="$emit('close')">
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
<script setup>
|
||||
import { deploymentSummary, deploymentStatusLabel } from "./DeploymentFeedback.js";
|
||||
|
||||
defineProps({ report: { type: Object, required: true } });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section aria-label="最近一次尝试的部署结果">
|
||||
<h3 class="modal-section-title">本次部署结果</h3>
|
||||
<p role="status">{{ deploymentSummary(report) }}</p>
|
||||
<div class="attempt-list">
|
||||
<article v-for="(item, index) in report.results" :key="item.server_id || index" class="attempt-row">
|
||||
<div>
|
||||
<strong>{{ item.server || "未命名服务器" }}</strong>
|
||||
<span class="muted">{{ item.message || "无附加信息" }}</span>
|
||||
</div>
|
||||
<span class="tag">{{ deploymentStatusLabel(item.status) }}</span>
|
||||
</article>
|
||||
</div>
|
||||
<p class="muted">逐服务器结果不代表整体部署或站点 HTTPS 校验成功,请结合任务状态判断。</p>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped src="./Dashboard.css"></style>
|
||||
@@ -0,0 +1,190 @@
|
||||
import { onBeforeUnmount, onMounted, ref } from "vue";
|
||||
|
||||
const terminalStatuses = new Set(["success", "failed", "cancelled", "partial_success"]);
|
||||
|
||||
export function taskIsPending(task) {
|
||||
return !terminalStatuses.has(task?.status);
|
||||
}
|
||||
|
||||
export function latestDeploymentReport(task, attempts, results) {
|
||||
const latest = Math.max(0, ...attempts.map((item) => item.attempt_number || 0));
|
||||
const items = results.filter((item) => item.attempt_number === latest);
|
||||
if (taskIsPending(task) || latest === 0 || items.length === 0) return null;
|
||||
return {
|
||||
status: task.status,
|
||||
total: items.length,
|
||||
success: items.filter((item) => item.status === "success").length,
|
||||
failed: items.filter((item) => item.status !== "success").length,
|
||||
results: items,
|
||||
};
|
||||
}
|
||||
|
||||
// 查询失败只表示暂时无法确认状态,不能据此重发任务或宣布执行失败。
|
||||
export function useTaskMonitor({ fetchAdmin, tasks, deploymentResult, showTaskDetails,
|
||||
taskDetails, taskAttempts, taskDetailsLoading, taskDetailsError, refreshResources }) {
|
||||
const taskQueryError = ref("");
|
||||
const taskDeploymentReport = ref(null);
|
||||
let selectedID = "";
|
||||
let stopped = false;
|
||||
let timer;
|
||||
let controller;
|
||||
let inFlight;
|
||||
let resourcesDirty = false;
|
||||
|
||||
async function readJSON(path, signal) {
|
||||
const response = await fetchAdmin(path, { signal });
|
||||
const result = await response.json().catch(() => null);
|
||||
if (!response.ok || !result) {
|
||||
const error = new Error("任务状态查询失败,将自动重试;请勿重复提交任务");
|
||||
error.status = response.status;
|
||||
throw error;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async function readTask(id, signal) {
|
||||
const path = `/api/v1/tasks/${encodeURIComponent(id)}`;
|
||||
const task = await readJSON(path, signal);
|
||||
if (task.id !== id || !task.status) throw new Error("任务状态响应不完整,将自动重试");
|
||||
const [attempts, results] = await Promise.all([
|
||||
readJSON(`${path}/attempts`, signal),
|
||||
readJSON(`${path}/deployment-results`, signal),
|
||||
]);
|
||||
if (!Array.isArray(attempts.items) || !Array.isArray(results.items)) {
|
||||
throw new Error("任务执行记录响应不完整,将自动重试");
|
||||
}
|
||||
const latestAttempt = attempts.items.reduce((latest, item) =>
|
||||
!latest || item.attempt_number > latest.attempt_number ? item : latest, null);
|
||||
if (!taskIsPending(task) && latestAttempt && latestAttempt.status !== task.status) {
|
||||
throw new Error("任务记录正在更新,将重新查询一致的执行结果");
|
||||
}
|
||||
return { task, attempts: attempts.items, report: latestDeploymentReport(task, attempts.items, results.items) };
|
||||
}
|
||||
|
||||
async function poll() {
|
||||
const activeController = new AbortController();
|
||||
controller = activeController;
|
||||
const signal = activeController.signal;
|
||||
const timeout = setTimeout(() => activeController.abort(), 10000);
|
||||
const detailID = selectedID;
|
||||
const deploymentID = deploymentResult.value?.pending ? deploymentResult.value.taskID : "";
|
||||
try {
|
||||
const list = await readJSON("/api/v1/tasks?limit=20", signal);
|
||||
if (!Array.isArray(list.items)) throw new Error("任务列表响应不完整,将自动重试");
|
||||
if (stopped) return;
|
||||
const previous = new Map(tasks.value.map((item) => [item.id, item]));
|
||||
if (list.items.some((item) => previous.has(item.id) &&
|
||||
taskIsPending(previous.get(item.id)) && !taskIsPending(item))) resourcesDirty = true;
|
||||
tasks.value = list.items;
|
||||
taskQueryError.value = "";
|
||||
const ids = [...new Set([detailID, deploymentID].filter(Boolean))];
|
||||
await Promise.all(ids.map(async (id) => {
|
||||
try {
|
||||
const snapshot = await readTask(id, signal);
|
||||
if (stopped) return;
|
||||
if (selectedID === id && showTaskDetails.value) {
|
||||
taskDetails.value = snapshot.task;
|
||||
taskAttempts.value = snapshot.attempts;
|
||||
taskDeploymentReport.value = snapshot.report;
|
||||
taskDetailsError.value = "";
|
||||
}
|
||||
if (deploymentResult.value?.taskID === id) {
|
||||
if (deploymentResult.value.pending && !taskIsPending(snapshot.task)) resourcesDirty = true;
|
||||
deploymentResult.value = {
|
||||
...deploymentResult.value,
|
||||
pending: taskIsPending(snapshot.task),
|
||||
taskStatus: snapshot.task.status,
|
||||
taskMessage: snapshot.task.message || "",
|
||||
report: snapshot.report,
|
||||
queryError: "",
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
if (stopped) return;
|
||||
const denied = error.status === 401 || error.status === 403;
|
||||
const message = denied ? "当前已无权读取此任务,请联系项目管理员"
|
||||
: "暂时无法查询任务状态,将自动重试;这不代表任务失败,请勿重复提交";
|
||||
if (selectedID === id) {
|
||||
taskDetailsError.value = message;
|
||||
if (denied) {
|
||||
taskDetails.value = null;
|
||||
taskAttempts.value = [];
|
||||
taskDeploymentReport.value = null;
|
||||
}
|
||||
}
|
||||
if (deploymentResult.value?.taskID === id) {
|
||||
deploymentResult.value.queryError = message;
|
||||
if (denied) {
|
||||
deploymentResult.value.report = null;
|
||||
deploymentResult.value.taskMessage = "";
|
||||
deploymentResult.value.taskStatus = "";
|
||||
}
|
||||
}
|
||||
}
|
||||
}));
|
||||
if (!stopped && resourcesDirty && refreshResources) {
|
||||
await refreshResources(signal);
|
||||
resourcesDirty = false;
|
||||
}
|
||||
} catch (error) {
|
||||
if (!stopped) {
|
||||
if (error.status === 401 || error.status === 403) {
|
||||
tasks.value = [];
|
||||
taskDetails.value = null;
|
||||
taskAttempts.value = [];
|
||||
taskDeploymentReport.value = null;
|
||||
if (deploymentResult.value) {
|
||||
deploymentResult.value.report = null;
|
||||
deploymentResult.value.taskMessage = "";
|
||||
}
|
||||
}
|
||||
taskQueryError.value = "任务状态查询失败,将自动重试;请勿重复提交任务";
|
||||
if (selectedID === detailID && detailID) taskDetailsError.value = taskQueryError.value;
|
||||
if (deploymentID && deploymentResult.value?.taskID === deploymentID) {
|
||||
deploymentResult.value.queryError = taskQueryError.value;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
if (!stopped && selectedID === detailID) taskDetailsLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function refreshTaskStatus() {
|
||||
if (stopped) return Promise.resolve();
|
||||
if (!inFlight) inFlight = poll().finally(() => { inFlight = null; });
|
||||
return inFlight;
|
||||
}
|
||||
|
||||
async function openTaskDetails(item) {
|
||||
selectedID = item.id;
|
||||
showTaskDetails.value = true;
|
||||
taskDetails.value = null;
|
||||
taskAttempts.value = [];
|
||||
taskDeploymentReport.value = null;
|
||||
taskDetailsError.value = "";
|
||||
taskDetailsLoading.value = true;
|
||||
await refreshTaskStatus();
|
||||
// 用户切换详情时,旧请求不能覆盖新选择;等待旧查询结束后再读取新任务。
|
||||
if (!stopped && selectedID === item.id && taskDetailsLoading.value) await refreshTaskStatus();
|
||||
}
|
||||
|
||||
function closeTaskDetails() {
|
||||
selectedID = "";
|
||||
showTaskDetails.value = false;
|
||||
taskDetails.value = null;
|
||||
taskAttempts.value = [];
|
||||
taskDeploymentReport.value = null;
|
||||
taskDetailsError.value = "";
|
||||
taskDetailsLoading.value = false;
|
||||
}
|
||||
|
||||
onMounted(() => { timer = window.setInterval(refreshTaskStatus, 3000); });
|
||||
onBeforeUnmount(() => {
|
||||
stopped = true;
|
||||
window.clearInterval(timer);
|
||||
controller?.abort();
|
||||
});
|
||||
|
||||
return { taskQueryError, taskDeploymentReport, refreshTaskStatus, openTaskDetails, closeTaskDetails };
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { useDashboard } from "./Dashboard.js";
|
||||
import { latestDeploymentReport } from "./TaskMonitor.js";
|
||||
import { deploymentSummary } from "./DeploymentFeedback.js";
|
||||
import { deferred, mountComposable } from "../../test-support/mount.js";
|
||||
|
||||
const initialTask = { id: "async-task", domain_id: "domain-1", task_type: "certificate_deploy", status: "running" };
|
||||
const target = { server_id: "server-1", server: "部署目标", status: "success", attempt_number: 1 };
|
||||
|
||||
function taskFetcher(readTask, onPost = () => {}) {
|
||||
return async (path, options = {}) => {
|
||||
const task = readTask();
|
||||
if (options.method === "POST") {
|
||||
onPost(options);
|
||||
return Response.json({ task, accepted: true }, { status: 202 });
|
||||
}
|
||||
if (path === `/api/v1/tasks/${task.id}`) return Response.json(task);
|
||||
if (path.endsWith("/attempts")) return Response.json({ items: [{ attempt_number: 1, status: task.status }] });
|
||||
if (path.endsWith("/deployment-results")) return Response.json({ items: task.status === "running" ? [] : [target] });
|
||||
if (path.startsWith("/api/v1/tasks?")) return Response.json({ items: [task] });
|
||||
return Response.json({ items: [] });
|
||||
};
|
||||
}
|
||||
|
||||
test("异步部署接收后不误报成功或缺失结果,最终失败不被逐目标成功覆盖", async (t) => {
|
||||
let current = { ...initialTask };
|
||||
const posts = [];
|
||||
const { state } = await mountComposable(t, useDashboard, taskFetcher(() => current, (options) => posts.push(options)));
|
||||
await state.deployDomain({ id: "domain-1", name: "example.test" });
|
||||
assert.equal(posts.length, 1);
|
||||
assert.match(posts[0].headers["Idempotency-Key"], /^deploy-domain-1-/);
|
||||
assert.equal(state.deploymentResult.value.pending, true);
|
||||
assert.equal(state.deploymentResult.value.running, false);
|
||||
assert.equal(state.deploymentResult.value.error, "");
|
||||
assert.equal(state.deploymentResult.value.report, null);
|
||||
assert.match(state.notice.value, /任务已提交/);
|
||||
current = { ...current, status: "failed", message: "站点校验未通过" };
|
||||
await state.refreshTaskStatus();
|
||||
assert.equal(state.deploymentResult.value.pending, false);
|
||||
assert.equal(state.deploymentResult.value.taskStatus, "failed");
|
||||
assert.equal(state.deploymentResult.value.report.results[0].status, "success");
|
||||
assert.doesNotMatch(deploymentSummary(state.deploymentResult.value.report), /部署完成/);
|
||||
assert.equal(posts.length, 1);
|
||||
});
|
||||
|
||||
test("刷新页面从持久化任务恢复详情,关闭结果窗口不取消任务", async (t) => {
|
||||
let current = { ...initialTask };
|
||||
const { state } = await mountComposable(t, useDashboard, taskFetcher(() => current));
|
||||
assert.equal(state.tasks.value[0].id, current.id);
|
||||
await state.openTaskDetails(current);
|
||||
assert.equal(state.taskDetails.value.status, "running");
|
||||
state.deploymentResult.value = null;
|
||||
current = { ...current, status: "success", message: "证书部署成功" };
|
||||
await state.refreshTaskStatus();
|
||||
assert.equal(state.taskDetails.value.status, "success");
|
||||
assert.equal(state.taskDeploymentReport.value.results.length, 1);
|
||||
state.closeTaskDetails();
|
||||
assert.equal(state.taskDetails.value, null);
|
||||
});
|
||||
|
||||
test("部署结果只汇总最新尝试,不混用上一次失败或伪造站点验证", () => {
|
||||
const task = { ...initialTask, status: "success" };
|
||||
const attempts = [{ attempt_number: 1 }, { attempt_number: 2 }];
|
||||
const report = latestDeploymentReport(task, attempts, [
|
||||
{ ...target, status: "failed" }, { ...target, attempt_number: 2 },
|
||||
]);
|
||||
assert.equal(report.total, 1);
|
||||
assert.equal(report.failed, 0);
|
||||
assert.equal(report.verification_status, undefined);
|
||||
assert.equal(latestDeploymentReport(task, attempts, [target]), null);
|
||||
assert.equal(latestDeploymentReport(initialTask, attempts, [target]), null);
|
||||
});
|
||||
|
||||
test("状态查询断线保留后台任务,恢复后继续读取且不会再次提交", async (t) => {
|
||||
let unavailable = false;
|
||||
let posts = 0;
|
||||
const fetchTask = taskFetcher(() => initialTask, () => { posts += 1; });
|
||||
const { state } = await mountComposable(t, useDashboard, (path, options) => {
|
||||
if (unavailable && path.startsWith("/api/v1/tasks")) return Promise.reject(new Error("连接中断"));
|
||||
return fetchTask(path, options);
|
||||
});
|
||||
await state.deployDomain({ id: "domain-1", name: "example.test" });
|
||||
unavailable = true;
|
||||
await state.refreshTaskStatus();
|
||||
assert.equal(state.deploymentResult.value.pending, true);
|
||||
assert.equal(state.deploymentResult.value.taskStatus, "running");
|
||||
assert.match(state.deploymentResult.value.queryError, /勿重复提交/);
|
||||
unavailable = false;
|
||||
await state.refreshTaskStatus();
|
||||
assert.equal(state.deploymentResult.value.queryError, "");
|
||||
assert.equal(posts, 1);
|
||||
});
|
||||
|
||||
test("任务轮询不重叠,卸载取消在途查询并停止计时器", async (t) => {
|
||||
let block = false;
|
||||
let requests = 0;
|
||||
let aborted = false;
|
||||
const fetchTask = taskFetcher(() => initialTask);
|
||||
const { state, unmount, runIntervals } = await mountComposable(t, useDashboard, (path, options) => {
|
||||
if (block && path.startsWith("/api/v1/tasks?")) {
|
||||
requests += 1;
|
||||
return new Promise((resolve, reject) => {
|
||||
options.signal.addEventListener("abort", () => { aborted = true; reject(new Error("已停止查询")); });
|
||||
});
|
||||
}
|
||||
return fetchTask(path, options);
|
||||
});
|
||||
block = true;
|
||||
const pending = state.refreshTaskStatus();
|
||||
runIntervals();
|
||||
runIntervals();
|
||||
assert.equal(requests, 1);
|
||||
unmount();
|
||||
await pending;
|
||||
runIntervals();
|
||||
assert.equal(aborted, true);
|
||||
assert.equal(requests, 1);
|
||||
assert.equal(state.taskQueryError.value, "");
|
||||
});
|
||||
|
||||
test("切换详情时迟到请求不能覆盖新任务", async (t) => {
|
||||
const delayed = deferred();
|
||||
let blocked = true;
|
||||
const fetchTask = taskFetcher(() => initialTask);
|
||||
const { state } = await mountComposable(t, useDashboard, async (path, options) => {
|
||||
if (path === "/api/v1/tasks/first" && blocked) return delayed.promise;
|
||||
if (path === "/api/v1/tasks/second") return Response.json({ ...initialTask, id: "second" });
|
||||
return fetchTask(path, options);
|
||||
});
|
||||
const first = state.openTaskDetails({ id: "first" });
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
const second = state.openTaskDetails({ id: "second" });
|
||||
blocked = false;
|
||||
delayed.resolve(Response.json({ ...initialTask, id: "first" }));
|
||||
await Promise.all([first, second]);
|
||||
assert.equal(state.taskDetails.value.id, "second");
|
||||
assert.equal(state.taskDetailsLoading.value, false);
|
||||
});
|
||||
|
||||
test("异步取消与重试只提示请求已接收,不提前宣布终态", async (t) => {
|
||||
const fetchTask = taskFetcher(() => initialTask);
|
||||
const { state } = await mountComposable(t, useDashboard, (path, options = {}) => {
|
||||
if (options.method === "DELETE") return Response.json({ task: { ...initialTask, status: "cancelling" } }, { status: 202 });
|
||||
return fetchTask(path, options);
|
||||
});
|
||||
window.confirm = () => true;
|
||||
await state.cancelTask(initialTask);
|
||||
assert.match(state.notice.value, /等待任务停止和部署收尾/);
|
||||
assert.doesNotMatch(state.notice.value, /任务已取消/);
|
||||
await state.retryTask({ ...initialTask, status: "failed" });
|
||||
assert.match(state.notice.value, /重试已提交/);
|
||||
assert.doesNotMatch(state.notice.value, /已重新执行/);
|
||||
});
|
||||
|
||||
test("代理返回非 JSON 时保留原状态,不泄露 HTML 或误报完成", async (t) => {
|
||||
let invalid = false;
|
||||
const fetchTask = taskFetcher(() => initialTask);
|
||||
const { state } = await mountComposable(t, useDashboard, (path, options) => {
|
||||
if (invalid && path.startsWith("/api/v1/tasks/")) return Promise.resolve(new Response("<html>504</html>", { status: 504 }));
|
||||
return fetchTask(path, options);
|
||||
});
|
||||
await state.openTaskDetails(initialTask);
|
||||
invalid = true;
|
||||
await state.refreshTaskStatus();
|
||||
assert.equal(state.taskDetails.value.status, "running");
|
||||
assert.match(state.taskDetailsError.value, /不代表任务失败/);
|
||||
assert.doesNotMatch(state.taskDetailsError.value, /<html>|Unexpected/);
|
||||
});
|
||||
|
||||
test("任务与尝试读取遇到并发重试时不混用旧终态和新结果", async (t) => {
|
||||
let retrying = false;
|
||||
const current = { ...initialTask, status: "success" };
|
||||
const fetchTask = taskFetcher(() => current);
|
||||
const { state } = await mountComposable(t, useDashboard, (path, options) => {
|
||||
if (retrying && path.endsWith("/attempts")) {
|
||||
return Promise.resolve(Response.json({ items: [{ attempt_number: 2, status: "running" }] }));
|
||||
}
|
||||
return fetchTask(path, options);
|
||||
});
|
||||
await state.openTaskDetails(current);
|
||||
retrying = true;
|
||||
await state.refreshTaskStatus();
|
||||
assert.match(state.taskDetailsError.value, /暂时无法查询/);
|
||||
assert.equal(state.taskAttempts.value[0].attempt_number, 1);
|
||||
});
|
||||
|
||||
test("项目撤权后清除缓存的任务详情和部署结果", async (t) => {
|
||||
let denied = false;
|
||||
const current = { ...initialTask, status: "success" };
|
||||
const fetchTask = taskFetcher(() => current);
|
||||
const { state } = await mountComposable(t, useDashboard, (path, options) => {
|
||||
if (denied && path.startsWith("/api/v1/tasks/")) {
|
||||
return Promise.resolve(Response.json({ error: "无权访问此任务" }, { status: 403 }));
|
||||
}
|
||||
return fetchTask(path, options);
|
||||
});
|
||||
await state.openTaskDetails(current);
|
||||
assert.equal(state.taskDeploymentReport.value.results.length, 1);
|
||||
denied = true;
|
||||
await state.refreshTaskStatus();
|
||||
assert.equal(state.taskDetails.value, null);
|
||||
assert.equal(state.taskDeploymentReport.value, null);
|
||||
assert.deepEqual(state.taskAttempts.value, []);
|
||||
assert.match(state.taskDetailsError.value, /无权读取/);
|
||||
});
|
||||
|
||||
test("任务完成后自动刷新域名证书数据,但不覆盖正在编辑的设置", async (t) => {
|
||||
let current = { ...initialTask };
|
||||
let resourceReads = 0;
|
||||
const fetchTask = taskFetcher(() => current);
|
||||
const { state } = await mountComposable(t, useDashboard, (path, options) => {
|
||||
if (path === "/api/v1/domains") {
|
||||
resourceReads += 1;
|
||||
return Promise.resolve(Response.json({ items: [{ id: "domain-1", status: current.status === "success" ? "active" : "pending" }] }));
|
||||
}
|
||||
return fetchTask(path, options);
|
||||
});
|
||||
state.settingsForm.value.notification.sender_name = "正在编辑的名称";
|
||||
assert.equal(state.domains.value[0].status, "pending");
|
||||
current = { ...current, status: "success" };
|
||||
await state.refreshTaskStatus();
|
||||
assert.equal(state.domains.value[0].status, "active");
|
||||
assert.equal(state.settingsForm.value.notification.sender_name, "正在编辑的名称");
|
||||
assert.equal(resourceReads, 2);
|
||||
});
|
||||
Reference in new issue
Block a user