Files
37duAutomation/desktop/electron-shell/electron/cpclient.js
T

134 lines
3.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 中心机 REST 客户端:_cp_call 等价(头规则一致、超时、错误透传 detail)。
"use strict";
const { makeLogger } = require("./logger");
const config = require("./config");
const logger = makeLogger("cpclient");
class HttpError extends Error {
constructor(status, detail) {
super(typeof detail === "string" && detail ? detail : `中心机 ${status}`);
this.status = status;
this.detail = detail;
}
}
function baseUrl() {
if (!config.CONTROLPLANE_URL) {
const err = new Error("统一后端未配置(CONTROLPLANE_URL)");
err.status = 503;
throw err;
}
return config.CONTROLPLANE_URL;
}
// 机器凭证头(X-API-Token)
function machineHeaders() {
const h = {};
if (config.CONTROLPLANE_TOKEN) h["X-API-Token"] = config.CONTROLPLANE_TOKEN;
return h;
}
// params: {a: 1} → query string
function qs(params) {
if (!params) return "";
const parts = Object.entries(params)
.filter(([, v]) => v !== undefined && v !== null)
.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`);
return parts.length ? `?${parts.join("&")}` : "";
}
async function request(method, urlPath, opts = {}) {
const { headers = {}, json, params, body, timeout = 30, raw = false } = opts;
const url = `${baseUrl()}${urlPath}${qs(params)}`;
const h = { ...headers };
let payload;
if (json !== undefined) {
h["Content-Type"] = "application/json";
payload = JSON.stringify(json);
} else if (body !== undefined) {
payload = body;
}
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), timeout * 1000);
let res;
try {
res = await fetch(url, {
method,
headers: h,
body: payload,
signal: ctrl.signal,
redirect: "follow",
});
} catch (e) {
const err = new Error(`中心机不可达: ${e.message}`);
err.status = 502;
throw err;
} finally {
clearTimeout(timer);
}
const buf = Buffer.from(await res.arrayBuffer());
if (res.status >= 400) {
let detail = buf.toString("utf-8").slice(0, 300);
try {
detail = JSON.parse(detail).detail || detail;
} catch (e) {
/* 非 JSON 错误体 */
}
throw new HttpError(res.status, detail);
}
if (raw) {
return { status: res.status, headers: res.headers, body: buf };
}
// JSON(二进制接口用 raw)
const text = buf.toString("utf-8");
try {
return JSON.parse(text);
} catch (e) {
return { detail: text.slice(0, 300) };
}
}
// 流式下载(shell/chrome 大包,带进度回调):返回 {status, sha, contentLength}
async function streamDownload(urlPath, opts = {}) {
const { headers = {}, timeout = 600, onProgress, onData } = opts;
const url = `${baseUrl()}${urlPath}`;
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), timeout * 1000);
let res;
try {
res = await fetch(url, { headers, signal: ctrl.signal, redirect: "follow" });
} catch (e) {
clearTimeout(timer);
const err = new Error(`下载失败: ${e.message}`);
err.status = 502;
throw err;
}
const crypto = require("crypto");
const sha = crypto.createHash("sha256");
const total = parseInt(res.headers.get("content-length") || "0", 10);
let received = 0;
const reader = res.body.getReader();
try {
for (;;) {
const { done, value } = await reader.read();
if (done) break;
sha.update(value);
received += value.length;
if (onData) onData(value);
if (onProgress) onProgress(received, total);
}
} catch (e) {
throw new Error(`下载中断: ${e.message}`);
} finally {
clearTimeout(timer);
}
if (res.status >= 400) {
throw new HttpError(res.status, `下载失败 HTTP ${res.status}`);
}
return { status: res.status, sha256: sha.digest("hex"), contentLength: total, received };
}
module.exports = { HttpError, request, machineHeaders, qs, streamDownload, baseUrl };