Spaces:
Sleeping
Sleeping
File size: 7,069 Bytes
476094d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 | import { spawn } from "node:child_process";
import net from "node:net";
import path from "node:path";
import {
buildCliArgs,
buildCommandPreview,
getToolDefinition,
sanitizeParams,
} from "./tool-registry.mjs";
const REPO_ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", "..");
const MAX_LOG_ENTRIES = 800;
function nowIso() {
return new Date().toISOString();
}
async function checkPortAvailable(host, port) {
return new Promise((resolve, reject) => {
const server = net.createServer();
server.once("error", (error) => {
server.close(() => reject(error));
});
server.once("listening", () => {
server.close(() => resolve(true));
});
server.listen(port, host);
});
}
async function safeJson(response) {
try {
return await response.json();
} catch {
return null;
}
}
export class ApiPoolProxyManager {
constructor(historyStore) {
this.historyStore = historyStore;
this.child = null;
this.state = {
running: false,
pid: null,
startedAt: null,
stopRequestedAt: null,
lastExitCode: null,
params: null,
commandPreview: null,
recentLogs: [],
};
}
appendLog(stream, chunk) {
const normalized = String(chunk || "").replace(/\r\n/g, "\n");
const pieces = normalized.split("\n");
for (const piece of pieces) {
if (!piece) continue;
this.state.recentLogs.push({
timestamp: nowIso(),
stream,
text: piece,
});
}
if (this.state.recentLogs.length > MAX_LOG_ENTRIES) {
this.state.recentLogs.splice(0, this.state.recentLogs.length - MAX_LOG_ENTRIES);
}
}
async start(rawParams = {}) {
if (this.child && this.state.running) {
return { reused: true, status: await this.getStatus() };
}
const tool = getToolDefinition("api-pool.start");
const params = sanitizeParams(tool, rawParams);
try {
await checkPortAvailable(params.host, params.port);
} catch (error) {
const message =
error?.code === "EADDRINUSE"
? `端口 ${params.host}:${params.port} 已被占用,请更换 API 池代理端口或先停止已有进程。`
: `无法绑定 ${params.host}:${params.port}:${error?.message || String(error)}`;
const wrapped = new Error(message);
wrapped.statusCode = 409;
throw wrapped;
}
const childEnv = { ...process.env };
if (params.proxyUrl) {
childEnv.CODEX_PROXY_BOOTSTRAPPED = "1";
childEnv.NODE_USE_ENV_PROXY = "1";
childEnv.HTTPS_PROXY = params.proxyUrl;
childEnv.HTTP_PROXY = params.proxyUrl;
childEnv.ALL_PROXY = params.proxyUrl;
}
const child = spawn(tool.command, buildCliArgs(tool, params), {
cwd: REPO_ROOT,
env: childEnv,
stdio: ["ignore", "pipe", "pipe"],
});
this.child = child;
this.state = {
running: true,
pid: child.pid,
startedAt: nowIso(),
stopRequestedAt: null,
lastExitCode: null,
params,
commandPreview: buildCommandPreview(tool, params, {
hiddenFields: ["localApiKey"],
}),
recentLogs: [],
};
this.appendLog("stdout", `启动 API 池代理进程 PID=${child.pid}`);
child.stdout.on("data", (chunk) => {
this.appendLog("stdout", chunk.toString("utf8"));
});
child.stderr.on("data", (chunk) => {
this.appendLog("stderr", chunk.toString("utf8"));
});
child.on("error", async (error) => {
this.appendLog("stderr", error?.message || String(error));
this.state.running = false;
this.state.pid = null;
this.state.lastExitCode = 1;
await this.historyStore.add({
id: `api-pool-start-${Date.now()}`,
toolId: "api-pool.start",
status: "failed",
exitCode: 1,
createdAt: this.state.startedAt,
startedAt: this.state.startedAt,
finishedAt: nowIso(),
commandPreview: this.state.commandPreview,
paramsSummary: `provider=${params.provider}, 监听 ${params.host}:${params.port}`,
});
});
child.on("close", async (code) => {
this.state.running = false;
this.state.pid = null;
this.state.lastExitCode = code ?? 1;
this.appendLog("stdout", `API 池代理进程已退出,exitCode=${this.state.lastExitCode}`);
await this.historyStore.add({
id: `api-pool-start-${Date.now()}`,
toolId: "api-pool.start",
status: this.state.lastExitCode === 0 ? "succeeded" : "failed",
exitCode: this.state.lastExitCode,
createdAt: this.state.startedAt,
startedAt: this.state.startedAt,
finishedAt: nowIso(),
commandPreview: this.state.commandPreview,
paramsSummary: `provider=${params.provider}, 监听 ${params.host}:${params.port}`,
});
this.child = null;
});
return { reused: false, status: await this.getStatus() };
}
async stop() {
if (!this.child || !this.state.running) {
return { stopped: false, status: await this.getStatus() };
}
this.state.stopRequestedAt = nowIso();
this.appendLog("stdout", "收到停止请求,准备关闭 API 池代理进程");
const child = this.child;
child.kill("SIGTERM");
await new Promise((resolve) => {
const timeout = setTimeout(() => {
if (this.child && this.state.running) {
this.appendLog("stderr", "SIGTERM 超时,改用 SIGKILL");
this.child.kill("SIGKILL");
}
}, 3000);
child.once("close", () => {
clearTimeout(timeout);
resolve();
});
});
return { stopped: true, status: await this.getStatus() };
}
async fetchHealth() {
if (!this.state.params) return null;
const { host, port } = this.state.params;
try {
const response = await fetch(`http://${host}:${port}/healthz`);
return {
ok: response.ok,
status: response.status,
body: await safeJson(response),
};
} catch (error) {
return {
ok: false,
status: 0,
error: error?.message || String(error),
};
}
}
async fetchProxyStatus() {
if (!this.state.params) return null;
const { host, port, localApiKey } = this.state.params;
try {
const response = await fetch(`http://${host}:${port}/proxy/status`, {
headers: {
authorization: `Bearer ${localApiKey}`,
},
});
return {
ok: response.ok,
status: response.status,
body: await safeJson(response),
};
} catch (error) {
return {
ok: false,
status: 0,
error: error?.message || String(error),
};
}
}
async getStatus() {
return {
...this.state,
endpoint:
this.state.params && this.state.params.host && this.state.params.port
? `http://${this.state.params.host}:${this.state.params.port}`
: null,
health: await this.fetchHealth(),
proxyStatus: await this.fetchProxyStatus(),
};
}
}
|