64 lines
1.9 KiB
TypeScript
64 lines
1.9 KiB
TypeScript
const API_TAG = "SSE-API";
|
|
function apiLog(msg: string) {
|
|
const t = new Date().toISOString().slice(0, 19).replace("T", " ");
|
|
console.log(`[${t}] [${API_TAG}] ${msg}`);
|
|
}
|
|
function apiErr(msg: string) {
|
|
const t = new Date().toISOString().slice(0, 19).replace("T", " ");
|
|
console.error(`[${t}] [${API_TAG}] ${msg}`);
|
|
}
|
|
|
|
import { executeUpdate } from "@/lib/update";
|
|
|
|
// POST /api/update/execute - 执行容器更新(SSE 流式输出日志)
|
|
export async function POST() {
|
|
const encoder = new TextEncoder();
|
|
|
|
apiLog("收到更新请求,创建 SSE 流");
|
|
|
|
const stream = new ReadableStream({
|
|
async start(controller) {
|
|
// 发送日志的辅助函数
|
|
const sendLog = (message: string) => {
|
|
const data = JSON.stringify({ log: message });
|
|
controller.enqueue(encoder.encode(`data: ${data}\n\n`));
|
|
};
|
|
|
|
try {
|
|
apiLog("开始执行 executeUpdate...");
|
|
const result = await executeUpdate(sendLog);
|
|
|
|
apiLog(`executeUpdate 完成: success=${result.success}, message="${result.message}"`);
|
|
|
|
// 发送最终结果
|
|
const finalData = JSON.stringify({
|
|
done: true,
|
|
success: result.success,
|
|
message: result.message,
|
|
});
|
|
controller.enqueue(encoder.encode(`data: ${finalData}\n\n`));
|
|
} catch (error) {
|
|
const errMsg =
|
|
error instanceof Error ? error.message : "未知错误";
|
|
apiErr(`SSE 流异常: ${errMsg}`);
|
|
controller.enqueue(
|
|
encoder.encode(
|
|
`data: ${JSON.stringify({ done: true, success: false, message: errMsg })}\n\n`
|
|
)
|
|
);
|
|
} finally {
|
|
apiLog("关闭 SSE 流");
|
|
controller.close();
|
|
}
|
|
},
|
|
});
|
|
|
|
return new Response(stream, {
|
|
headers: {
|
|
"Content-Type": "text/event-stream",
|
|
"Cache-Control": "no-cache",
|
|
Connection: "keep-alive",
|
|
},
|
|
});
|
|
}
|